请设计一个简单的 Webpack 配置,用于将一个 React 单页应用打包成可用于生产的代码,包括环境优化、错误堆栈跟踪和性能监控。

Webpack 配置设计

为了将一个 React 单页应用程序打包成可用于生产的代码,我们需要优化环境配置、实现错误堆栈跟踪以及性能监控。以下是一个示例配置文件 webpack.config.js:

const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const(dotenv) = require('dotenv-webpack');
const TerserPlugin = require('terser-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.[contenthash].js',
    publicPath: '/',
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/, // 正则表达式,匹配 js 或 jsx 结尾的文件
        exclude: /node_modules/, // 排除 node_modules 目录
        loader: 'babel-loader', // 使用 babel-loader 编译 ES6+ 代码至 ES5
      },
      {
        test: /\.(css|scss)$/, // 匹配 css 或 scss 文件
        use: [
          MiniCssExtractPlugin.loader, // 提取 CSS 为单独的文件
          'css-loader',
          'sass-loader',
        ],
      },
      {
        test: /\.(jpg|jpeg|png|gif|svg)$/, // 匹配图片文件
        type: 'asset',
        parser: {
          dataUrlCondition: {
            maxSize: 8 * 1024, // 小于 8 KB 的图片会被转换为 base64 编码
          },
        },
      },
    ],
  },
  plugins: [
    new HtmlWebPackPlugin({
      template: './public/index.html',
    }),
    new MiniCssExtractPlugin({
      filename: '[name].[contenthash].css',
    }),
    new Dotenv({
      path: './.env',
    }),
    new BundleAnalyzerPlugin({
      analyzerMode: 'static', // 生成报告至 dist/report.html
    }),
  ],
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          format: {
            comments: false,
          },
        },
        extractComments: false,
      }),
    ],
    runtimeChunk: 'single',
    splitChunks: {
      chunks: 'all',
      maxInitialRequests: Infinity,
      minSize: 0,
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\]/,
          name: 'vendors',
          chunks: 'all',
        },
      },
    },
  },
  devtool: 'source-map', // 开启源代码映射,方便调试生产环境错误
  devServer: {
    contentBase: path.join(__dirname, 'public'), // 指定静态文件目录
    historyApiFallback: true, // 适用于单页应用,自动处理 404 响应
  },
};

解释

  • entry: 入口文件设置为 src/index.js。
  • output: 指定输出路径和文件名,并使用 contenthash 来防止缓存。
  • resolve: 自动解析文件扩展名,便于导入时省略扩展名。
  • module: 定义了如何处理不同类型的文件,包括 JavaScript/JSX 文件、CSS/SCSS 文件和图片文件。
  • plugins: 使用了多个插件来优化构建过程,包括生成 HTML 文件、提取 CSS、环境变量加载和打包分析。
  • optimization: 包括代码分割、代码压缩和运行时分离。
  • devtool: 开启源代码映射,有助于调试生产环境中的错误。
  • devServer: 配置了开发服务器,支持热更新和单页应用路由。

以上配置可以确保 React 单页应用程序在生产环境中高效运行,同时便于调试和维护。