Webpack 其他配置

8 阅读3分钟

一、resolve 模块解析配置

Webpack 的 resolve 配置决定了如何解析模块路径,是项目中非常重要的配置项。

1. extensions 自动解析扩展名

module.exports = {
  resolve: {
    extensions: ['.js', '.jsx', '.json', '.vue'],
    // 使用示例:import App from './App' 会依次尝试查找:
    // ./App.js → ./App.jsx → ./App.json → ./App.vue
  }
}

作用

  • 自动尝试添加扩展名来解析模块
  • 减少 import 语句中的文件扩展名
  • 数组顺序决定查找优先级

2. alias 路径别名

const path = require('path')

module.exports = {
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      components: path.resolve(__dirname, 'src/components')
    }
    // 使用示例:
    // import Button from '@/components/Button'
    // import Header from 'components/Header'
  }
}

作用

  • 简化模块引入路径
  • 避免相对路径嵌套过深(如 ../../../components
  • 使代码更易维护和重构

二、mode 模式配置

Webpack 的 mode 配置决定了打包的优化级别。

1. 三种模式对比

module.exports = {
  mode: 'development', // 或 'production' 或 'none'
}
模式特点适用场景
development不压缩代码,包含 source map,优化构建速度开发环境
production自动启用代码压缩、Tree Shaking 等优化生产环境
none不使用任何默认优化选项需要完全自定义时

2. 模式对应的默认配置

开发模式默认启用

  • devtool: 'eval'
  • 不压缩代码
  • 保留模块和 chunk 名称

生产模式默认启用

  • devtool: false
  • 代码压缩(TerserPlugin)
  • 模块标识符优化(moduleIds: 'deterministic')
  • 副作用优化(sideEffects: true)

三、开发服务器配置

Webpack 5 内置了开发服务器,无需额外安装。

1. 基本配置

module.exports = {
  devServer: {
    static: './dist',      // 静态资源目录
    port: 8080,           // 端口号
    open: true,           // 自动打开浏览器
    compress: true,       // 启用 gzip 压缩
    historyApiFallback: true // 支持 HTML5 History API
  }
}

2. 常用配置项

配置项作用
hot: true启用热模块替换(HMR)
proxy配置 API 代理
client配置浏览器客户端行为
watchFiles监听文件变化
https启用 HTTPS

3. 启动命令

// package.json
{
  "scripts": {
    "dev": "webpack serve --mode development"
  }
}

四、热模块替换(HMR)

HMR 允许在运行时更新各种模块,而无需完全刷新页面。

1. 基础配置

module.exports = {
  devServer: {
    hot: true  // 启用 HMR
  },
  // 对于 JS 模块,需要在入口文件添加:
  // if (module.hot) {
  //   module.hot.accept()
  // }
}

2. 针对不同模块的 HMR 处理

CSS 模块(通过 style-loader 自动支持)

{
  test: /\.css$/,
  use: ['style-loader', 'css-loader'] // style-loader 内置 HMR 支持
}

Vue 组件(vue-loader 自动支持)

{
  test: /\.vue$/,
  loader: 'vue-loader' // 自动支持 HMR
}

React 组件(需要额外配置)

// 安装 react-refresh 相关依赖
npm install @pmmmwh/react-refresh-webpack-plugin react-refresh --save-dev

// webpack.config.js
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin')

module.exports = {
  plugins: [
    new ReactRefreshWebpackPlugin()
  ]
}

3. HMR 工作原理

  1. 应用程序代码请求 HMR 运行时
  2. 服务器监听文件变化
  3. 服务器发送更新消息到客户端
  4. 客户端运行时应用更新

五、完整配置示例

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  resolve: {
    extensions: ['.js', '.jsx', '.json'],
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  },
  devServer: {
    static: './dist',
    port: 3000,
    hot: true,
    open: true,
    proxy: {
      '/api': 'http://localhost:4000'
    }
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: 'babel-loader'
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html'
    })
  ]
}

六、常见问题解决

  1. HMR 不工作

    • 确保 devServer.hot 设置为 true
    • 检查是否在入口文件添加了 HMR 接受代码
    • 确认使用的 loader 支持 HMR(如 style-loader、vue-loader)
  2. 路径别名不生效

    • 检查路径是否正确
    • 确保 webpack 配置被正确加载
    • 重启开发服务器
  3. 开发服务器无法访问

    • 检查端口是否被占用
    • 尝试设置 host: '0.0.0.0' 允许外部访问
    • 检查防火墙设置

Webpack 5 官方文档相关链接: