一、打包工具选型对比
1.1 主流打包工具特性对比
工具 | 速度 | Tree Shaking | 代码分割 | 热更新 | 适用场景 |
---|---|---|---|---|---|
Webpack | 中 | ✔️ | ✔️ | ✔️ | 复杂SPA |
Rollup | 快 | ✔️ | ✔️ | ❌ | 库开发 |
Parcel | 最快 | ✔️ | ✔️ | ✔️ | 快速原型 |
esbuild | 极快 | ✔️ | ✔️ | ✔️ | 大型项目 |
Vite | 超快 | ✔️ | ✔️ | ✔️ | 现代框架 |
1.2 工具选择决策树
二、Webpack 完整配置
2.1 基础生产配置
// webpack.config.prod.js const path = require('path'); const TerserPlugin = require('terser-webpack-plugin'); const CssMinimizerPlugin = require('css-minimizer-webpack-plugin'); module.exports = { mode: 'production', entry: './src/index.js', output: { filename: '[name].[contenthash:8].js', path: path.resolve(__dirname, 'dist'), clean: true, }, module: { rules: [ { test: /.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } }, { test: /.css$/, use: ['style-loader', 'css-loader'] } ] }, optimization: { minimize: true, minimizer: [ new TerserPlugin({ parallel: true, terserOptions: { compress: { drop_console: true, }, }, }), new CssMinimizerPlugin(), ], splitChunks: { chunks: 'all', }, }, };
2.2 高级优化配置
代码分割策略:
optimization: { splitChunks: { cacheGroups: { vendors: { test: /[\/]node_modules[\/]/, name: 'vendors', chunks: 'all', }, commons: { name: 'commons', minChunks: 2, chunks: 'initial', minSize: 0, }, }, }, runtimeChunk: { name: 'runtime', }, }
持久化缓存:
module.exports = { cache: { type: 'filesystem', buildDependencies: { config: [__filename], }, }, };
三、代码压缩技术详解
3.1 JavaScript 压缩
Terser 配置选项:
new TerserPlugin({ parallel: 4, // 使用4个线程 extractComments: false, // 不提取注释 terserOptions: { compress: { pure_funcs: ['console.info'], // 只移除console.info dead_code: true, // 删除不可达代码 drop_debugger: true, }, format: { comments: false, // 移除所有注释 }, mangle: { properties: { regex: /^_/, // 只混淆下划线开头的属性 }, }, }, })
3.2 CSS 压缩优化
PostCSS 配置:
// postcss.config.js module.exports = { plugins: [ require('cssnano')({ preset: ['advanced', { discardComments: { removeAll: true }, colormin: true, zindex: false, }] }), require('autoprefixer') ] }
3.3 HTML 压缩
const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { plugins: [ new HtmlWebpackPlugin({ template: './src/index.html', minify: { collapseWhitespace: true, removeComments: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true, useShortDoctype: true, minifyCSS: true, minifyJS: true, }, }), ], };
四、高级打包技巧
4.1 按需加载
React 动态导入:
const LazyComponent = React.lazy(() => import('./LazyComponent')); function MyComponent() { return ( Loading...
}>
);
}