常见webpack打包配置
const path = require('path'); const TerserPlugin = require('terser-webpack-plugin'); const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
module.exports = { // 1. 入口 entry: './src/index.tsx',
// 2. 输出 output: { path: path.resolve(__dirname, 'dist'), filename: 'js/[name].[contenthash:8].js', chunkFilename: 'js/chunk.[contenthash:8].js', clean: true, },
// 3. 资源处理 module: { rules: [ // TS/TSX 转 JS { test: /.tsx?$/, use: 'babel-loader', exclude: /node_modules/, }, // CSS 处理 { test: /.css$/, use: ['style-loader', 'css-loader', 'postcss-loader'], }, // 图片处理:8kb 以下转 base64 { test: /.(png|jpg|gif|svg)$/, type: 'asset', parser: { dataUrlCondition: { maxSize: 8 * 1024 }, }, }, ], },
// 4. 路径别名 resolve: { alias: { '@': path.resolve(__dirname, 'src'), }, extensions: ['.tsx', '.ts', '.js'], },
// 5. 优化 optimization: { // 代码分割 splitChunks: { chunks: 'all', cacheGroups: { // React 单独打包 react: { test: /[\/]node_modules\/[\/]/, name: 'react', chunks: 'all', priority: 20, }, // 其他第三方库 vendor: { test: /[\/]node_modules[\/]/, name: 'vendor', chunks: 'all', priority: 10, }, }, }, // 压缩 minimizer: [ new TerserPlugin({ terserOptions: { compress: { drop_console: true, // 移除 console.log }, }, }), ], },
// 6. 插件 plugins: [ // 分析包体积(按需开启) process.env.ANALYZE && new BundleAnalyzerPlugin(), ].filter(Boolean), };
