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

Posted 天界程序员

tags:

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

生产模式我们就是在开发环境下面进行改造。

step1–复制一份开发配置

复制一份开发模式的配置文件在config目录下面,并改名为webpack.prod.js

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

output: 
    path: path.resolve(__dirname, "../dist"), // 打包输出的目录
    filename: "static/js/[name].[contenthash:10].js",
    chunkFilename: "static/js/[name].[contenthash:10].chunk.js",
    assetModuleFilename: "static/js/[hash:10][ext][query]",
    clean: true,//清空上一次打包的资源
,

由于生产环境为了保证每一次打包都是最新的代码,这里开启了上一次打包资源清空的配置。

step3–提取CSS样式成单独文件

这里需要使用到插件:mini-css-extract-plugin

1、引入插件并取代公共loader函数里面的style-loader

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

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

2、开启插件并配置其他选项

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

step4–CSS压缩

需要使用到的插件:css-minimizer-webpack-plugin

const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");

  optimization: 
    // 压缩的操作
    minimizer: [
      new CssMinimizerPlugin(),
    ]
  

step5–JS压缩

需要使用到的插件:terser-webpack-plugin,webpack5自带,无需额外安装。

const TerserWebpackPlugin = require("terser-webpack-plugin");

optimization: 
    // 压缩的操作
    minimizer: [
      new TerserWebpackPlugin(),
    ]
  

step6–修改模式为生产模式

当环境是生产模式时webpack会自动对html进行压缩

 mode: "production"

step7–修改sourceMap的方式

devtool: "source-map",

step8–移除开发服务器与自动化

  // devServer: 
  //   open: false,
  //   host: "localhost",
  //   port: 3000,
  //   hot: true,
  //   historyApiFallback: true, // 解决react-router刷新404问题
  // ,

step9–移除HMR功能

// const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
// babel处理js|jsx资源
      
        test: /\\.(js|jsx)$/,
        loader: 'babel-loader',
        options: 
          cacheDirectory: true,
          cacheCompression: false,
          // plugins: [
          //   // "@babel/plugin-transform-runtime", // presets中包含了
          //  'react-refresh/babel', // 开启js的HMR功能
          // ],
        ,
      
// new ReactRefreshWebpackPlugin(),

step10–图片压缩

使用的插件:image-minimizer-webpack-plugin, 包比较难下载

const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
optimization: 
    // 压缩的操作
    minimizer: [
      new CssMinimizerPlugin(),
      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",
                      ,
                    ,
                  ],
                ,
              ],
            ],
          ,
        ,
      ),
    ],
  ,

step11–安装依赖包

npm i mini-css-extract-plugin css-minimizer-webpack-plugin -D
npm i image-minimizer-webpack-plugin imagemin -D
// 无损压缩
npm install imagemin-gifsicle imagemin-jpegtran imagemin-optipng imagemin-svgo -D

step12–配置打包命令

"build": "cross-env NODE_ENV=production webpack --config ./config/webpack.prod.js"
  • 运行命令
npm run build

观察dist目录文件。

step13–复制公共资源到打包目录

复制公共资源到打包目录:如网站图标等需要复制到dist目录

使用到的插件:copy-webpack-plugin

  • 安装依赖
npm i copy-webpack-plugin -D
  • 使用
const CopyPlugin = require("copy-webpack-plugin");
// 将public下面的资源复制到dist目录去(除了index.html)
    new CopyPlugin(
      patterns: [
        
          from: path.resolve(__dirname, "../public"),
          to: path.resolve(__dirname, "../dist"),
          toType: "dir",
          noErrorOnMissing: true, // 不生成错误
          globOptions: 
            // 忽略文件
            ignore: ["**/index.html"],
          ,
          info: 
            // 跳过terser压缩js
            minimized: true,
          ,
        ,
      ],
    ),

step14–现阶段详细的生产环境配置

// webpack.prod.js
const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");

const getStyleLoaders = (preProcessor) => 
  return [
    MiniCssExtractPlugin.loader,
    "css-loader",
    
      loader: "postcss-loader",
      options: 
        postcssOptions: 
          plugins: [
            "postcss-preset-env", // 能解决大多数样式兼容性问题
          ],
        ,
      ,
    ,
    preProcessor,
  ].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/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,
              cacheCompression: false,
              plugins: [
                // "@babel/plugin-transform-runtime" // presets中包含了
              ],
            ,
          ,
        ],
      ,
    ],
  ,
  plugins: [
    new ESLintWebpackPlugin(
      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"),
    ),
    new MiniCssExtractPlugin(
      filename: "static/css/[name].[contenthash:10].css",
      chunkFilename: "static/css/[name].[contenthash:10].chunk.css",
    ),
    // 将public下面的资源复制到dist目录去(除了index.html)
    new CopyPlugin(
      patterns: [
        
          from: path.resolve(__dirname, "../public"),
          to: path.resolve(__dirname, "../dist"),
          toType: "dir",
          noErrorOnMissing: true, // 不生成错误
          globOptions: 
            // 忽略文件
            ignore: ["**/index.html"],
          ,
          info: 
            // 跳过terser压缩js
            minimized: true,
          ,
        ,
      ],
    ),
  ],
  optimization: 
    // 压缩的操作
    minimizer: [
      new CssMinimizerPlugin(),
      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"],
  ,
  mode: "production",
  devtool: "source-map",
;

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

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

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

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

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

个人笔记2023年搭建基于webpack5与typescript的react项目

Webpack5 搭建 Vue3 + TS 项目