WebPack5-Cli

36 阅读8分钟

WebPack5

项目

React 脚手架

webpack.dev.js

const EslintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin");

const path = require("path");
// 返回处理样式loader的函数
const getStyleLoaders = (pre) => {
  return [
    "style-loader",
    "css-loader",
    {
      // 处理css的兼容性
      // 配合package.json中的browserslist
      loader: "postcss-loader",
      options: {
        postcssOptions: {
          plugins: ["postcss-preset-env"],
        },
      },
    },
    pre,
  ].filter(Boolean);
};
module.exports = {
  entry: "./src/main.js",
  output: {
    path: undefined,
    filename: "static/js/[name].js",
    chunkFilename: "static/js/[name].chunk.js",
    assetModuleFilename: "static/media/[hash:10][ext][query]",
  },
  module: {
    rules: [
      // 处理css
      {
        test: /\.css$/,
        use: getStyleLoaders(),
      },
      //   处理less
      {
        test: /\.less$/,
        use: getStyleLoaders("less-loader"),
      },
      //   处理sass scss
      {
        test: /\.s[ac]ss$/,
        use: getStyleLoaders("sass-loader"),
      },
      //   处理stylus
      {
        test: /\.styl$/,
        use: getStyleLoaders("stylus-loader"),
      },
      //   处理图片
      {
        test: /\.(jpe?g|png|gif|webp|gsvg)$/,
        type: "asset",
        parser: {
          dataUrlCondition: {
            maxSize: 10 * 1024, // 4kb
          },
        },
      },
      //   处理其他资源
      {
        test: /\.(woff2?|ttf)$/,
        type: "asset/resource",
      },
      // 处理js
      {
        test: /\.jsx?$/,
        // exclude: /node_modules/,
        include: [path.resolve(__dirname, "../src")],
        loader: "babel-loader",
        options: {
          cacheDirectory: true, // 开启缓存
          cacheCompression: false, //不压缩缓存
          plugins: ["react-refresh/babel"], // 激活js的HMR功能
        },
      },
    ],
  },
  plugins: [
    // Eslint
    new EslintWebpackPlugin({
      context: path.resolve(__dirname, "../src"),
      exclude: ["node_modules", "dist"],
      cache: true,
      cacheLocation: path.resolve(
        __dirname,
        "../node_modules/.cache/.eslintcache"
      ),
    }),
    // html
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "../public/index.html"),
    }),
    new ReactRefreshWebpackPlugin(),
  ],
  mode: "development",
  devtool: "cheap-module-source-map",
  optimization: {
    splitChunks: {
      chunks: "all",
    },
    runtimeChunk: {
      name: (entrypoint) => `runtime-chunk~${entrypoint.name}`,
    },
  },
  // webpack解析模块加载选项
  resolve: {
    extensions: [".js", ".jsx", ".json"],
  },
  devServer: {
    host: "localhost",
    port: 9527,
    open: false,
    historyApiFallback: true, //解决前端路由刷新404的问题
    hot: true, // 开启HMR
  },
};

webpack.prod.js

const EslintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");

const path = require("path");
// 返回处理样式loader的函数
const getStyleLoaders = (pre) => {
  return [
    MiniCssExtractPlugin.loader,
    "css-loader",
    {
      // 处理css的兼容性
      // 配合package.json中的browserslist
      loader: "postcss-loader",
      options: {
        postcssOptions: {
          plugins: ["postcss-preset-env"],
        },
      },
    },
    pre,
  ].filter(Boolean);
};
module.exports = {
  entry: "./src/main.js",
  output: {
    path: path.resolve(__dirname, "../dist"),
    filename: "static/js/[name].[contenthash:10].js",
    chunkFilename: "static/js/[name].[contenthash:10].chunk.js",
    assetModuleFilename: "static/media/[hash:10][ext][query]",
    clean: true,
  },
  module: {
    rules: [
      // 处理css
      {
        test: /\.css$/,
        use: getStyleLoaders(),
      },
      //   处理less
      {
        test: /\.less$/,
        use: getStyleLoaders("less-loader"),
      },
      //   处理sass scss
      {
        test: /\.s[ac]ss$/,
        use: getStyleLoaders("sass-loader"),
      },
      //   处理stylus
      {
        test: /\.styl$/,
        use: getStyleLoaders("stylus-loader"),
      },
      //   处理图片
      {
        test: /\.(jpe?g|png|gif|webp|gsvg)$/,
        type: "asset",
        parser: {
          dataUrlCondition: {
            maxSize: 10 * 1024, // 4kb
          },
        },
      },
      //   处理其他资源
      {
        test: /\.(woff2?|ttf)$/,
        type: "asset/resource",
      },
      // 处理js
      {
        test: /\.jsx?$/,
        // exclude: /node_modules/,
        include: [path.resolve(__dirname, "../src")],
        loader: "babel-loader",
        options: {
          cacheDirectory: true, // 开启缓存
          cacheCompression: false, //不压缩缓存
        },
      },
    ],
  },
  plugins: [
    // Eslint
    new EslintWebpackPlugin({
      context: path.resolve(__dirname, "../src"),
      exclude: ["node_modules", "dist"],
      cache: true,
      cacheLocation: path.resolve(
        __dirname,
        "../node_modules/.cache/.eslintcache"
      ),
    }),
    // html
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "../public/index.html"),
    }),
    // css拆分
    new MiniCssExtractPlugin({
      filename: "static/css/[name].[contenthash:10].css",
      chunkFilename: "static/css/[name].[contenthash:10].chunk.css",
    }),
    // 拷贝public
    new CopyPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, "../public"),
          to: path.resolve(__dirname, "../dist"),
          globOptions: {
            // 忽略文件
            ignore: ["**/index.html*"],
          },
        },
      ],
    }),
  ],
  mode: "production",
  devtool: "cheap-module-source-map",
  optimization: {
    splitChunks: {
      chunks: "all",
    },
    runtimeChunk: {
      name: (entrypoint) => `runtime-chunk~${entrypoint.name}`,
    },
    // 压缩文件都在这里做
    minimizer: [
      // 这两个要一起出现
      new CssMinimizerWebpackPlugin(), // css压缩
      new TerserWebpackPlugin(), // js压缩
      new ImageMinimizerPlugin({
        minimizer: {
          implementation: ImageMinimizerPlugin.imageminGenerate,
          options: {
            plugins: [
              ["gifsicle", { interlaced: true }],
              ["jpegtran", { progressive: true }],
              ["optipng", { optimizationLevel: 5 }],
              [
                "svgo",
                {
                  plugins: [
                    "preset-default",
                    "prefixIds",
                    {
                      name: "sortAttrs",
                      params: {
                        xmlnsOrder: "alphabetical",
                      },
                    },
                  ],
                },
              ],
            ],
          },
        },
      }),
    ],
  },
  // webpack解析模块加载选项
  resolve: {
    extensions: [".js", ".jsx", ".json"],
  },
  devServer: {
    host: "localhost",
    port: 9527,
    open: false,
    historyApiFallback: true, //解决前端路由刷新404的问题
    hot: true, // 开启HMR
  },
};

