1、生产环境压缩代码:在生产环境中,使用 UglifyJSPlugin 或 TerserPlugin 等插件对代码进行压缩,可以减少代码体积,提高加载速度。
例如:
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
// ...其它配置
optimization: {
minimize: true,
minimizer: [new TerserPlugin()],
},
};
2、按需加载代码:使用动态 import 或 React.lazy 动态加载组件代码,可以实现按需加载,减少初始加载时间。
例如:
import('./some-module').then(someModule => {
// 使用 someModule
});
import React, { lazy, Suspense } from 'react';
const SomeComponent = lazy(() => import('./SomeComponent'));
function MyComponent() {
return (
<Suspense fallback={<div>Loading...</div>}>
<SomeComponent />
</Suspense>
);
}
3、提取公共代码:使用 SplitChunksPlugin 插件将公共模块提取出来,可以减少重复加载,提高性能
例如:
module.exports = {
// ...其它配置
optimization: {
splitChunks: {
chunks: 'all',
minSize: 20000,
minChunks: 1,
maxAsyncRequests: 30,
maxInitialRequests: 30,
automaticNameDelimiter: '~',
},
},
};
4、使用缓存:使用 contenthash 将静态资源文件名与文件内容相关联,可以在文件内容变化时改变文件名,避免浏览器缓存问题
例如:
module.exports = {
// ...其它配置
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[contenthash].js',
},
};
5、优化图片资源:使用 image-webpack-loader 或 url-loader 等插件对图片进行压缩和转换,可以减少图片体积,提升性能。
例如:
module.exports = {
// ...其它配置
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
fallback: require.resolve('file-loader'),
},
},
],
},
],
},
};