代码拆分
- 原理:将大的代码文件拆分成多个小的文件,使得浏览器可以按需加载,减少初始加载时间。
- 实现方式:
- 动态导入:在ES6模块中使用
import()
语法进行动态导入。例如在importComponent.js
文件中:
// importComponent.js
export const loadComponent = () => import('./MyComponent.js');
- Webpack配置:在
webpack.config.js
中,使用splitChunks
插件来配置代码拆分。
module.exports = {
//...其他配置
optimization: {
splitChunks: {
chunks: 'all',
minSize: 30000,
minChunks: 1,
maxAsyncRequests: 5,
maxInitialRequests: 3,
automaticNameDelimiter: '~',
name: true,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
}
};
缓存策略
- 原理:通过缓存已处理过的模块,减少重复计算,提升打包速度。
- 实现方式:
- Webpack缓存:在
webpack.config.js
中启用缓存。
module.exports = {
//...其他配置
cache: {
type: 'filesystem',
buildDependencies: {
config: [__filename]
}
}
};
- 浏览器缓存:设置HTTP缓存头,让浏览器缓存静态资源。例如在服务器配置中设置:
// Node.js Express服务器示例
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.set('Cache - Control','public, max - age = 31536000'); // 一年的缓存时间
next();
});
//...其他服务器配置
多进程构建
- 原理:利用多核CPU的优势,并行处理任务,加快构建速度。
- 实现方式:
- 使用
thread-loader
:安装thread-loader
,在webpack.config.js
中配置。
module.exports = {
//...其他配置
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
'thread-loader',
{
loader: 'babel-loader',
options: {
presets: ['@babel/preset - env']
}
}
]
}
]
}
};
- 使用
parallel - webpack
:安装parallel - webpack
,在package.json
的scripts
中配置:
{
"scripts": {
"build": "parallel - webpack --config webpack.config.js"
}
}