"- 使用Webpack的Tree Shaking功能
// webpack.config.js
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
//...
optimization: {
minimizer: [new TerserPlugin()],
},
};
- 压缩代码
// webpack.config.js
module.exports = {
mode: 'production',
optimization: {
minimize: true,
},
};
- 按需加载
// 使用动态import语法
const button = document.getElementById('button');
button.addEventListener('click', () => {
import('./module').then(module => {
module.default();
});
});
- 使用SplitChunksPlugin拆分代码
// webpack.config.js
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
},
},
};
- 移除不必要的插件和loader
- 使用DLLPlugin和DllReferencePlugin预编译依赖模块
- 使用externals配置外部依赖
// webpack.config.js
module.exports = {
externals: {
lodash: '_',
},
};
- 使用Source Map只在开发环境开启
// webpack.config.js
module.exports = {
devtool: 'source-map',
};
- 使用PurgeCSSPlugin清除无用的CSS
// webpack.config.js
const PurgeCSSPlugin = require('purgecss-webpack-plugin');
const glob = require('glob');
module.exports = {
plugins: [
new PurgeCSSPlugin({
paths: glob.sync('src/**/*.js', { nodir: true }),
}),
],
};
- 使用MiniCssExtractPlugin提取CSS到单独文件
// webpack.config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
module: {
rules: [
{
test: /\\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
],
},
plugins: [
new MiniCssExtractPlugin(),
],
};
```"