mcpField
W
webpack-bundler

webpack-bundler

github.com/mindrally开发287810 次安装3 周前更新
代码仓库

关于 webpack-bundler

用于配置 JavaScript 应用构建的 Webpack 开发技能,涵盖打包、加载器、插件、优化、调试和 CI/CD 实践。

主要功能

  1. 01Webpack 配置指导
  2. 02代码拆分与 tree shaking
  3. 03加载器和插件用法
  4. 04打包体积与构建优化
  5. 05调试及 CI/CD 实践

适用场景

  1. 01配置生产与开发构建
  2. 02缩减打包体积和构建时间
  3. 03检查打包结果与源映射

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/mindrally/skills --skill webpack-bundler

安装后在 Claude Code 中输入/webpack-bundler确认已加载。

详细介绍

Webpack 打包器

你是 Webpack 领域的专家,Webpack 是一款功能强大的 JavaScript 应用模块打包器。使用 Webpack 配置和相关代码时,请遵循以下指南。

核心原则

  • Webpack 是一个静态模块打包器,会根据入口点构建依赖关系图
  • 注重优化打包体积、构建性能和开发体验
  • 使用 Webpack 5+ 的功能,以遵循最佳实践并提升性能
  • 了解插件和加载器生态系统

项目结构

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

配置最佳实践

入口和输出
module.exports = {
  entry: {
    main: './src/index.js',
    vendor: './src/vendor.js'
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash].js',
    clean: true
  }
};
模式配置
module.exports = {
  mode: 'production', // or 'development'
  // production mode enables tree-shaking, minification, and optimizations
};

代码拆分

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

// With React
const LazyComponent = React.lazy(() => import('./LazyComponent'));
SplitChunks 配置
optimization: {
  splitChunks: {
    chunks: 'all',
    cacheGroups: {
      vendor: {
        test: /[\\/]node_modules[\\/]/,
        name: 'vendors',
        chunks: 'all'
      }
    }
  }
}

Tree Shaking

启用 Tree Shaking
  1. 使用 ES6 模块语法(import/export)
  2. 设置 mode: 'production'
  3. 在 package.json 中配置 sideEffects
{
  "sideEffects": false
}

或者指定包含副作用的文件:

{
  "sideEffects": ["*.css", "*.scss"]
}
用于 Tree Shaking 的 Babel 配置
{
  "presets": [
    ["@babel/preset-env", { "modules": false }]
  ]
}

加载器

常见加载器配置
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'
    }
  ]
}

插件

必备插件
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()
]

性能优化

打包体积优化
  • 使用 webpack-bundle-analyzer 找出体积较大的依赖
  • 启用 Tree Shaking,移除未使用的代码
  • 用体积更小的替代品替换较大的依赖
  • 启用 Gzip 或 Brotli 压缩
构建性能
module.exports = {
  cache: {
    type: 'filesystem'
  },
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx'],
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  }
};
生产环境优化
optimization: {
  minimize: true,
  minimizer: [
    new TerserPlugin({
      parallel: true
    }),
    new CssMinimizerPlugin()
  ],
  moduleIds: 'deterministic',
  runtimeChunk: 'single'
}

开发服务器

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

环境变量

const webpack = require('webpack');

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

应避免的常见反模式

  • 不要将所有内容都打包到单个文件中
  • 只需要特定函数时,避免导入整个库
  • 不要在开发环境中跳过 source map
  • 避免硬编码特定环境的值
  • 不要忽略打包体积警告

测试和调试

  • 使用 source map 进行调试(devtool: 'source-map')
  • 定期使用 webpack-bundle-analyzer 分析打包内容
  • 部署前在本地测试生产构建
  • 使用 stats 选项了解构建输出

安全注意事项

  • 及时更新 Webpack 和插件
  • 验证并清理所有用户输入
  • 使用内容安全策略(Content Security Policy)标头
  • 避免在打包文件中暴露敏感数据

与 CI/CD 集成

  • 缓存 node_modules 和 Webpack 缓存
  • 使用 --mode production 运行生产构建
  • 超出打包体积预算时使构建失败
  • 生成并存储打包分析报告

评论

支持 Markdown