Webpack 完全教程

第一章:基础配置

1.1 安装和基本配置

Webpack 的安装和基本配置方法。

练习 1.1:基本配置示例

展示 Webpack 的基本配置。

安装 Webpack
# 全局安装
npm install -g webpack webpack-cli

# 项目安装
npm install --save-dev webpack webpack-cli
基本配置文件
// webpack.config.js
const path = require('path');

module.exports = {
  // 入口文件
  entry: './src/index.js',
  
  // 输出配置
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  
  // 开发模式
  mode: 'development',
  
  // 开发工具
  devtool: 'source-map',
  
  // 开发服务器
  devServer: {
    contentBase: './dist',
    port: 3000,
    hot: true
  }
};

1.2 Loader 配置

Webpack 的 Loader 配置。

练习 1.2:常用 Loader 配置

展示常用 Loader 的配置。

Loader 配置示例
// webpack.config.js
module.exports = {
  // ... 其他配置
  
  module: {
    rules: [
      // Babel Loader
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },
      
      // CSS Loader
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      },
      
      // SCSS Loader
      {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader', 'sass-loader']
      },
      
      // 图片 Loader
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: ['file-loader']
      },
      
      // 字体 Loader
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        use: ['file-loader']
      }
    ]
  }
};

第二章:高级特性

2.1 代码分割

Webpack 的代码分割功能。

练习 2.1:代码分割示例

展示代码分割的配置。

代码分割配置
// webpack.config.js
module.exports = {
  // ... 其他配置
  
  optimization: {
    splitChunks: {
      chunks: 'all',
      minSize: 20000,
      maxSize: 0,
      minChunks: 1,
      maxAsyncRequests: 30,
      maxInitialRequests: 30,
      automaticNameDelimiter: '~',
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true
        }
      }
    }
  }
};
动态导入示例
// 动态导入
import(/* webpackChunkName: "lodash" */ 'lodash').then(({ default: _ }) => {
  console.log(_.join(['Hello', 'webpack'], ' '));
});

2.2 插件配置

Webpack 的插件配置。

练习 2.2:常用插件配置

展示常用插件的配置。

插件配置示例
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpack = require('webpack');

module.exports = {
  // ... 其他配置
  
  plugins: [
    // 清理输出目录
    new CleanWebpackPlugin(),
    
    // 生成 HTML 文件
    new HtmlWebpackPlugin({
      title: 'Webpack App',
      template: './src/index.html'
    }),
    
    // 提取 CSS
    new MiniCssExtractPlugin({
      filename: '[name].[contenthash].css'
    }),
    
    // 环境变量
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    }),
    
    // 热更新
    new webpack.HotModuleReplacementPlugin()
  ]
};

第三章:性能优化

3.1 构建优化

Webpack 的构建优化配置。

练习 3.1:构建优化示例

展示构建优化的配置。

构建优化配置
// webpack.config.js
module.exports = {
  // ... 其他配置
  
  optimization: {
    // 压缩代码
    minimize: true,
    
    // 模块标识符
    moduleIds: 'deterministic',
    
    // 运行时块
    runtimeChunk: 'single',
    
    // 缓存组
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all'
        }
      }
    }
  },
  
  // 解析配置
  resolve: {
    // 扩展名
    extensions: ['.js', '.json', '.jsx'],
    
    // 别名
    alias: {
      '@': path.resolve(__dirname, 'src')
    },
    
    // 模块解析
    modules: ['node_modules']
  }
};

3.2 开发优化

Webpack 的开发优化配置。

练习 3.2:开发优化示例

展示开发优化的配置。

开发优化配置
// webpack.config.js
module.exports = {
  // ... 其他配置
  
  // 开发服务器
  devServer: {
    contentBase: './dist',
    port: 3000,
    hot: true,
    open: true,
    compress: true,
    historyApiFallback: true,
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  },
  
  // 缓存
  cache: {
    type: 'filesystem',
    buildDependencies: {
      config: [__filename]
    }
  },
  
  // 性能提示
  performance: {
    hints: 'warning',
    maxEntrypointSize: 512000,
    maxAssetSize: 512000
  }
};

第四章:最佳实践

4.1 多环境配置

Webpack 的多环境配置。

练习 4.1:多环境配置示例

展示多环境配置的使用。

多环境配置示例
// webpack.common.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash].js'
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    })
  ]
};

// webpack.dev.js
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
  mode: 'development',
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './dist'
  }
});

// webpack.prod.js
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
  mode: 'production',
  devtool: 'source-map'
});

4.2 自定义配置

Webpack 的自定义配置。

练习 4.2:自定义配置示例

展示自定义配置的使用。

自定义配置示例
// webpack.config.js
const path = require('path');
const webpack = require('webpack');

// 自定义插件
class MyPlugin {
  apply(compiler) {
    compiler.hooks.emit.tapAsync('MyPlugin', (compilation, callback) => {
      console.log('MyPlugin is running');
      callback();
    });
  }
}

module.exports = {
  // ... 其他配置
  
  plugins: [
    new MyPlugin()
  ],
  
  // 自定义 loader
  module: {
    rules: [
      {
        test: /\.my$/,
        use: [
          {
            loader: path.resolve('path/to/loader.js'),
            options: {
              // loader 选项
            }
          }
        ]
      }
    ]
  }
};

学习建议

建议按照章节顺序学习,每完成一个练习后再进行下一个。可以通过实际项目来实践所学知识,特别是性能优化和最佳实践部分。注意 Webpack 的配置非常灵活,需要根据项目需求选择合适的配置方案。