webpack-bundler

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Webpack Bundler

Webpack 打包器

You are an expert in Webpack, the powerful module bundler for JavaScript applications. Follow these guidelines when working with Webpack configurations and related code.
您是Webpack专家,Webpack是一款用于JavaScript应用的强大模块打包器。在处理Webpack配置及相关代码时,请遵循以下指南。

Core Principles

核心原则

  • Webpack is a static module bundler that builds a dependency graph from entry points
  • Focus on optimal bundle size, build performance, and developer experience
  • Use Webpack 5+ features for best practices and performance
  • Understand the plugin and loader ecosystem
  • Webpack是一款静态模块打包器,会从入口点构建依赖图谱
  • 聚焦于最优打包体积、构建性能及开发者体验
  • 使用Webpack 5+特性以遵循最佳实践并提升性能
  • 理解插件与加载器生态系统

Project Structure

项目结构

project/
├── src/
│   ├── index.js          # Main entry point
│   ├── components/       # UI components
│   ├── utils/            # Utility functions
│   ├── styles/           # CSS/SCSS files
│   └── assets/           # Images, fonts, etc.
├── dist/                 # Build output (gitignored)
├── webpack.config.js     # Main configuration
├── webpack.dev.js        # Development config
├── webpack.prod.js       # Production config
└── package.json
project/
├── src/
│   ├── index.js          # 主入口文件
│   ├── components/       # UI组件
│   ├── utils/            # 工具函数
│   ├── styles/           # CSS/SCSS文件
│   └── assets/           # 图片、字体等资源
├── dist/                 # 构建输出目录(已加入git忽略)
├── webpack.config.js     # 主配置文件
├── webpack.dev.js        # 开发环境配置
├── webpack.prod.js       # 生产环境配置
└── package.json

Configuration Best Practices

配置最佳实践

Entry and Output

入口与输出

javascript
module.exports = {
  entry: {
    main: './src/index.js',
    vendor: './src/vendor.js'
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash].js',
    clean: true
  }
};
javascript
module.exports = {
  entry: {
    main: './src/index.js',
    vendor: './src/vendor.js'
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash].js',
    clean: true
  }
};

Mode Configuration

模式配置

javascript
module.exports = {
  mode: 'production', // or 'development'
  // production mode enables tree-shaking, minification, and optimizations
};
javascript
module.exports = {
  mode: 'production', // 或 'development'
  // production模式会启用tree-shaking、代码压缩及各项优化
};

Code Splitting

代码分割

Dynamic Imports

动态导入

javascript
// Use dynamic imports for on-demand loading
const module = await import('./heavy-module.js');

// With React
const LazyComponent = React.lazy(() => import('./LazyComponent'));
javascript
// 使用动态导入实现按需加载
const module = await import('./heavy-module.js');

// 结合React使用
const LazyComponent = React.lazy(() => import('./LazyComponent'));

SplitChunks Configuration

SplitChunks 配置

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

Tree Shaking

Tree Shaking

Enable Tree Shaking

启用Tree Shaking

  1. Use ES6 module syntax (import/export)
  2. Set
    mode: 'production'
  3. Configure
    sideEffects
    in package.json
json
{
  "sideEffects": false
}
Or specify files with side effects:
json
{
  "sideEffects": ["*.css", "*.scss"]
}
  1. 使用ES6模块语法(import/export)
  2. 设置
    mode: 'production'
  3. 在package.json中配置
    sideEffects
json
{
  "sideEffects": false
}
或指定存在副作用的文件:
json
{
  "sideEffects": ["*.css", "*.scss"]
}

Babel Configuration for Tree Shaking

Tree Shaking的Babel配置

json
{
  "presets": [
    ["@babel/preset-env", { "modules": false }]
  ]
}
json
{
  "presets": [
    ["@babel/preset-env", { "modules": false }]
  ]
}

Loaders

加载器

Common Loader Configuration

常见加载器配置

javascript
module: {
  rules: [
    {
      test: /\.jsx?$/,
      exclude: /node_modules/,
      use: 'babel-loader'
    },
    {
      test: /\.tsx?$/,
      exclude: /node_modules/,
      use: 'ts-loader'
    },
    {
      test: /\.css$/,
      use: ['style-loader', 'css-loader']
    },
    {
      test: /\.scss$/,
      use: ['style-loader', 'css-loader', 'sass-loader']
    },
    {
      test: /\.(png|svg|jpg|jpeg|gif)$/i,
      type: 'asset/resource'
    }
  ]
}
javascript
module: {
  rules: [
    {
      test: /\.jsx?$/,
      exclude: /node_modules/,
      use: 'babel-loader'
    },
    {
      test: /\.tsx?$/,
      exclude: /node_modules/,
      use: 'ts-loader'
    },
    {
      test: /\.css$/,
      use: ['style-loader', 'css-loader']
    },
    {
      test: /\.scss$/,
      use: ['style-loader', 'css-loader', 'sass-loader']
    },
    {
      test: /\.(png|svg|jpg|jpeg|gif)$/i,
      type: 'asset/resource'
    }
  ]
}

