前言
随着前端技术的发展,前端项目越来越复杂,对打包工具的性能要求也越来越高。webpack 作为目前最流行的前端打包工具,其性能优化也成为了前端开发者必须掌握的技能之一。
本文将介绍一些 webpack 性能优化的实践记录,希望能够对大家有所帮助。
1. 使用 DLLPlugin
使用 DLLPlugin 可以将一些基本不会变的库提前打包成静态文件,避免每次打包都重新编译这些库,从而提高打包速度。
示例代码:
// www.javascriptcn.com code example
// webpack.config.js
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: {
vendor: ['react', 'react-dom', 'lodash'],
app: './src/index.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack.DllPlugin({
name: '[name]',
path: path.join(__dirname, 'dist', '[name]-manifest.json')
})
]
};// www.javascriptcn.com code example
// webpack.config.prod.js
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: {
app: './src/index.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack.DllReferencePlugin({
manifest: require('./dist/vendor-manifest.json')
})
]
};2. 使用 HappyPack
HappyPack 可以将模块的解析和编译过程并行化,从而提高打包速度。
示例代码:
// www.javascriptcn.com code example
// webpack.config.js
const HappyPack = require('happypack');
const os = require('os');
module.exports = {
module: {
rules: [
{
test: /\.js$/,
use: 'happypack/loader?id=js',
exclude: /node_modules/
}
]
},
plugins: [
new HappyPack({
id: 'js',
threads: os.cpus().length,
loaders: ['babel-loader']
})
]
};3. 使用 ParallelUglifyPlugin
ParallelUglifyPlugin 可以将代码压缩并行化,从而提高打包速度。
示例代码:
// www.javascriptcn.com code example
// webpack.config.prod.js
const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin');
module.exports = {
plugins: [
new ParallelUglifyPlugin({
uglifyJS: {
output: {
beautify: false,
comments: false
},
compress: {
warnings: false,
drop_console: true,
collapse_vars: true,
reduce_vars: true
}
}
})
]
};4. 使用 Tree Shaking
Tree Shaking 可以消除无用的代码,从而减小打包文件的体积。
示例代码:
// www.javascriptcn.com code example
// webpack.config.js
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: __dirname + '/dist'
},
optimization: {
usedExports: true
}
};// src/index.js
import { add } from './math.js';
console.log(add(1, 2));// src/math.js
export function add(a, b) {
return a + b;
}
export function minus(a, b) {
return a - b;
}5. 使用 Code Splitting
Code Splitting 可以将代码分割成不同的文件,从而减小打包文件的体积。
示例代码:
// www.javascriptcn.com code example
// webpack.config.js
module.exports = {
mode: 'production',
entry: {
app: './src/index.js',
vendor: ['react', 'react-dom']
},
output: {
filename: '[name].js',
path: __dirname + '/dist'
},
optimization: {
splitChunks: {
chunks: 'all'
}
}
};结语
以上是一些 webpack 性能优化的实践记录,希望对大家有所帮助。当然,这些并不是全部,还有很多其他的优化方法,需要根据实际情况进行调整。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d53501a941bf713499db02