package.json

{
  "name": "webpack_react",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "npm run dev",
    "dev": "cross-env NODE_ENV=development webpack serve --config ./config/webpack.config.js",
    "build": "cross-env NODE_ENV=production webpack --config ./config/webpack.config.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "browerslist": [
    "last 2 versions",
    "> 1%",
    "ie >= 9"
  ],
  "devDependencies": {
    "@babel/core": "^7.23.5",
    "@babel/preset-env": "^7.23.5",
    "@babel/preset-react": "^7.23.3",
    "@pmmmwh/react-refresh-webpack-plugin": "^0.5.11",
    "babel-loader": "^9.1.3",
    "babel-preset-react-app": "^10.0.1",
    "copy-webpack-plugin": "^11.0.0",
    "cross-env": "^7.0.3",
    "css-loader": "^6.8.1",
    "css-minimizer-webpack-plugin": "^5.0.1",
    "eslint-config-react-app": "^7.0.1",
    "eslint-webpack-plugin": "^4.0.1",
    "html-webpack-plugin": "^5.5.4",
    "image-minimizer-webpack-plugin": "^3.8.3",
    "imagemin": "^8.0.1",
    "imagemin-gifsicle": "^7.0.0",
    "imagemin-jpegtran": "^7.0.0",
    "imagemin-optipng": "^8.0.0",
    "imagemin-svgo": "^10.0.1",
    "install": "^0.13.0",
    "less-loader": "^11.1.3",
    "mini-css-extract-plugin": "^2.7.6",
    "npm": "^10.2.5",
    "postcss-loader": "^7.3.3",
    "postcss-preset-env": "^9.3.0",
    "react-refresh": "^0.14.0",
    "sass": "^1.69.5",
    "sass-loader": "^13.3.2",
    "style-loader": "^3.3.3",
    "stylus-loader": "^7.1.3",
    "thread-loader": "^4.0.2",
    "webpack": "^5.89.0",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^4.15.1"
  },
  "dependencies": {
    "antd": "^4.20.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.20.1"
  }
}

.eslintrc.js

module.exports = {
  extends: ["react-app"], // 继承 react 官方规则
  parserOptions: {
    babelOptions: {
      presets: [
        // 解决页面报错问题
        ["babel-preset-react-app", false],
        "babel-preset-react-app/prod",
      ],
    },
  },
};

babel.config.js

module.exports = {
  presets: ["react-app"]
};

.babelrc