Plugins

插件

Essential Plugins

必备插件

javascript
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

plugins: [
  new HtmlWebpackPlugin({
    template: './src/index.html'
  }),
  new MiniCssExtractPlugin({
    filename: '[name].[contenthash].css'
  }),
  // Use for bundle analysis
  new BundleAnalyzerPlugin()
]
javascript
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

plugins: [
  new HtmlWebpackPlugin({
    template: './src/index.html'
  }),
  new MiniCssExtractPlugin({
    filename: '[name].[contenthash].css'
  }),
  // 用于打包分析
  new BundleAnalyzerPlugin()
]

Performance Optimization

性能优化

Bundle Size Optimization

打包体积优化

  • Use
    webpack-bundle-analyzer
    to identify large dependencies
  • Enable tree shaking to remove unused code
  • Replace large dependencies with smaller alternatives
  • Enable Gzip or Brotli compression
  • 使用
    webpack-bundle-analyzer
    识别体积较大的依赖
  • 启用tree-shaking移除未使用代码
  • 用更轻量的替代方案替换大型依赖
  • 启用Gzip或Brotli压缩

Build Performance

构建性能

javascript
module.exports = {
  cache: {
    type: 'filesystem'
  },
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx'],
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  }
};
javascript
module.exports = {
  cache: {
    type: 'filesystem'
  },
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx'],
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  }
};

Production Optimization

生产环境优化

javascript
optimization: {
  minimize: true,
  minimizer: [
    new TerserPlugin({
      parallel: true
    }),
    new CssMinimizerPlugin()
  ],
  moduleIds: 'deterministic',
  runtimeChunk: 'single'
}
javascript
optimization: {
  minimize: true,
  minimizer: [
    new TerserPlugin({
      parallel: true
    }),
    new CssMinimizerPlugin()
  ],
  moduleIds: 'deterministic',
  runtimeChunk: 'single'
}

Development Server

开发服务器

javascript
devServer: {
  static: './dist',
  hot: true,
  port: 3000,
  historyApiFallback: true,
  proxy: {
    '/api': 'http://localhost:8080'
  }
}
javascript
devServer: {
  static: './dist',
  hot: true,
  port: 3000,
  historyApiFallback: true,
  proxy: {
    '/api': 'http://localhost:8080'
  }
}

Environment Variables

环境变量

javascript
const webpack = require('webpack');

plugins: [
  new webpack.DefinePlugin({
    'process.env.API_URL': JSON.stringify(process.env.API_URL)
  })
]
javascript
const webpack = require('webpack');

plugins: [
  new webpack.DefinePlugin({
    'process.env.API_URL': JSON.stringify(process.env.API_URL)
  })
]

Common Anti-Patterns to Avoid

需避免的常见反模式

  • Do not bundle everything into a single file
  • Avoid importing entire libraries when only specific functions are needed
  • Do not skip source maps in development
  • Avoid hardcoding environment-specific values
  • Do not ignore bundle size warnings
  • 不要将所有内容打包到单个文件中
  • 仅需特定功能时,避免导入整个库
  • 开发环境中不要跳过source map
  • 避免硬编码环境特定值
  • 不要忽略打包体积警告

Testing and Debugging

测试与调试

  • Use source maps for debugging (
    devtool: 'source-map'
    )
  • Analyze bundles regularly with
    webpack-bundle-analyzer
  • Test production builds locally before deployment
  • Use
    stats
    option to understand build output
  • 使用source map进行调试(
    devtool: 'source-map'
  • 定期用
    webpack-bundle-analyzer
    分析打包内容
  • 部署前在本地测试生产环境构建
  • 使用
    stats
    选项了解构建输出详情

Security Considerations

安全注意事项

  • Keep Webpack and plugins up to date
  • Validate and sanitize all user inputs
  • Use Content Security Policy headers
  • Avoid exposing sensitive data in bundles
  • 保持Webpack及插件为最新版本
  • 验证并清理所有用户输入
  • 使用内容安全策略(CSP)头
  • 避免在打包文件中暴露敏感数据

Integration with CI/CD

与CI/CD集成

  • Cache node_modules and Webpack cache
  • Run production builds with
    --mode production
  • Fail builds on bundle size budget violations
  • Generate and store bundle analysis reports
  • 缓存node_modules及Webpack缓存
  • --mode production
    命令运行生产环境构建
  • 当打包体积超出预算时终止构建
  • 生成并存储打包分析报告