Webpack 5 配置优化指南

Webpack 5 核心概念

Webpack 5 是一个现代JavaScript应用程序的静态模块打包器,它引入了许多新特性和改进。

基础配置示例

// webpack.config.js
const path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
        clean: true, // 清理输出目录
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: 'babel-loader'
            },
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            }
        ]
    },
    plugins: [],
    mode: 'development'
};

Webpack 5 新特性

  • 持久缓存:显著提升构建速度
  • 模块联邦:实现微前端架构
  • 资源模块:内置处理资源文件
  • Tree Shaking改进:更完善的未使用代码消除
  • Node.js polyfills移除:减小包体积

高级配置技巧

代码分割

// 动态导入实现代码分割
// 懒加载组件
const Home = () => import('./components/Home.vue');
const About = () => import('./components/About.vue');

// Webpack配置
module.exports = {
    optimization: {
        splitChunks: {
            chunks: 'all',
            cacheGroups: {
                vendors: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendors',
                    chunks: 'all'
                },
                commons: {
                    name: 'commons',
                    minChunks: 2,
                    chunks: 'initial',
                    minSize: 0
                }
            }
        }
    }
};

持久缓存配置

module.exports = {
    cache: {
        type: 'filesystem',
        buildDependencies: {
            config: [__filename]
        },
        cacheDirectory: path.resolve(__dirname, '.webpack_cache')
    },
    snapshot: {
        managedPaths: [path.resolve(__dirname, 'node_modules')],
        immutablePaths: [],
        buildDependencies: {
            hash: true
        }
    }
};