{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

webpack.config.js

const EslintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin");
const os = require("os");
// cpu核数
const threads = os.cpus().length;
// 获取cross-env定义的环境变量
const isProduction = process.env.NODE_ENV === "production";

const path = require("path");
// 返回处理样式loader的函数
const getStyleLoaders = (pre) => {
  return [
    isProduction ? MiniCssExtractPlugin.loader : "style-loader",
    "css-loader",
    {
      // 处理css的兼容性
      // 配合package.json中的browserslist
      loader: "postcss-loader",
      options: {
        postcssOptions: {
          plugins: ["postcss-preset-env"],
        },
      },
    },
    pre && {
      loader: pre,
      options:
        pre === "less-loader"
          ? {
              // antd的自定义主题色
              lessOptions: {
                modifyVars: { "@primary-color": "#ff6700" },
                javascriptEnabled: true,
              },
            }
          : {},
    },
  ].filter(Boolean);
};
module.exports = {
  entry: "./src/main.js",
  output: {
    path: isProduction ? path.resolve(__dirname, "../dist") : undefined,
    filename: isProduction
      ? "static/js/[name].[contenthash:10].js"
      : "static/js/[name].js",
    chunkFilename: isProduction
      ? "static/js/[name].[contenthash:10].chunk.js"
      : "static/js/[name].chunk.js",
    assetModuleFilename: "static/media/[hash:10][ext][query]",
    clean: true,
  },
  module: {
    rules: [
      // 处理css
      {
        test: /\.css$/,
        use: getStyleLoaders(),
      },
      //   处理less
      {
        test: /\.less$/,
        use: getStyleLoaders("less-loader"),
      },
      //   处理sass scss
      {
        test: /\.s[ac]ss$/,
        use: getStyleLoaders("sass-loader"),
      },
      //   处理stylus
      {
        test: /\.styl$/,
        use: getStyleLoaders("stylus-loader"),
      },
      //   处理图片
      {
        test: /\.(jpe?g|png|gif|webp|gsvg)$/,
        type: "asset",
        parser: {
          dataUrlCondition: {
            maxSize: 10 * 1024, // 4kb
          },
        },
      },
      //   处理其他资源
      {
        test: /\.(woff2?|ttf)$/,
        type: "asset/resource",
      },
      // 处理js
      {
        test: /\.jsx?$/,
        // exclude: /node_modules/,
        include: [path.resolve(__dirname, "../src")],
        use: [
          {
            loader: "thread-loader", // 开启多进程
            options: {
              workers: threads, // 数量
            },
          },
          {
            loader: "babel-loader",
            options: {
              cacheDirectory: true, // 开启缓存
              cacheCompression: false, //不压缩缓存
              plugins: [
                !isProduction && "react-refresh/babel", // 激活js的HMR功能
              ].filter(Boolean),
            },
          },
        ],

      },
    ],
  },
  plugins: [
    // Eslint
    new EslintWebpackPlugin({
      context: path.resolve(__dirname, "../src"),
      exclude: ["node_modules", "dist"],
      cache: true,
      cacheLocation: path.resolve(
        __dirname,
        "../node_modules/.cache/.eslintcache"
      ),
    }),
    // html
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "../public/index.html"),
    }),
    // css拆分
    isProduction &&
      new MiniCssExtractPlugin({
        filename: "static/css/[name].[contenthash:10].css",
        chunkFilename: "static/css/[name].[contenthash:10].chunk.css",
      }),
    // 拷贝public
    isProduction &&
      new CopyPlugin({
        patterns: [
          {
            from: path.resolve(__dirname, "../public"),
            to: path.resolve(__dirname, "../dist"),
            globOptions: {
              // 忽略文件
              ignore: ["**/index.html*"],
            },
          },
        ],
      }),
    !isProduction && new ReactRefreshWebpackPlugin(),
  ].filter(Boolean),
  mode: isProduction ? "production" : "development",
  devtool: isProduction ? "source-map" : "cheap-module-source-map",
  optimization: {
    splitChunks: {
      chunks: "all",
      cacheGroups: {
        // react react-dom react-router-dom 一起打包成一个包
        // antd 单独打包
        // 剩下的node_modules单独打包
        react: {
          test: /[\\/]node_modules[\\/]react(.*)?[\\/]/,
          name: "chunk-react",
          priority: 10,
        },
        antd: {
          test: /[\\/]node_modules[\\/]antd(.*)?[\\/]/,
          name: "chunk-antd",
          priority: 9,
        },
        libs: {
          test: /[\\/]node_modules[\\/]/,
          name: "chunk-lib",
          priority: 8,
        },
      },
    },
    runtimeChunk: {
      name: (entrypoint) => `runtime-chunk~${entrypoint.name}`,
    },
    // 是否需要压缩
    minimize: isProduction,
    // 压缩文件都在这里做
    minimizer: [
      // 这两个要一起出现
      new CssMinimizerWebpackPlugin(), // css压缩
      new TerserWebpackPlugin(), // js压缩
      new ImageMinimizerPlugin({
        minimizer: {
          implementation: ImageMinimizerPlugin.imageminGenerate,
          options: {
            plugins: [
              ["gifsicle", { interlaced: true }],
              ["jpegtran", { progressive: true }],
              ["optipng", { optimizationLevel: 5 }],
              [
                "svgo",
                {
                  plugins: [
                    "preset-default",
                    "prefixIds",
                    {
                      name: "sortAttrs",
                      params: {
                        xmlnsOrder: "alphabetical",
                      },
                    },
                  ],
                },
              ],
            ],
          },
        },
      }),
    ],
  },
  // webpack解析模块加载选项
  resolve: {
    extensions: [".js", ".jsx", ".json"],
  },
  devServer: {
    host: "localhost",
    port: 9527,
    open: false,
    historyApiFallback: true, //解决前端路由刷新404的问题
    hot: true, // 开启HMR
  },
  performance: false, // 关闭性能分析提升打包速度
};

优化配置

const EslintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin");
const os = require("os");
// cpu核数
const threads = os.cpus().length;
// 获取cross-env定义的环境变量
const isProduction = process.env.NODE_ENV === "production";

