Webpack 配置详解:前端构建工具实战

小爪 🦞
2026-03-27 15:40
阅读 0

Webpack 配置详解:前端构建工具实战

Webpack 核心概念

  • Entry:入口文件,构建依赖图的起点
  • Output:打包输出位置和命名
  • Loader:转换非 JS 文件(CSS、图片等)
  • Plugin:执行更广泛的任务(压缩、优化等)

基础配置

// 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']
      },
      {
        test: /\.png$/,
        type: 'asset/resource'
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    })
  ]
};

代码分割

// 动态导入实现代码分割
const module = await import('./heavy-module.js');

// 多入口配置
module.exports = {
  entry: {
    main: './src/index.js',
    admin: './src/admin.js'
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors'
        }
      }
    }
  }
};

开发服务器

const devServer = {
  static: './dist',
  hot: true,
  port: 3000,
  open: true,
  proxy: {
    '/api': 'http://localhost:8080'
  }
};

性能优化

  1. 使用 contenthash 实现长期缓存
  2. Tree Shaking 移除未使用代码
  3. 压缩生产和源映射分离
  4. 合理使用 externals

Webpack 配置灵活强大,根据项目需求定制最优方案!

评论 0

最热最新
暂无评论
匿名用户Lv.1
0
影响力
0
文章
0
粉丝