构建

Webpack

CLI、配置、Loader 与 Plugin 常用片段。 — 共 14 条

共 14 条代码片段

A. CLI 命令

构建

npx webpack
npx webpack --mode production
npx webpack --mode development
npx webpack --config webpack.prod.js

监听与开发服务

npx webpack --watch
npx webpack serve
npx webpack serve --open --port 8080

打包分析

npx webpack --profile --json > stats.json
npx webpack-bundle-analyzer stats.json

B. 基础配置

webpack.config.js 基础

const path = require("path");

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

devServer

module.exports = {
  devServer: {
    port: 8080,
    hot: true,
    historyApiFallback: true,
    proxy: [
      {
        context: ["/api"],
        target: "http://localhost:3000",
        changeOrigin: true,
      },
    ],
  },
};

路径别名

const path = require("path");

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

多环境配置合并

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

module.exports = merge(common, {
  mode: "development",
  devtool: "eval-source-map",
});

C. Loader

CSS / Less

module.exports = {
  module: {
    rules: [
      {
        test: /\.less$/i,
        use: ["style-loader", "css-loader", "less-loader"],
      },
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
};

Babel / TS

{
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  use: "babel-loader",
},
{
  test: /\.(ts|tsx)$/,
  exclude: /node_modules/,
  use: "ts-loader",
}

图片与字体

{
  test: /\.(png|jpe?g|gif|svg|woff2?|ttf|eot)$/i,
  type: "asset",
  parser: {
    dataUrlCondition: {
      maxSize: 8 * 1024,
    },
  },
}

D. Plugin

HtmlWebpackPlugin

const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  plugins: [
    new HtmlWebpackPlugin({
      template: "./public/index.html",
      title: "App",
    }),
  ],
};

DefinePlugin 环境变量

const webpack = require("webpack");

module.exports = {
  plugins: [
    new webpack.DefinePlugin({
      "process.env.NODE_ENV": JSON.stringify("production"),
      __APP_VERSION__: JSON.stringify("1.0.0"),
    }),
  ],
};

代码分割

module.exports = {
  optimization: {
    splitChunks: {
      chunks: "all",
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: "vendors",
          chunks: "all",
        },
      },
    },
    runtimeChunk: "single",
  },
};

提取 CSS

const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: "[name].[contenthash].css",
    }),
  ],
};