一、代码分割
代码分割能够将代码分成多个块,按需加载,从而提高加载速度和性能。Webpack通过import()
函数或require.ensure()
实现代码分割。
// 使用import()函数实现代码分割
import('./math').then(math => {
console.log(math.add(16, 26));
});
// 使用require.ensure()实现代码分割
require.ensure(['./math'], function(require) {
const math = require('./math');
console.log(math.add(16, 26));
});
使用webpack-bundle-analyzer
工具可以分析代码分割后的模块组成,从而优化代码分割策略。
二、Tree Shaking
Tree Shaking是指删除没有使用的代码,从而减小打包后的代码体积。开启Tree Shaking需要ES6的模块引入方式,并在webpack配置文件中开启压缩模式。
// math.js
export function add(a, b) {
return a + b;
}
export function square(a) {
return a * a;
}
// app.js
import { add } from './math';
console.log(add(16, 26));
三、懒加载
懒加载能够将页面划分成多个区域,在需要加载时再请求资源,提高了初始加载速度和性能。Webpack可以使用动态import
语法实现懒加载。
// 使用动态import语法实现懒加载
document.getElementById('btn').addEventListener('click', () => {
import('./lazy-loaded-module').then(module => {
// 使用模块
});
});
四、缓存
使用合理的缓存策略能够减少网络请求,提升性能。Webpack通过output.filename
属性设置文件名,通过output.chunkFilename
属性设置代码分割后的文件名。
// webpack.config.js
output: {
filename: '[name].[contenthash].js',
chunkFilename: '[name].[contenthash].js'
}
五、优化Loader
Webpack的Loader是打包过程中用于处理文件的转换器。优化Loader可以减小打包时间和提高性能。以下是一些优化Loader的方法:
1、使用include/exclude
设置匹配规则
module.exports = {
module: {
rules: [
{
test: /\.js$/,
include: [
path.resolve(__dirname, 'src')
],
exclude: [
path.resolve(__dirname, 'node_modules')
],
loader: 'babel-loader'
}
]
}
};
2、尽可能使用Loader默认配置
module.exports = {
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader'
}
]
}
};
3、尽可能使用最小化的Loader
module.exports = {
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
// 尽可能使用最小化的babel-preset-env
presets: [['env', { modules: false }]]
}
}
}
]
}
};
4、使用HappyPack并行处理Loader
const HappyPack = require('happypack');
module.exports = {
module: {
rules: [
{
test: /\.js$/,
use: 'happypack/loader?id=js'
}
]
},
plugins: [
new HappyPack({
id: 'js',
threads: 4,
loaders: ['babel-loader']
})
]
};
5、使用缓存Loader结果
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
module.exports = {
plugins: [
new HardSourceWebpackPlugin()
]
};
六、优化Resolve
使用优化路径解析的Resolve配置项能够减少查找时间,提高性能。并通过extensions
配置项减小文件查找范围。
module.exports = {
resolve: {
// 配置别名,避免路径深度影响性能
alias: {
'@': path.resolve(__dirname, 'src')
},
// 配置查找模块的路径,避免查找时间过长
modules: [path.resolve(__dirname, 'src'), 'node_modules'],
// 启用了扩展名的查找
extensions: ['.js', '.json']
}
};
七、优化DevServer
使用Webpack DevServer能够提高开发效率和性能。以下方法可以优化DevServer:
1、利用内存减少IO操作
module.exports = {
devServer: {
// 解决多页面刷新导致重新构建所有文件的问题
lazy: false,
// 将资源放入内存中,减少IO操作
contentBase: false
}
};
2、开启Gzip压缩
const CompressionPlugin = require('compression-webpack-plugin');
module.exports = {
plugins: [
new CompressionPlugin()
]
};
3、使用Hot Module Replacement(HMR)
module.exports = {
devServer: {
// 开启HMR
hot: true
},
plugins: [
// Webpack内置的HMR插件
new webpack.HotModuleReplacementPlugin()
]
};
八、使用优化后的Loader和插件
以下是一些常见Loader和插件的优化:
1、babel-loader优化
使用babel-loader
的cacheDirectory
选项可以启用缓存,减小编译时间。
module.exports = {
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true
}
}
]
}
]
}
};
2、css-loader和style-loader优化
使用mini-css-extract-plugin
插件可以把CSS提取成单独的文件,减少JavaScript文件体积,提升加载速度。
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
// 开启HMR
hmr: true,
// 如果模块是HMR能够更新的,将导出到CSS否则将创建一个新的样式唯一URL
reloadAll: true
}
},
'css-loader'
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css'
})
]
};
3、html-webpack-plugin优化
使用html-webpack-plugin
的template
选项可以指定HTML模板路径,从而减小编译速度。
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
]
};
4、UglifyJsPlugin优化
使用terser-webpack-plugin
代替UglifyJsPlugin
,可以提高压缩速度和缩小代码大小。
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
optimization: {
minimizer: [
new TerserPlugin({
cache: true,
parallel: true,
sourceMap: true // 必须启用,否则将影响调试
})
]
}
};