const path = require("path");
// 返回处理样式loader的函数
const getStyleLoaders = (pre) => {
  return [
    isProduction ? MiniCssExtractPlugin.loader : "style-loader",
    "css-loader",
    {
      // 处理css的兼容性
      // 配合package.json中的browserslist
      loader: "postcss-loader",
      options: {
        postcssOptions: {
          plugins: ["postcss-preset-env"],
        },
      },
    },
    // ++++++++++++++++++++++++++++++++++++++
    pre && {
      loader: pre,
      options:
        pre === "less-loader"
          ? {
              // antd的自定义主题色
              lessOptions: {
                modifyVars: { "@primary-color": "#ff6700" },
                javascriptEnabled: true,
              },
            }
          : {},
    },
    // ++++++++++++++++++++++++++++++++++++++
  ].filter(Boolean);
};
module.exports = {
  entry: "./src/main.js",
  output: {
    path: isProduction ? path.resolve(__dirname, "../dist") : undefined,
    filename: isProduction
      ? "static/js/[name].[contenthash:10].js"
      : "static/js/[name].js",
    chunkFilename: isProduction
      ? "static/js/[name].[contenthash:10].chunk.js"
      : "static/js/[name].chunk.js",
    assetModuleFilename: "static/media/[hash:10][ext][query]",
    clean: true,
  },
  module: {
    rules: [
      // 处理css
      {
        test: /\.css$/,
        use: getStyleLoaders(),
      },
      //   处理less
      {
        test: /\.less$/,
        use: getStyleLoaders("less-loader"),
      },
      //   处理sass scss
      {
        test: /\.s[ac]ss$/,
        use: getStyleLoaders("sass-loader"),
      },
      //   处理stylus
      {
        test: /\.styl$/,
        use: getStyleLoaders("stylus-loader"),
      },
      //   处理图片
      {
        test: /\.(jpe?g|png|gif|webp|gsvg)$/,
        type: "asset",
        parser: {
          dataUrlCondition: {
            maxSize: 10 * 1024, // 4kb
          },
        },
      },
      //   处理其他资源
      {
        test: /\.(woff2?|ttf)$/,
        type: "asset/resource",
      },
      // 处理js
      {
        test: /\.jsx?$/,
        // exclude: /node_modules/,
        include: [path.resolve(__dirname, "../src")],
        use: [
          {
            loader: "thread-loader", // 开启多进程
            options: {
              workers: threads, // 数量
            },
          },
          {
            loader: "babel-loader",
            options: {
              cacheDirectory: true, // 开启缓存
              cacheCompression: false, //不压缩缓存
              plugins: [
                !isProduction && "react-refresh/babel", // 激活js的HMR功能
              ].filter(Boolean),
            },
          },
        ],

      },
    ],
  },
  plugins: [
    // Eslint
    new EslintWebpackPlugin({
      context: path.resolve(__dirname, "../src"),
      exclude: ["node_modules", "dist"],
      cache: true,
      cacheLocation: path.resolve(
        __dirname,
        "../node_modules/.cache/.eslintcache"
      ),
    }),
    // html
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "../public/index.html"),
    }),
    // css拆分
    isProduction &&
      new MiniCssExtractPlugin({
        filename: "static/css/[name].[contenthash:10].css",
        chunkFilename: "static/css/[name].[contenthash:10].chunk.css",
      }),
    // 拷贝public
    isProduction &&
      new CopyPlugin({
        patterns: [
          {
            from: path.resolve(__dirname, "../public"),
            to: path.resolve(__dirname, "../dist"),
            globOptions: {
              // 忽略文件
              ignore: ["**/index.html*"],
            },
          },
        ],
      }),
    !isProduction && new ReactRefreshWebpackPlugin(),
  ].filter(Boolean),
  mode: isProduction ? "production" : "development",
  devtool: isProduction ? "source-map" : "cheap-module-source-map",
  optimization: {
    splitChunks: {
      chunks: "all",
      // ++++++++++++++++++++++++++++++++++++++
      cacheGroups: {
        // react react-dom react-router-dom 一起打包成一个包
        // antd 单独打包
        // 剩下的node_modules单独打包
        react: {
          test: /[\\/]node_modules[\\/]react(.*)?[\\/]/,
          name: "chunk-react",
          priority: 10,
        },
        antd: {
          test: /[\\/]node_modules[\\/]antd(.*)?[\\/]/,
          name: "chunk-antd",
          priority: 9,
        },
        libs: {
          test: /[\\/]node_modules[\\/]/,
          name: "chunk-lib",
          priority: 8,
        },
      },
      // ++++++++++++++++++++++++++++++++++++++
    },
    runtimeChunk: {
      name: (entrypoint) => `runtime-chunk~${entrypoint.name}`,
    },
    // 是否需要压缩
    minimize: isProduction,
    // 压缩文件都在这里做
    minimizer: [
      // 这两个要一起出现
      new CssMinimizerWebpackPlugin(), // css压缩
      new TerserWebpackPlugin(), // js压缩
      new ImageMinimizerPlugin({
        minimizer: {
          implementation: ImageMinimizerPlugin.imageminGenerate,
          options: {
            plugins: [
              ["gifsicle", { interlaced: true }],
              ["jpegtran", { progressive: true }],
              ["optipng", { optimizationLevel: 5 }],
              [
                "svgo",
                {
                  plugins: [
                    "preset-default",
                    "prefixIds",
                    {
                      name: "sortAttrs",
                      params: {
                        xmlnsOrder: "alphabetical",
                      },
                    },
                  ],
                },
              ],
            ],
          },
        },
      }),
    ],
  },
  // webpack解析模块加载选项
  resolve: {
    extensions: [".js", ".jsx", ".json"],
  },
  devServer: {
    host: "localhost",
    port: 9527,
    open: false,
    historyApiFallback: true, //解决前端路由刷新404的问题
    hot: true, // 开启HMR
  },
  // ++++++++++++++++++++++++++++++++++++++
  performance: false, // 关闭性能分析提升打包速度
  // ++++++++++++++++++++++++++++++++++++++
};

Vue 脚手架

webpack.dev.js

const EslintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { VueLoaderPlugin } = require("vue-loader");
const { DefinePlugin } = require("webpack");
const path = require("path");
// 返回处理样式loader的函数
const getStyleLoaders = (pre) => {
  return [
    "vue-style-loader",
    "css-loader",
    {
      // 处理css的兼容性
      // 配合package.json中的browserslist
      loader: "postcss-loader",
      options: {
        postcssOptions: {
          plugins: ["postcss-preset-env"],
        },
      },
    },
    pre,
  ].filter(Boolean);
};
module.exports = {
  entry: "./src/main.js",
  output: {
    path: undefined,
    filename: "static/js/[name].js",
    chunkFilename: "static/js/[name].chunk.js",
    assetModuleFilename: "static/media/[hash:10][ext][query]",
  },
  module: {
    rules: [
      // 处理css
      {
        test: /\.css$/,
        use: getStyleLoaders(),
      },
      //   处理less
      {
        test: /\.less$/,
        use: getStyleLoaders("less-loader"),
      },
      //   处理sass scss
      {
        test: /\.s[ac]ss$/,
        use: getStyleLoaders("sass-loader"),
      },
      //   处理stylus
      {
        test: /\.styl$/,
        use: getStyleLoaders("stylus-loader"),
      },
      //   处理图片
      {
        test: /\.(jpe?g|png|gif|webp|gsvg)$/,
        type: "asset",
        parser: {
          dataUrlCondition: {
            maxSize: 10 * 1024, // 4kb
          },
        },
      },
      //   处理其他资源
      {
        test: /\.(woff2?|ttf)$/,
        type: "asset/resource",
      },
      // 处理js
      {
        test: /\.js$/,
        // exclude: /node_modules/,
        include: [path.resolve(__dirname, "../src")],
        loader: "babel-loader",
        options: {
          cacheDirectory: true, // 开启缓存
          cacheCompression: false, //不压缩缓存
        },
      },
      // 处理 vue
      {
        test: /\.vue$/,
        loader: "vue-loader",
      },
    ],
  },
  plugins: [
    // Eslint
    new EslintWebpackPlugin({
      context: path.resolve(__dirname, "../src"),
      exclude: ["node_modules", "dist"],
      cache: true,
      cacheLocation: path.resolve(
        __dirname,
        "../node_modules/.cache/.eslintcache"
      ),
    }),
    // html
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "../public/index.html"),
    }),
    new VueLoaderPlugin(),
    // cress-enr定义的环境变量是给打包工具使用
    // DefinePlugin是给项目使用的
    new DefinePlugin({
      __VUE_OPTIONS_API__: true,
      __VUE_PROD_DEVTOOLS__: false,
    }),
  ],
  mode: "development",
  devtool: "cheap-module-source-map",
  optimization: {
    splitChunks: {
      chunks: "all",
    },
    runtimeChunk: {
      name: (entrypoint) => `runtime-chunk~${entrypoint.name}`,
    },
  },
  // webpack解析模块加载选项
  resolve: {
    extensions: [".js", ".vue", ".json"],
  },
  devServer: {
    host: "localhost",
    port: 9527,
    open: false,
    historyApiFallback: true, //解决前端路由刷新404的问题
    hot: true, // 开启HMR
  },
};

webpack.prod.js

const EslintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const { VueLoaderPlugin } = require("vue-loader");
const { DefinePlugin } = require("webpack");

const path = require("path");
// 返回处理样式loader的函数
const getStyleLoaders = (pre) => {
  return [
    MiniCssExtractPlugin.loader,
    "css-loader",
    {
      // 处理css的兼容性
      // 配合package.json中的browserslist
      loader: "postcss-loader",
      options: {
        postcssOptions: {
          plugins: ["postcss-preset-env"],
        },
      },
    },
    pre,
  ].filter(Boolean);
};
module.exports = {
  entry: "./src/main.js",
  output: {
    path: path.resolve(__dirname, "../dist"),
    filename: "static/js/[name].[contenthash:10].js",
    chunkFilename: "static/js/[name].[contenthash:10].chunk.js",
    assetModuleFilename: "static/media/[hash:10][ext][query]",
    clean: true,
  },
  module: {
    rules: [
      // 处理css
      {
        test: /\.css$/,
        use: getStyleLoaders(),
      },
      //   处理less
      {
        test: /\.less$/,
        use: getStyleLoaders("less-loader"),
      },
      //   处理sass scss
      {
        test: /\.s[ac]ss$/,
        use: getStyleLoaders("sass-loader"),
      },
      //   处理stylus
      {
        test: /\.styl$/,
        use: getStyleLoaders("stylus-loader"),
      },
      //   处理图片
      {
        test: /\.(jpe?g|png|gif|webp|gsvg)$/,
        type: "asset",
        parser: {
          dataUrlCondition: {
            maxSize: 10 * 1024, // 4kb
          },
        },
      },
      //   处理其他资源
      {
        test: /\.(woff2?|ttf)$/,
        type: "asset/resource",
      },
      // 处理js
      {
        test: /\.js$/,
        // exclude: /node_modules/,
        include: [path.resolve(__dirname, "../src")],
        loader: "babel-loader",
        options: {
          cacheDirectory: true, // 开启缓存
          cacheCompression: false, //不压缩缓存
        },
      },
      // 处理 vue
      {
        test: /\.vue$/,
        loader: "vue-loader",
      },
    ],
  },
  plugins: [
    // Eslint
    new EslintWebpackPlugin({
      context: path.resolve(__dirname, "../src"),
      exclude: ["node_modules", "dist"],
      cache: true,
      cacheLocation: path.resolve(
        __dirname,
        "../node_modules/.cache/.eslintcache"
      ),
    }),
    // html
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "../public/index.html"),
    }),
    // css拆分
    new MiniCssExtractPlugin({
      filename: "static/css/[name].[contenthash:10].css",
      chunkFilename: "static/css/[name].[contenthash:10].chunk.css",
    }),
    // 拷贝public
    new CopyPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, "../public"),
          to: path.resolve(__dirname, "../dist"),
          globOptions: {
            // 忽略文件
            ignore: ["**/index.html*"],
          },
        },
      ],
    }),
    new VueLoaderPlugin(),
    // cress-enr定义的环境变量是给打包工具使用
    // DefinePlugin是给项目使用的
    new DefinePlugin({
      __VUE_OPTIONS_API__: true,
      __VUE_PROD_DEVTOOLS__: false,
    }),
  ],
  mode: "production",
  devtool: "cheap-module-source-map",
  optimization: {
    splitChunks: {
      chunks: "all",
    },
    runtimeChunk: {
      name: (entrypoint) => `runtime-chunk~${entrypoint.name}`,
    },
    // 压缩文件都在这里做
    minimizer: [
      // 这两个要一起出现
      new CssMinimizerWebpackPlugin(), // css压缩
      new TerserWebpackPlugin(), // js压缩
      new ImageMinimizerPlugin({
        minimizer: {
          implementation: ImageMinimizerPlugin.imageminGenerate,
          options: {
            plugins: [
              ["gifsicle", { interlaced: true }],
              ["jpegtran", { progressive: true }],
              ["optipng", { optimizationLevel: 5 }],
              [
                "svgo",
                {
                  plugins: [
                    "preset-default",
                    "prefixIds",
                    {
                      name: "sortAttrs",
                      params: {
                        xmlnsOrder: "alphabetical",
                      },
                    },
                  ],
                },
              ],
            ],
          },
        },
      }),
    ],
  },
  // webpack解析模块加载选项
  resolve: {
    extensions: [".js", ".vue", ".json"],
  },
  devServer: {
    host: "localhost",
    port: 9527,
    open: false,
    historyApiFallback: true, //解决前端路由刷新404的问题
    hot: true, // 开启HMR
  },
};

