以下是一些常见的webpack打包优化方案:
1.使用生产模式(production mode):
// webpack.config.js module.exports = { mode: 'production', // ... 其他配置 };
2.代码分割(Code Splitting):
// webpack.config.js module.exports = { // ... optimization: { splitChunks: { chunks: 'all', }, }, };
3.缓存(Caching):
// webpack.config.js module.exports = { // ... output: { filename: '[name].[contenthash].bundle.js', chunkFilename: '[name].[contenthash].chunk.js', }, };
4.使用异步导入(Async Import):
// 在需要按需加载的地方使用动态导入 import('./SomeModule').then(module => { // do something with the module });
5.使用HardSourcePlugin来缓存模块解析结果:
// webpack.config.js const HardSourcePlugin = require('hard-source-webpack-plugin'); module.exports = { // ... plugins: [ new HardSourcePlugin(), ], };
6.使用uglifyjs-webpack-plugin或terser-webpack-plugin进行更深层次的代码压缩:
// webpack.config.js const TerserPlugin = require('terser-webpack-plugin'); module.exports = { optimization: { minimize: true, minimizer: [new TerserPlugin({ /* 更多配置 */ })], }, };
7.优化loader配置,比如使用cache-loader
来缓存Babel编译结果:
// webpack.config.js module.exports = { module: { rules: [ { test: /\.js$/, use: ['cache-loader', 'babel-loader'], exclude: /node_modules/, }, // ... 其他规则 ], }, };
8.使用webpack-bundle-analyzer插件分析bundle大小:
// webpack.config.js const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; module.exports = { plugins: [ new BundleAnalyzerPlugin({ analyzerMode: 'static', // 分析结果以静态页面的形式打开 }), ], };
标签:...,exports,config,module,js,webpack,优化,打包 From: https://www.cnblogs.com/czhowe/p/18144186