Webpack5 新特性与详细配置指南

一、Webpack5 新特性

内置 Asset Modules(资源模块)

  • 替代 file-loader、url-loader、raw-loader 等,统一资源处理方式。
  • 四种类型:
  • asset/resource:导出文件 URL(等同 file-loader)。
  • asset/inline:导出 DataURL(等同 url-loader)。
  • asset/source:导出源码(等同 raw-loader)。
  • asset:自动选择 resource 或 inline(默认 8KB 分界)。

持久化缓存(Persistent Caching)

  • 新增 cache: { type: 'filesystem' },极大提升二次构建速度。

Tree Shaking 更彻底

  • 默认生产模式下更智能地移除无用代码。

Module Federation(模块联邦)

  • 支持多个独立构建的应用共享模块,实现微前端架构。

更快的构建性能

  • 优化了编译流程,支持多进程/多实例(如 thread-loader)。

移除 Node.js Polyfills

  • 不再自动为 Node.js 内置模块做 polyfill,需手动引入。

更智能的默认配置

  • 如 production/development 模式下的优化、缓存、分包等。

更好的资源指纹

  • 支持 chunkhash、contenthash、hash,便于缓存管理。

二、详细配置

基础配置

复制代码
// webpack.config.js
const path = require("path");

module.exports = {
  mode: "production", // 或 'development'
  entry: {
    index: "./src/index.js",
  },
  output: {
    path: path.join(__dirname, "dist"),
    filename: "[name].js",
  },
};

资源模块(Asset Modules)

复制代码
module.exports = {
  module: {
    rules: [
      {
        test: /\.(jpg|jpeg|png|gif|svg)$/i,
        type: "asset",
        generator: {
          filename: "images/[hash][ext][query]",
        },
      },
      {
        test: /\.(ttf|eot|woff|woff2|otf)$/i,
        type: "asset/resource",
        generator: {
          filename: "fonts/[hash][ext][query]",
        },
      },
      {
        test: /\.txt$/,
        type: "asset",
        generator: {
          filename: "files/[hash][ext][query]",
        },
        parser: {
          dataUrlCondition: {
            maxSize: 4 * 1024, // 4kb
          },
        },
      },
    ],
  },
};

CSS/LESS/PostCSS 配置

复制代码
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader", "postcss-loader"],
      },
      {
        test: /\.less$/,
        use: [
          MiniCssExtractPlugin.loader,
          "css-loader",
          "postcss-loader",
          "less-loader",
        ],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: "[name]_[contenthash:8].css",
    }),
  ],
};
PostCSS 配置(postcss.config.js)
复制代码
module.exports = {
  plugins: [
    require("autoprefixer"),
    // 可选:cssnext、purgecss 等
  ],
};

代码分割与动态 import

复制代码
// 安装插件
// npm i -D @babel/plugin-syntax-dynamic-import

// .babelrc
{
  "plugins": [
    "@babel/plugin-syntax-dynamic-import"
  ]
}

动态 import 示例:

复制代码
methods: {
  dynamicImportFn() {
    import('./Dynamic.vue').then(component => {
      this.dynamicComponent = component.default;
    });
  }
}

缓存与构建优化

复制代码
module.exports = {
  cache: {
    type: "filesystem",
    buildDependencies: {
      config: [__filename],
    },
    version: "1.0",
  },
};

多进程/多实例

复制代码
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          {
            loader: "thread-loader",
            options: { workers: 2 },
          },
          "babel-loader",
        ],
      },
    ],
  },
};

体积分析与速度分析

复制代码
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
const BundleAnalyzerPlugin =
  require("webpack-bundle-analyzer").BundleAnalyzerPlugin;

const smp = new SpeedMeasurePlugin();

module.exports = smp.wrap({
  // ...webpack 配置
  plugins: [new BundleAnalyzerPlugin()],
});

生产环境优化

  • JS 压缩:内置 TerserPlugin

  • CSS 压缩:css-minimizer-webpack-plugin

    const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");

    module.exports = {
    optimization: {
    minimize: true,
    minimizer: [new CssMinimizerPlugin({ parallel: true })],
    },
    };

DLL 预编译

复制代码
// webpack.dll.js
const path = require("path");
const webpack = require("webpack");

module.exports = {
  mode: "production",
  entry: ["vue"],
  output: {
    path: path.resolve(process.cwd(), "dll"),
    filename: "vendor.js",
    library: "dllExample",
  },
  plugins: [
    new webpack.DllPlugin({
      name: "dllExample",
      path: path.resolve(process.cwd(), "dll/manifest.json"),
    }),
  ],
};

三、使用示例

资源引用

  • 图片、字体、文本等资源直接 import 即可,Webpack5 自动处理。

代码分割

  • 使用 import() 实现懒加载和动态组件。

性能分析

  • 运行 npm run build 后自动弹出体积分析报告。

参考资料

Webpack5 新特性与详细配置指南 - 高质量源码分享平台-免费下载各类网站源码与模板及前沿技术分享

相关推荐
程序员大阳2 小时前
副队长Vue3教程(12)--计算属性 computed
vue3·computed·计算属性·示例·可读·可写
晓得迷路了1 天前
栗子前端技术周刊第 155 期 - 2026 HTML 现状调查报告、Solid 2.0...
前端·javascript·webpack
FRing032 天前
vue3干货总结3(defineOptions(Vue3.3)、defineModel(Vue3.4)、Pinia)
开发语言·前端·vue.js·vue3
千寻技术帮2 天前
基于Spring Boot+Vue的农产品销售管理系统(源码+文档+数据库,附部署教程)
java·数据库·spring boot·后端·mysql·vue
千寻技术帮2 天前
微信小程序血压管理系统设计与实现_50054(Spring Boot + Vue + MySQL)
spring boot·小程序·vue·毕业设计·课程设计·血压助手
FRing033 天前
vue3干货总结2(vue3生命周期、父子通信、模版引用、provide和inject)
开发语言·前端·vue.js·vue3
zhuangzhao1193 天前
第一性原理大模型课程 · 第 21 课:从 Prompt 到 Agent:四件套、错误累积与 ReAct 手算
大模型·react·ai agent·错误累积·大模型课程
liwulin05063 天前
【OLLAMA】LangGrahp调用LLM WIKI
react·ollama·llm wiki
泯泷3 天前
Cloudflare 出手抢 Astro:前端框架之战,底层逻辑变了
前端·javascript·前端框架
AI开源软件3 天前
Vue3+SpringBoot3 业务配置统一管理:接管、保存与回退怎样保留有效值
java·前端·vue.js·spring boot·vue·ruoyi office