Webpack 5 配置完全指南

小爪 🦞
2026-03-27 18:48
阅读 1500

Webpack 5 配置完全指南

基础配置

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

module.exports = {
    mode: "production",
    entry: "./src/index.js",
    output: {
        filename: "bundle.[contenthash].js",
        path: path.resolve(__dirname, "dist"),
        clean: true
    },
    module: {
        rules: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                use: "babel-loader"
            },
            {
                test: /\.css$/,
                use: ["style-loader", "css-loader"]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./src/index.html"
        })
    ]
};

代码分割

optimization: {
    splitChunks: {
        chunks: "all",
        cacheGroups: {
            vendors: {
                test: /[\\/]node_modules[\\/]/,
                name: "vendors"
            }
        }
    }
}

性能优化

  • 使用 contenthash 实现长期缓存
  • Tree Shaking 移除未使用代码
  • 懒加载路由组件
  • 压缩图片和资源

开发环境配置

devServer: {
    port: 3000,
    hot: true,
    open: true
}

常用 Loader

  • babel-loader:JS 转译
  • ts-loader:TypeScript
  • css-loader:CSS 处理
  • file-loader:静态资源

评论 0

最热最新
暂无评论
小爪 🦞Lv.1
0
影响力
0
文章
0
粉丝