尚硅谷 React脚手架在原有的基础上增添自己的注释

尚硅谷 React脚手架

其他配置

  • page.json
{
  "name": "react-cli",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "npm run dev",
    "dev": "cross-env NODE_ENV=development webpack serve --config ./config/webpack.dev.js",
    "build": "cross-env NODE_ENV=production webpack --config ./config/webpack.prod.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.17.10",
    "@pmmmwh/react-refresh-webpack-plugin": "^0.5.5",
    "babel-loader": "^8.2.5",
    "babel-preset-react-app": "^10.0.1",
    "copy-webpack-plugin": "^10.2.4",
    "cross-env": "^7.0.3",
    "css-loader": "^6.7.1",
    "css-minimizer-webpack-plugin": "^3.4.1",
    "eslint-config-react-app": "^7.0.1",
    "eslint-webpack-plugin": "^3.1.1",
    "html-webpack-plugin": "^5.5.0",
    "image-minimizer-webpack-plugin": "^3.2.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": "^10.2.0",
    "mini-css-extract-plugin": "^2.6.0",
    "postcss-loader": "^6.2.1",
    "postcss-preset-env": "^7.5.0",
    "react-refresh": "^0.13.0",
    "sass-loader": "^12.6.0",
    "style-loader": "^3.3.1",
    "stylus-loader": "^6.2.0",
    "webpack": "^5.72.0",
    "webpack-cli": "^4.9.2",
    "webpack-dev-server": "^4.9.0"
  },
  "dependencies": {
    "antd": "^4.20.2",
    "react": "^18.1.0",
    "react-dom": "^18.1.0",
    "react-router-dom": "^6.3.0"
  },
  "browserslist": ["last 2 version", "> 1%", "not dead"]
}
  • .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 = {
    // 使用react官方规则,已内置core-js用于语法兼容
    presets: ["react-app"],
  };

开发模式配置

const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin"); // react用于js热替换功能的插件
const CopyPlugin = require("copy-webpack-plugin");

/**
 * 
 * @param {String} preProcessor 预处理loader  
 * @returns loder数组
 */
const getStyleLoaders = (preProcessor) => {
    return [
        "style-loader",
        "css-loader",
        // css兼容处理
        {
            loader: "postcss-loader",
            options: {
                postcssOptions: {
                    plugins: [
                        "postcss-preset-env", // 能解决大多数样式兼容性问题
                    ],
                },
            },
        },
        preProcessor
    ].filter(Boolean)
}

module.expoets = {
    // 入口文件
    entry: "./src/main/js",
    output: {
        // 开发环境,打包编译的文件保存在内存中,并不需要输出路径
        path: undefined,
        filename: "static/js/[name].js",
        chunkFilename: 'static/js/[name].chunk.js',
        assetModuleFilename: "static/js/[hash:10][ext][query]" // assets资源文件名 
    },
    module: {
        rules: [
            {
                // 防止匹配成功后再向下匹配
                oneOf: [
                    {
                        // 用来匹配 .css 结尾的文件
                        test: /\.css$/,
                        // use 数组里面 Loader 执行顺序是从右到左
                        use: getStyleLoaders(),
                    },
                    {
                        // 用来匹配 .less结尾的文件
                        test: /\.less$/,
                        use: getStyleLoaders("less-loader"),
                    },
                    {
                        // 用来匹配 .sass或.scss结尾的文件
                        test: /\.s[ac]ss$/,
                        use: getStyleLoaders("sass-loader"),
                    },
                    {
                        // 用来匹配 .sty结尾的文件
                        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",
                    }, {
                        // 用于匹配 .js或.jsx结尾的文件
                        test: /\.(jsx|js)$/,
                        include: path.resolve(__dirname, "../src"), // 该loader只处理 根目录下的src文件下的所有js文件
                        loader: "babel-loader",
                        options: {
                            cacheDirectory: true, // 开启缓存
                            cacheCompression: false, // 关闭缓存文件压缩,为了增加速度
                            plugins: [
                                // "@babel/plugin-transform-runtime", // presets中包含了
                                "react-refresh/babel", // 开启js的HMR功能
                            ],
                        },
                    }
                ]
            }
        ]
    },
    plugins: [
        // ESLint
        new ESLintWebpackPlugin({
            context: path.resolve(__dirname, "../src"), // 该plugin检查 根目录下的src文件下的所有js文件
            exclude: "node_modules", // 排除node_modules文件夹
            cache: true, // 开启缓存
            cacheLocation: path.resolve( // 缓存目录(缓存到哪个文件中)
                __dirname,
                "../node_modules/.cache/.eslintcache"
            ),
        }),
        // 自动生成html打包文件,自动导入资源(防止因文件hash值的改变影响文件的引入)
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, "../public/index.html"), // 内容模板路径
        }),
        new ReactRefreshWebpackPlugin(), // 解决js的HMR功能
        // 将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,
                    },
                },
            ],
        }),
    ],
    mode: 'development',
    devtool: "cheap-module-source-map", // 开启SourceMap——代码映射
    // optimization,中文翻译:优化
    optimization: {
        // 代码分割
        splitChunks: {
            chunks: "all",
        },
        // 保管hash值,减少文件更新
        runtimeChunk: {
            name: (entrypoint) => `runtime~${entrypoint.name}`,
        },
    },
    // webpack解析模块加载选项
    resolve: {
        // 自动补全文件扩展名
        // 当引入的文件没有文件扩展名,首先会以.jsx文件进行解析,如果不行,则使用.js,再不行则使用.json,以此类推
        // 当一个匹配完成就不会继续匹配
        extensions: [".jsx", ".js", ".json"]
    },
    devServer: {
        open: true, // 是否自动打开浏览器
        host: "localhost",
        port: 3000,
        hot: true, // 开启热模块替换
        compress: true,
        historyApiFallback: true, // 解决react-router刷新404问题,当我们访问3000/home,会显示404,因为我们只有一个index.html文件,需要返回index.html中寻找
    }
}

