webpack4基本配置文件


webpack.config.js

没有webpack.config.js文件,会使用默认的配置文件
1
npx webapack index.js
webpack.config.js基本配置
1
2
3
4
5
6
7
8
9
10
11
const path = require('path')
module.exports = {
entry: './index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'sef') // path是绝对路径, path.resolve(__dirname指的是webpack所在的当前路径
}
}

// 打包:
npx webpack
package.json设置打包命令
1
2
3
"scripts": {
"bundle": "webpack" // 执行node-module里的webpack,npm run bundle等价于npx webpack
},
webpack.config.js省略部分配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 打包出终端显示信息
Hash: 5a6e95c2982789aadabc
Version: webpack 4.41.0
Time: 298ms
Built at: 2019-10-04 17:39:14
Asset Size Chunks Chunk Names
bundle.js 1.17 KiB 0 [emitted] main
Entrypoint main = bundle.js

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.

// webpack.config.js
const path = require('path')
module.exports = {
mode: 'development', // WARNING in configuration警告原因,是因为没写mode,mode为production打包出的bundle.js为一行代码,为development为多行
entry: {
main: './index.js' // 这就是Chunk Names, Chunk为唯一id
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'sef')
}
}
修改文件名

webpack的默认配置文件为webpack.config.js,假如要修改名字,需要修改配置指向

1
npx webpack --config webpackConfig1.js
多入口文件

有时候需要将入口文件分为2个以上

1
2
3
4
5
6
7
8
9
10
11
// webpack.config.js
module.exports = {
entry: {
index1: './index.js',
index2: './index1.js'
},
output: {
filename: '[name].js', // 此处的name为entry的key,所以打包后的文件名为index1.js, index2.js
path: path.resolve(__dirname, 'sef')
}
}
导出的文件上传到cdn等服务器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// webpack.config.js
module.exports = {
entry: {
index1: './index.js',
index2: './index1.js'
},
plugins: [new HtmlWebpackPlugin({
template: './index.html'
}), new CleanWebpackPlugin()],
output: {
publicPath: 'http://www.cdn.com', // <script type="text/javascript" src="http://www.cdn.com/index1.js"></script>
filename: '[name].js',
path: path.resolve(__dirname, 'sef')
}
}