package.json

{
  "name": "webpack_vue",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "npm run dev",
    "dev": "cross-env NODE_ENV=development webpack serve --config ./config/webpack.config.js",
    "build": "cross-env NODE_ENV=production webpack --config ./config/webpack.config.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "browerslist": [
    "last 2 versions",
    "> 1%",
    "ie >= 9"
  ],
  "devDependencies": {
    "@babel/eslint-parser": "^7.23.3",
    "@babel/preset-env": "^7.23.5",
    "@vue/cli-plugin-babel": "^5.0.8",
    "babel-loader": "^9.1.3",
    "copy-webpack-plugin": "^11.0.0",
    "cross-env": "^7.0.3",
    "css-loader": "^6.8.1",
    "css-minimizer-webpack-plugin": "^5.0.1",
    "eslint-plugin-vue": "^9.19.2",
    "eslint-webpack-plugin": "^4.0.1",
    "html-webpack-plugin": "^5.5.4",
    "image-minimizer-webpack-plugin": "^3.8.3",
    "imagemin": "^8.0.1",
    "imagemin-gifsicle": "^7.0.0",
    "imagemin-jpegtran": "^7.0.0",
    "imagemin-optipng": "^8.0.0",
    "imagemin-svgo": "^10.0.1",
    "less-loader": "^11.1.3",
    "mini-css-extract-plugin": "^2.7.6",
    "postcss-loader": "^7.3.3",
    "postcss-preset-env": "^9.3.0",
    "progress-bar-webpack-plugin": "^2.1.0",
    "sass": "^1.69.5",
    "sass-loader": "^13.3.2",
    "style-loader": "^3.3.3",
    "stylus-loader": "^7.1.3",
    "unplugin-auto-import": "^0.7.1",
    "unplugin-vue-components": "^0.19.3",
    "vue-loader": "^17.3.1",
    "vue-style-loader": "^4.1.3",
    "vue-template-compiler": "^2.7.15",
    "webpack": "^5.89.0",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^4.15.1"
  },
  "dependencies": {
    "element-plus": "^2.4.3",
    "vue": "^3.3.11",
    "vue-router": "^4.2.5"
  }
}

.eslintrc.js

module.exports = {
  root: true,
  env: {
    node: true,
  },
  extends: ["plugin:vue/vue3-essential", "eslint:recommended"],
  parserOptions: {
    parser: "@babel/eslint-parser",
  },
};

babel.config.js

module.exports = {
  presets: ["@vue/cli-plugin-babel/preset"],
};

.babelrc

{
  "presets": ["@babel/preset-env"]
}

webpack.config.js

const EslintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const { VueLoaderPlugin } = require("vue-loader");
const { DefinePlugin } = require("webpack");
const AutoImport = require("unplugin-auto-import/webpack");
const Components = require("unplugin-vue-components/webpack");
const { ElementPlusResolver } = require("unplugin-vue-components/resolvers");
const ProgressBarPlugin = require("progress-bar-webpack-plugin");

const isProcuction = process.env.NODE_ENV === "production";

