webpack 2 实践系列(二)— entry 和 output

源码地址:https://github.com/silence717/webpack2-demos

具体可参见 demo02-entry-output 目录下

Entry Points

entry是webpack配置的入口文件的属性,也是整个项目的主入口,其余依赖的模块均在这个文件中引入。
使用方式:entry: string | Array

Output

输出选项告诉webpack如何编写编译后的文件到磁盘。虽然可以有多个入口,但是只要一个输出配置项。
下面列举几个最主要的配置属性:

path

打包后的输出目录地址,是绝对路径。

1
2
3
output: {
path: __dirname + '/'
}

publicPath

正在研究当中,目前遇到一个dev和build环境image路径的问题,晚点具体补充。

fileName

fileName – 指定输出文件的名称

1
2
3
output: {
filename: 'bundle.js'
}

单个entry和 output 配置

webpacl.config.js

1
2
3
4
5
6
7
module.exports = {
entry: './index.js',
output: {
filename: 'bundle.js',
path: __dirname + '/'
}
};

如果能够保证当前项目只有一个入口,我们还可以简写为:

1
2
3
4
5
6
7
8
9
module.exports = {
entry: {
main: './index.js'
},
output: {
filename: 'bundle.js',
path: __dirname + '/'
}
};

单个入口配置参照: demo02-entry-output/single 目录下

多个entry 和对于 output

如果我们配置了多个入口那么应该使用提花布,确保每个文件有一个唯一的名称:

  • [name] is replaced by the name of the chunk.
  • [hash] is replaced by the hash of the compilation.
  • [chunkhash] is replaced by the hash of the chunk.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    module.exports = {
    entry: {
    indexOne: './indexOne.js',
    indexTwo: './indexTwo.js'
    },
    output: {
    // filename: '[hash].bundle.js',
    filename: '[name].bundle.js',
    path: __dirname + '/'
    }
    };

多个入口配置参照: demo02-entry-output/multi 目录下

杨芳<br>前端一枚<br>背包客,热爱旅行,喜欢摄影<br>轻微洁癖,强迫症,电话恐惧症患者!