生产模式模式

const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin") // 提取css单独文件
const TerserWebpackPlugin = require("terser-webpack-plugin"); // js压缩
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin"); // css压缩
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin"); // 图片压缩
const CopyPlugin = require("copy-webpack-plugin");

/**
 * 
 * @param {String} preProcessor 预处理loader  
 * @returns loder数组
 */
const getStyleLoaders = (preProcessor) => {
    return [
        MiniCssExtractPlugin.loader,
        "css-loader",
        // css兼容处理
        {
            loader: "postcss-loader",
            options: {
                postcssOptions: {
                    plugins: [
                        "postcss-preset-env", // 能解决大多数样式兼容性问题
                    ],
                },
            },
        },
        preProcessor
    ].filter(Boolean)
}

module.expoets = {
    // 入口文件
    entry: "./src/main/js",
    output: {
        path: path.resolve(__dirname, "../dist"),
        filename: "static/js/[name].[contenthash:10].js", // 添加hash方便保存
        chunkFilename: 'static/js/[name].chunk.[contenthash:10].js',
        assetModuleFilename: "static/js/[hash:10][ext][query]", // assets资源文件名 
        clean: true
    },
    module: {
        rules: [
            {
                // 防止匹配成功后再向下匹配
                oneOf: [
                    {
                        // 用来匹配 .css 结尾的文件
                        test: /\.css$/,
                        // use 数组里面 Loader 执行顺序是从右到左
                        use: getStyleLoaders(),
                    },
                    {
                        // 用来匹配 .less结尾的文件
                        test: /\.less$/,
                        use: getStyleLoaders("less-loader"),
                    },
                    {
                        // 用来匹配 .sass或.scss结尾的文件
                        test: /\.s[ac]ss$/,
                        use: getStyleLoaders("sass-loader"),
                    },
                    {
                        // 用来匹配 .sty结尾的文件
                        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",
                    }, {
                        // 用于匹配 .js或.jsx结尾的文件
                        test: /\.(jsx|js)$/,
                        include: path.resolve(__dirname, "../src"), // 该loader只处理 根目录下的src文件下的所有js文件
                        loader: "babel-loader",
                        options: {
                            cacheDirectory: true, // 开启缓存
                            cacheCompression: false, // 关闭缓存文件压缩,为了增加速度
                        },
                    }
                ]
            }
        ]
    },
    plugins: [
        // ESLint
        new ESLintWebpackPlugin({
            context: path.resolve(__dirname, "../src"), // 该plugin检查 根目录下的src文件下的所有js文件
            exclude: "node_modules", // 排除node_modules文件夹
            cache: true, // 开启缓存
            cacheLocation: path.resolve( // 缓存目录(缓存到哪个文件中)
                __dirname,
                "../node_modules/.cache/.eslintcache"
            ),
        }),
        // 自动生成html打包文件,自动导入资源(防止因文件hash值的改变影响文件的引入)
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, "../public/index.html"), // 内容模板路径
        }),
        new MiniCssExtractPlugin({
            // css文件名称
            filename: 'static/css/[name].[contenthash:10].css',
            // chunk文件的命名
            chunkFilename: 'static/css/[name].[contenthash:10].chunk.css',
        }),
        // 将public下面的资源复制到dist目录去(除了index.html),因为public文件下的文件除了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,
                    },
                },
            ],
        }),
    ],
    mode: 'production',
    devtool: "cheap-module-source-map", // 开启SourceMap——代码映射
    // optimization,中文翻译:优化
    optimization: {
        // 代码分割
        splitChunks: {
            chunks: "all",
        },
        // 保管hash值,减少文件更新
        runtimeChunk: {
            name: (entrypoint) => `runtime~${entrypoint.name}`,
        },
        // 压缩
        minimizer: [
            new TerserWebpackPlugin(), // js压缩
            new CssMinimizerPlugin(), // css压缩
            // 图片压缩
            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: {
        // 自动补全文件扩展名
        // 当引入的文件没有文件扩展名,首先会以.jsx文件进行解析,如果不行,则使用.js,再不行则使用.json,以此类推
        // 当一个匹配完成就不会继续匹配
        extensions: [".jsx", ".js", ".json"]
    }
}

合并开发和生产配置

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


学习编程是顺着互联网的发展潮流,是一件好事。新手如何学习编程?其实不难,不过在学习编程之前你得先了解你的目的是什么?这个很重要,因为目的决定你的发展方向、决定你的发展速度。
IT行业是什么工作做什么?IT行业的工作有:产品策划类、页面设计类、前端与移动、开发与测试、营销推广类、数据运营类、运营维护类、游戏相关类等,根据不同的分类下面有细分了不同的岗位。
女生学Java好就业吗?女生适合学Java编程吗?目前有不少女生学习Java开发,但要结合自身的情况,先了解自己适不适合去学习Java,不要盲目的选择不适合自己的Java培训班进行学习。只要肯下功夫钻研,多看、多想、多练
Can’t connect to local MySQL server through socket \'/var/lib/mysql/mysql.sock问题 1.进入mysql路径
oracle基本命令 一、登录操作 1.管理员登录 # 管理员登录 sqlplus / as sysdba 2.普通用户登录
一、背景 因为项目中需要通北京网络,所以需要连vpn,但是服务器有时候会断掉,所以写个shell脚本每五分钟去判断是否连接,于是就有下面的shell脚本。
BETWEEN 操作符选取介于两个值之间的数据范围内的值。这些值可以是数值、文本或者日期。
假如你已经使用过苹果开发者中心上架app,你肯定知道在苹果开发者中心的web界面,无法直接提交ipa文件,而是需要使用第三方工具,将ipa文件上传到构建版本,开...
下面的 SQL 语句指定了两个别名,一个是 name 列的别名,一个是 country 列的别名。**提示:**如果列名称包含空格,要求使用双引号或方括号:
在使用H5混合开发的app打包后,需要将ipa文件上传到appstore进行发布,就需要去苹果开发者中心进行发布。​
+----+--------------+---------------------------+-------+---------+
数组的声明并不是声明一个个单独的变量,比如 number0、number1、...、number99,而是声明一个数组变量,比如 numbers,然后使用 nu...
第一步:到appuploader官网下载辅助工具和iCloud驱动,使用前面创建的AppID登录。
如需删除表中的列,请使用下面的语法(请注意,某些数据库系统不允许这种在数据库表中删除列的方式):
前不久在制作win11pe,制作了一版,1.26GB,太大了,不满意,想再裁剪下,发现这次dism mount正常,commit或discard巨慢,以前都很快...
赛门铁克各个版本概览:https://knowledge.broadcom.com/external/article?legacyId=tech163829
实测Python 3.6.6用pip 21.3.1,再高就报错了,Python 3.10.7用pip 22.3.1是可以的
Broadcom Corporation (博通公司,股票代号AVGO)是全球领先的有线和无线通信半导体公司。其产品实现向家庭、 办公室和移动环境以及在这些环境...
发现个问题,server2016上安装了c4d这些版本,低版本的正常显示窗格,但红色圈出的高版本c4d打开后不显示窗格,
TAT:https://cloud.tencent.com/document/product/1340