const path = require("path");
// 返回处理样式loader的函数
const getStyleLoaders = (pre) => {
  return [
    isProcuction ? MiniCssExtractPlugin.loader : "vue-style-loader",
    "css-loader",
    {
      // 处理css的兼容性
      // 配合package.json中的browserslist
      loader: "postcss-loader",
      options: {
        postcssOptions: {
          plugins: ["postcss-preset-env"],
        },
      },
    },
    pre && {
      loader: pre,
      options:
        pre === "sass-loader"
          ? {
              // additionalData: `@use "@/styles/element/index.scss" as *;`,  // 自定义主题颜色
            }
          : {},
    },
  ].filter(Boolean);
};
module.exports = {
  entry: "./src/main.js",
  output: {
    path: isProcuction ? path.resolve(__dirname, "../dist") : undefined,
    filename: isProcuction
      ? "static/js/[name].[contenthash:10].js"
      : "static/js/[name].js",
    chunkFilename: isProcuction
      ? "static/js/[name].[contenthash:10].chunk.js"
      : "static/js/[name].chunk.js",
    assetModuleFilename: "static/media/[hash:10][ext][query]",
    clean: true,
  },
  module: {
    rules: [
      // 处理css
      {
        test: /\.css$/,
        use: getStyleLoaders(),
      },
      //   处理less
      {
        test: /\.less$/,
        use: getStyleLoaders("less-loader"),
      },
      //   处理sass scss
      {
        test: /\.s[ac]ss$/,
        use: getStyleLoaders("sass-loader"),
      },
      //   处理stylus
      {
        test: /\.styl$/,
        use: getStyleLoaders("stylus-loader"),
      },
      //   处理图片
      {
        test: /\.(jpe?g|png|gif|webp|gsvg)$/,
        type: "asset",
        parser: {
          dataUrlCondition: {
            maxSize: 10 * 1024, // 4kb
          },
        },
      },
      //   处理其他资源
      {
        test: /\.(woff2?|ttf)$/,
        type: "asset/resource",
      },
      // 处理js
      {
        test: /\.js$/,
        // exclude: /node_modules/,
        include: [path.resolve(__dirname, "../src")],
        loader: "babel-loader",
        options: {
          cacheDirectory: true, // 开启缓存
          cacheCompression: false, //不压缩缓存
        },
      },
      // 处理 vue
      {
        test: /\.vue$/,
        loader: "vue-loader",
        options: {
          cacheDirectory: path.resolve(
            __dirname,
            "../node_modules/.cache/vue-loader"
          ),
        },
      },
    ],
  },
  plugins: [
    // Eslint
    new EslintWebpackPlugin({
      context: path.resolve(__dirname, "../src"),
      exclude: ["node_modules", "dist"],
      cache: true,
      cacheLocation: path.resolve(
        __dirname,
        "../node_modules/.cache/.eslintcache"
      ),
    }),
    // html
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "../public/index.html"),
    }),
    // css拆分
    isProcuction &&
      new MiniCssExtractPlugin({
        filename: "static/css/[name].[contenthash:10].css",
        chunkFilename: "static/css/[name].[contenthash:10].chunk.css",
      }),
    // 拷贝public
    isProcuction &&
      new CopyPlugin({
        patterns: [
          {
            from: path.resolve(__dirname, "../public"),
            to: path.resolve(__dirname, "../dist"),
            globOptions: {
              // 忽略文件
              ignore: ["**/index.html*"],
            },
          },
        ],
      }),
    new VueLoaderPlugin(),
    // cress-enr定义的环境变量是给打包工具使用
    // DefinePlugin是给项目使用的
    new DefinePlugin({
      __VUE_OPTIONS_API__: true,
      __VUE_PROD_DEVTOOLS__: false,
    }),
    // 按需加载Elementplsu的配置
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    // 自定义主题的配置,引入sass
    Components({
      resolvers: [
        ElementPlusResolver({
          // 自定义主题,引入sass
          importStyle: "sass",
        }),
      ],
    }),
    // 进度条
    new ProgressBarPlugin(),
  ].filter(Boolean),
  mode: isProcuction ? "production" : "development",
  devtool: isProcuction ? "cheap-module-source-map" : "source-map",
  optimization: {
    splitChunks: {
      chunks: "all",
      cacheGroups: {
        vue: {
          test: /[\\/]node_modules[\\/]vue(.*)[\\/]/,
          name: "vue-chunk",
          priority: 20,
        },
        elementPlus: {
          test: /[\\/]node_modules[\\/]element-plus[\\/]/,
          name: "elementPlus-chunk",
          priority: 18,
        },
        libs: {
          test: /[\\/]node_modules[\\/]/,
          name: "libs-chunk",
          priority: 16,
        },
      },
    },
    runtimeChunk: {
      name: (entrypoint) => `runtime-chunk~${entrypoint.name}`,
    },
    minimize: isProcuction,
    // 压缩文件都在这里做
    minimizer: [
      // 这两个要一起出现
      new CssMinimizerWebpackPlugin(), // css压缩
      new TerserWebpackPlugin(), // js压缩
      new ImageMinimizerPlugin({
        minimizer: {
          implementation: ImageMinimizerPlugin.imageminGenerate,
          options: {
            plugins: [
              ["gifsicle", { interlaced: true }],
              ["jpegtran", { progressive: true }],
              ["optipng", { optimizationLevel: 5 }],
              [
                "svgo",
                {
                  plugins: [
                    "preset-default",
                    "prefixIds",
                    {
                      name: "sortAttrs",
                      params: {
                        xmlnsOrder: "alphabetical",
                      },
                    },
                  ],
                },
              ],
            ],
          },
        },
      }),
    ],
  },
  // webpack解析模块加载选项
  resolve: {
    extensions: [".js", ".vue", ".json"],
    // 路径别名
    alias: {
      "@": path.resolve(__dirname, "src"),
    },
  },
  devServer: {
    host: "localhost",
    port: 9527,
    open: false,
    historyApiFallback: true, //解决前端路由刷新404的问题
    hot: true, // 开启HMR
  },
  performance: false,
};

优化配置

const EslintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const { VueLoaderPlugin } = require("vue-loader");
const { DefinePlugin } = require("webpack");
// ++++++++++++++++++++++++++++++++++++++
const AutoImport = require("unplugin-auto-import/webpack");
const Components = require("unplugin-vue-components/webpack");
const { ElementPlusResolver } = require("unplugin-vue-components/resolvers");
// ++++++++++++++++++++++++++++++++++++++
const ProgressBarPlugin = require("progress-bar-webpack-plugin");

const isProcuction = process.env.NODE_ENV === "production";

