webpack4之Tree Shaking配置


Tree Shaking

针对有些ESmodule引入的文件里,有些方法在项目里是没有用到的,那打包的时候就可以将这些方法去掉。

配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// index.js
import './index.css' // 因为没有使用exports,所以Tree Shaking会忽略这个,要再package.json设置
import { add } from './index1.js'
add(1,2)

// webpack.config.js
module.exports = {
mode: 'production', // 对development不生效
devtool: 'cheap-module-eval-source-map',
entry: {
index1: './index.js'
},
module: {
rules: [{
test: /\.(css)$/,
use: ['style-loader', 'css-loader', 'postcss-loader']
}],
},
plugins: [new HtmlWebpackPlugin({
template: './index.html'
}), new CleanWebpackPlugin()
],
optimization: {
usedExports: true // 哪些使用的exports进行打包
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'sef')
}
}

// package.json
{
"name": "webpack-demo",
"sideEffects": ['*.css*'], // 设置这项,import './index.css'不会被忽略
"version": "1.0.0",
"description": "",
"main": "index.js",
}