
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',
},
},
// ...
};
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';
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
},
// ...
};
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';
使用缓存:配置cache.type:'filesystem'使用文件系统缓存来减少重复构建。
splitchunks 优化:根据项目需求调整 optimization.splitchunks,例如:
// 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
},
},
// ...
};
模块解析优化:通过resolve.mainfields和resolve.modules配置减少模块解析的开销。
并行编译:使用threads-loader或worker-loader并行处理任务,加快编译速度。
代码分割:使用动态导入(import())按需加载代码,减少初始加载时间。
// main.js
import('./dynamic-feature.js').then((dynamicfeature) => {
dynamicfeature.init();
});
// webpack.config.js
module.exports = {
// ...
experiments: {
outputmodule: true, // enable output module support
},
// ...
};
虽然webpack 5本身对tree shake进行了优化,但开发者可以通过一些策略进一步提高其效果。确保您的代码遵循以下原则:
源映射对于调试至关重要,但它也会增加构建时间和输出大小。您可以根据环境调整source map类型:
// webpack.config.js
module.exports = {
// ...
devtool: isproduction ? 'source-map' : 'cheap-module-source-map', // use a smaller source map in production environment
// ...
};
module.exports = {
// ...
module: {
rules: [
{
test: /\.(png|jpe?g|gif|svg)$/i,
type: 'asset/resource', // Automatic resource processing
},
],
},
// ...
};
以上就是Webpack新特性详解及性能优化实践的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号