const path = require("path");
// 返回处理样式loader的函数
const getStyleLoaders = (pre) => {
  return [
    isProcuction ? MiniCssExtractPlugin.loader : "vue-style-loader",
    "css-loader",
    {
      // 处理css的兼容性
      // 配合package.json中的browserslist
      loader: "postcss-loader",
      options: {
        postcssOptions: {
          plugins: ["postcss-preset-env"],
        },
      },
    },
    // ++++++++++++++++++++++++++++++++++++++
    pre && {
      loader: pre,
      options:
        pre === "sass-loader"
          ? {
              // additionalData: `@use "@/styles/element/index.scss" as *;`,  // 自定义主题颜色
            }
          : {},
    },
    // ++++++++++++++++++++++++++++++++++++++
  ].filter(Boolean);
};
module.exports = {
  entry: "./src/main.js",
  output: {
    path: isProcuction ? path.resolve(__dirname, "../dist") : undefined,
    filename: isProcuction
      ? "static/js/[name].[contenthash:10].js"
      : "static/js/[name].js",
    chunkFilename: isProcuction
      ? "static/js/[name].[contenthash:10].chunk.js"
      : "static/js/[name].chunk.js",
    assetModuleFilename: "static/media/[hash:10][ext][query]",
    clean: true,
  },
  module: {
    rules: [
      // 处理css
      {
        test: /\.css$/,
        use: getStyleLoaders(),
      },
      //   处理less
      {
        test: /\.less$/,
        use: getStyleLoaders("less-loader"),
      },
      //   处理sass scss
      {
        test: /\.s[ac]ss$/,
        use: getStyleLoaders("sass-loader"),
      },
      //   处理stylus
      {
        test: /\.styl$/,
        use: getStyleLoaders("stylus-loader"),
      },
      //   处理图片
      {
        test: /\.(jpe?g|png|gif|webp|gsvg)$/,
        type: "asset",
        parser: {
          dataUrlCondition: {
            maxSize: 10 * 1024, // 4kb
          },
        },
      },
      //   处理其他资源
      {
        test: /\.(woff2?|ttf)$/,
        type: "asset/resource",
      },
      // 处理js
      {
        test: /\.js$/,
        // exclude: /node_modules/,
        include: [path.resolve(__dirname, "../src")],
        loader: "babel-loader",
        options: {
          cacheDirectory: true, // 开启缓存
          cacheCompression: false, //不压缩缓存
        },
      },
      // 处理 vue
      {
        test: /\.vue$/,
        loader: "vue-loader",
        options: {
          cacheDirectory: path.resolve(
            __dirname,
            "../node_modules/.cache/vue-loader"
          ),
        },
      },
    ],
  },
  plugins: [
    // Eslint
    new EslintWebpackPlugin({
      context: path.resolve(__dirname, "../src"),
      exclude: ["node_modules", "dist"],
      cache: true,
      cacheLocation: path.resolve(
        __dirname,
        "../node_modules/.cache/.eslintcache"
      ),
    }),
    // html
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "../public/index.html"),
    }),
    // css拆分
    isProcuction &&
      new MiniCssExtractPlugin({
        filename: "static/css/[name].[contenthash:10].css",
        chunkFilename: "static/css/[name].[contenthash:10].chunk.css",
      }),
    // 拷贝public
    isProcuction &&
      new CopyPlugin({
        patterns: [
          {
            from: path.resolve(__dirname, "../public"),
            to: path.resolve(__dirname, "../dist"),
            globOptions: {
              // 忽略文件
              ignore: ["**/index.html*"],
            },
          },
        ],
      }),
    new VueLoaderPlugin(),
    // cress-enr定义的环境变量是给打包工具使用
    // DefinePlugin是给项目使用的
    new DefinePlugin({
      __VUE_OPTIONS_API__: true,
      __VUE_PROD_DEVTOOLS__: false,
    }),
    // ++++++++++++++++++++++++++++++++++++++
    // 按需加载Elementplsu的配置
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    // 自定义主题的配置,引入sass
    Components({
      resolvers: [
        ElementPlusResolver({
          // 自定义主题,引入sass
          importStyle: "sass",
        }),
      ],
    }),
    // ++++++++++++++++++++++++++++++++++++++
    // 进度条
    new ProgressBarPlugin(),
  ].filter(Boolean),
  mode: isProcuction ? "production" : "development",
  devtool: isProcuction ? "cheap-module-source-map" : "source-map",
  optimization: {
    splitChunks: {
      chunks: "all",
      // ++++++++++++++++++++++++++++++++++++++
      cacheGroups: {
        vue: {
          test: /[\\/]node_modules[\\/]vue(.*)[\\/]/,
          name: "vue-chunk",
          priority: 20,
        },
        elementPlus: {
          test: /[\\/]node_modules[\\/]element-plus[\\/]/,
          name: "elementPlus-chunk",
          priority: 18,
        },
        libs: {
          test: /[\\/]node_modules[\\/]/,
          name: "libs-chunk",
          priority: 16,
        },
      },
      // ++++++++++++++++++++++++++++++++++++++
    },
    runtimeChunk: {
      name: (entrypoint) => `runtime-chunk~${entrypoint.name}`,
    },
    minimize: isProcuction,
    // 压缩文件都在这里做
    minimizer: [
      // 这两个要一起出现
      new CssMinimizerWebpackPlugin(), // css压缩
      new TerserWebpackPlugin(), // js压缩
      new ImageMinimizerPlugin({
        minimizer: {
          implementation: ImageMinimizerPlugin.imageminGenerate,
          options: {
            plugins: [
              ["gifsicle", { interlaced: true }],
              ["jpegtran", { progressive: true }],
              ["optipng", { optimizationLevel: 5 }],
              [
                "svgo",
                {
                  plugins: [
                    "preset-default",
                    "prefixIds",
                    {
                      name: "sortAttrs",
                      params: {
                        xmlnsOrder: "alphabetical",
                      },
                    },
                  ],
                },
              ],
            ],
          },
        },
      }),
    ],
  },
  // webpack解析模块加载选项
  resolve: {
    extensions: [".js", ".vue", ".json"],
    // ++++++++++++++++++++++++++++++++++++++
    // 路径别名
    alias: {
      "@": path.resolve(__dirname, "src"),
    },
    // ++++++++++++++++++++++++++++++++++++++
  },
  devServer: {
    host: "localhost",
    port: 9527,
    open: false,
    historyApiFallback: true, //解决前端路由刷新404的问题
    hot: true, // 开启HMR
  },
  // ++++++++++++++++++++++++++++++++++++++
  performance: false,
  // ++++++++++++++++++++++++++++++++++++++
};