Webpack 5新特性详解及性能优化实践
1.长期缓存
Webpack 5 通过确定性的 Chunk ID、模块 ID 和导出 ID 实现长期缓存,这意味着相同的输入将始终产生相同的输出。这样,当您的用户再次访问更新的网站时,浏览器可以重用旧的缓存,而不必重新下载所有资源。
// webpack.config.js module.exports = { // ... output: { // Use contenthash to ensure that the file name is associated with the content filename: '[name].[contenthash].js', chunkFilename: '[name].[contenthash].chunk.js', // Configure the asset hash to ensure long-term caching assetModuleFilename: '[name].[contenthash][ext][query]', // Use file system cache cache: { type: 'filesystem', }, }, // ... };
2. Tree Shaking 优化
Webpack 5 增强了 Tree Shaking 的效率,特别是对 ESM 的支持。
// package.json { "sideEffects": false, // Tell Webpack that this package has no side effects and can safely remove unreferenced code } // library.js export function myLibraryFunction() { // ... } // main.js import { myLibraryFunction } from './library.js';
3. 连接模块
Webpack 5 的 concatenateModules 选项可以合并小模块以减少 HTTP 请求数。但是,该功能可能会增加内存消耗,因此需要权衡使用:
// webpack.config.js module.exports = { // ... optimization: { concatenateModules: true, // Defaults to true, but may need to be turned off in some cases }, // ... };
4. 删除 Node.js 模块 Polyfill
Webpack 5 不再自动注入 Node.js 核心模块的 polyfill,开发者需要根据目标环境手动导入:
// If you need to be compatible with older browsers, you need to manually import polyfills import 'core-js/stable'; import 'regenerator-runtime/runtime'; // Or use babel-polyfill import '@babel/polyfill';
5. 性能优化实践
// webpack.config.js module.exports = { // ... optimization: { splitChunks: { chunks: 'all', minSize: 10000, // Adjust the appropriate size threshold maxSize: 0, // Allow code chunks of all sizes to be split }, }, // ... };
// main.js import('./dynamic-feature.js').then((dynamicFeature) => { dynamicFeature.init(); });
// webpack.config.js module.exports = { // ... experiments: { outputModule: true, // Enable output module support }, // ... };
6. Tree shake 的深入应用
虽然 Webpack 5 本身对 Tree shake 进行了优化,但开发者还可以通过一些策略进一步提升其效果。请确保你的代码遵循以下原则:
7. Loader 和 Plugin 优化
8.Source Map 策略
Source Map 对于调试至关重要,但它也会增加构建时间和输出大小。你可以根据环境调整 Source Map 类型:
// webpack.config.js module.exports = { // ... devtool: isProduction ? 'source-map' : 'cheap-module-source-map', // Use a smaller Source Map in production environment // ... };
9. 图片及静态资源处理
module.exports = { // ... module: { rules: [ { test: /\.(png|jpe?g|gif|svg)$/i, type: 'asset/resource', // Automatic resource processing }, ], }, // ... };