webpack5项目搭建React-Cli(配置合并)

Posted 天界程序员

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了webpack5项目搭建React-Cli(配置合并)相关的知识,希望对你有一定的参考价值。

对于开发环境的配置和生产环境的配置,有大部分代码配置是重复的,因此我们希望将配置合并减少代码体积。

我们在config目录下新建一个新的文件: webpack.config.js

step1–判断环境类型

对于什么时候是开发环境,什么时候是生产环境,我们可以通过process.env.NODE_ENV的值来判断。

// 需要通过 cross-env 定义环境变量
const isProduction = process.env.NODE_ENV === "production";

step2–修改输出目录与命名方式

 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/js/[hash:10][ext][query]",
    clean: true,
  ,

step3–判断CSS是否提取为单独文件

const getStyleLoaders = (preProcessor) => 
  return [
    isProduction ? MiniCssExtractPlugin.loader : "style-loader",
    "css-loader",
    
      loader: "postcss-loader",
      options: 
        postcssOptions: 
          plugins: [
            "postcss-preset-env", // 能解决大多数样式兼容性问题
          ],
        ,
      ,
    ,
    preProcessor,
  ].filter(Boolean);
;

过滤插件:

plugins: [
   //...
    isProduction &&
      new MiniCssExtractPlugin(
        filename: "static/css/[name].[contenthash:10].css",
        chunkFilename: "static/css/[name].[contenthash:10].chunk.css",
      ),
  ].filter(Boolean),

step4–判断是否开启HMR功能

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

  test: /\\.(jsx|js)$/,
  include: path.resolve(__dirname, "../src"),
  loader: "babel-loader",
  options: 
    cacheDirectory: true, // 开启babel编译缓存
    cacheCompression: false, // 缓存文件不要压缩
    plugins: [
      // "@babel/plugin-transform-runtime",  // presets中包含了
      !isProduction && "react-refresh/babel",
    ].filter(Boolean),
  ,
,

过滤插件:

plugins: [
   //...
    !isProduction && new ReactRefreshWebpackPlugin(),
  ].filter(Boolean),

step5–判断模式的值

mode: isProduction ? "production" : "development",

step6–判断sourceMap的值

devtool: isProduction ? "source-map" : "cheap-module-source-map",

step7–判断是否开启代码压缩

 optimization: 
    minimize: isProduction,
    // ...
 

如果是生产环境就开启代码压缩,反之则关闭

step8–引入DevServer

devServer: 
    open: true,
    host: "localhost",
    port: 3000,
    hot: true,
    compress: true,
    historyApiFallback: true,
  ,

step9–现阶段合并的配置代码

const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const htmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin");

// 需要通过 cross-env 定义环境变量
const isProduction = process.env.NODE_ENV === "production";

const getStyleLoaders = (preProcessor) => 
  return [
    isProduction ? MiniCssExtractPlugin.loader : "style-loader",
    "css-loader",
    
      loader: "postcss-loader",
      options: 
        postcssOptions: 
          plugins: [
            "postcss-preset-env", // 能解决大多数样式兼容性问题
          ],
        ,
      ,
    ,
    preProcessor,
  ].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/js/[hash:10][ext][query]",
    clean: true,
  ,
  module: 
    rules: [
      
        oneOf: [
          
            // 用来匹配 .css 结尾的文件
            test: /\\.css$/,
            // use 数组里面 Loader 执行顺序是从右到左
            use: getStyleLoaders(),
          ,
          
            test: /\\.less$/,
            use: getStyleLoaders("less-loader"),
          ,
          
            test: /\\.s[ac]ss$/,
            use: getStyleLoaders("sass-loader"),
          ,
          
            test: /\\.styl$/,
            use: getStyleLoaders("stylus-loader"),
          ,
          
            test: /\\.(png|jpe?g|gif|svg)$/,
            type: "asset",
            parser: 
              dataUrlCondition: 
                maxSize: 10 * 1024, // 小于10kb的图片会被base64处理
              ,
            ,
          ,
          
            test: /\\.(ttf|woff2?)$/,
            type: "asset/resource",
          ,
          
            test: /\\.(jsx|js)$/,
            include: path.resolve(__dirname, "../src"),
            loader: "babel-loader",
            options: 
              cacheDirectory: true, // 开启babel编译缓存
              cacheCompression: false, // 缓存文件不要压缩
              plugins: [
                // "@babel/plugin-transform-runtime",  // presets中包含了
                !isProduction && "react-refresh/babel",
              ].filter(Boolean),
            ,
          ,
        ],
      ,
    ],
  ,
  plugins: [
    new ESLintWebpackPlugin(
      extensions: [".js", ".jsx"],
      context: path.resolve(__dirname, "../src"),
      exclude: "node_modules",
      cache: true,
      cacheLocation: path.resolve(
        __dirname,
        "../node_modules/.cache/.eslintcache"
      ),
    ),
    new HtmlWebpackPlugin(
      template: path.resolve(__dirname, "../public/index.html"),
    ),
    isProduction &&
      new MiniCssExtractPlugin(
        filename: "static/css/[name].[contenthash:10].css",
        chunkFilename: "static/css/[name].[contenthash:10].chunk.css",
      ),
    !isProduction && new ReactRefreshWebpackPlugin(),
  ].filter(Boolean),
  optimization: 
    minimize: isProduction,
    // 压缩的操作
    minimizer: [
      // 压缩css
      new CssMinimizerPlugin(),
      // 压缩js
      new TerserWebpackPlugin(),
      // 压缩图片
      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",
                      ,
                    ,
                  ],
                ,
              ],
            ],
          ,
        ,
      ),
    ],
    // 代码分割配置
    splitChunks: 
      chunks: "all",
      // 其他都用默认值
    ,
    runtimeChunk: 
      name: (entrypoint) => `runtime~$entrypoint.name`,
    ,
  ,
  resolve: 
    extensions: [".jsx", ".js", ".json"],
  ,
  devServer: 
    open: true,
    host: "localhost",
    port: 3000,
    hot: true,
    compress: true,
    historyApiFallback: true,
  ,
  mode: isProduction ? "production" : "development",
  devtool: isProduction ? "source-map" : "cheap-module-source-map",
;

step10–新的启动命令

 "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"
  ,

以上是关于webpack5项目搭建React-Cli(配置合并)的主要内容,如果未能解决你的问题,请参考以下文章

webpack5项目搭建React-Cli(开发模式)

webpack5项目搭建React-Cli(生产模式)

webpack5项目搭建Vue-Cli(生产环境)

webpack5项目搭建Vue-Cli(配置优化)

webpack5项目搭建Vue-Cli(合并配置)

webpack5项目搭建Vue-Cli(开发模式)