带有 JavaScript、React 和 jest 的 Webpack 给出 Babel 错误

Posted

技术标签:

【中文标题】带有 JavaScript、React 和 jest 的 Webpack 给出 Babel 错误【英文标题】:Webpack with JavaScript, React and jest gives Babel Error 【发布时间】:2022-01-24 03:37:30 【问题描述】:

我已经设置了 Webpack,并希望它可以用于几乎任何你能想象到的东西。但是当我想实现 jest 进行测试时,它会给我一个 Babel 错误。

我的 webpack.config.js

const path = require("path");
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const  CleanWebpackPlugin  = require("clean-webpack-plugin");
const htmlWebpackPlugin = require("html-webpack-plugin");


let mode = "development";
let target = "web";
const plugins = [
  new CleanWebpackPlugin(),
  new MiniCssExtractPlugin(),
  new HtmlWebpackPlugin(
    template: "./src/index.html",
  ),
];

if (process.env.NODE_ENV === "production") 
  mode = "production";
  // Temporary workaround for 'browserslist' bug that is being patched in the near future
  target = "browserslist";


if (process.env.SERVE) 
  // We only want React Hot Reloading in serve mode
  plugins.push(new ReactRefreshWebpackPlugin());


module.exports = 
  // mode defaults to 'production' if not set
  mode: mode,

  // This is unnecessary in Webpack 5, because it's the default.
  // However, react-refresh-webpack-plugin can't find the entry without it.
  entry: "./src/index.js",

  output: 
    // output path is required for `clean-webpack-plugin`
    path: path.resolve(__dirname, "dist"),
    // this places all images processed in an image folder
    assetModuleFilename: "images/[hash][ext][query]",
  ,

  module: 
    rules: [
      
        test: /\.(s[ac]|c)ss$/i,
        use: [
          
            loader: MiniCssExtractPlugin.loader,
            // This is required for asset imports in CSS, such as url()
            options:  publicPath: "" ,
          ,
          "css-loader",
          "postcss-loader",
          // according to the docs, sass-loader should be at the bottom, which
          // loads it first to avoid prefixes in your sourcemaps and other issues.
          "sass-loader",
        ],
      ,
      
        test: /\.(png|jpe?g|gif|svg)$/i,
        /**
         * The `type` setting replaces the need for "url-loader"
         * and "file-loader" in Webpack 5.
         *
         * setting `type` to "asset" will automatically pick between
         * outputing images to a file, or inlining them in the bundle as base64
         * with a default max inline size of 8kb
         */
        type: "asset",

        /**
         * If you want to inline larger images, you can set
         * a custom `maxSize` for inline like so:
         */
        // parser: 
        //   dataUrlCondition: 
        //     maxSize: 30 * 1024,
        //   ,
        // ,
      ,
      
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: 
          // without additional settings, this will reference .babelrc
          loader: "babel-loader",
          options: 
            /**
             * From the docs: When set, the given directory will be used
             * to cache the results of the loader. Future webpack builds
             * will attempt to read from the cache to avoid needing to run
             * the potentially expensive Babel recompilation process on each run.
             */
            cacheDirectory: true,
          ,
        ,
      ,
    ],
  ,

  plugins: plugins,

  target: target,

  devtool: "source-map",

  resolve: 
    extensions: [".js", ".jsx"],
  ,

  // required if using webpack-dev-server
  devServer: 
    contentBase: "./dist",
    hot: true,
  ,
;

还有 package.json


  "name": "webpack-starters",
  "version": "1.0.0",
  "private": true,
  "description": "A collection of different Webpack setups for quick referencing or starting from",
  "scripts": 
    "start": "cross-env SERVE=true webpack serve",
    "watch": "webpack --watch",
    "build": "cross-env NODE_ENV=production webpack",
    "build-dev": "webpack",
    "clean": "rm -rf ./dist",
    "test": "jest --coverage"
  ,
  "author": "Mike van Eckendonk",
  "license": "MIT",
  "devDependencies": 
    "@babel/core": "^7.16.5",
    "@babel/preset-env": "^7.16.5",
    "@babel/preset-react": "^7.16.5",
    "@pmmmwh/react-refresh-webpack-plugin": "^0.5.4",
    "babel": "^6.23.0",
    "babel-jest": "^27.4.5",
    "babel-loader": "^8.2.3",
    "clean-webpack-plugin": "^3.0.0",
    "cross-env": "^7.0.3",
    "css-loader": "^5.2.7",
    "html-webpack-plugin": "^5.5.0",
    "jest-webpack": "^0.3.1",
    "mini-css-extract-plugin": "^2.1.0",
    "postcss": "^8.4.4",
    "postcss-loader": "^4.3.0",
    "postcss-preset-env": "^6.7.0",
    "react-refresh": "^0.9.0",
    "sass": "^1.44.0",
    "sass-loader": "^10.2.0",
    "webpack": "^5.65.0",
    "webpack-cli": "^4.9.1",
    "webpack-dev-server": "^4.7.1"
  ,
  "dependencies": 
    "react": "^17.0.1",
    "react-dom": "^17.0.1"
  

babel.config.js

// Cannot load "react-refresh/babel" in production
const plugins = [];
if (process.env.NODE_ENV !== "production") 
  plugins.push("react-refresh/babel");


module.exports = 
  presets: [
    "@babel/preset-env",
    // Runtime automatic with React 17+ allows not importing React
    // in files only using JSX (no state or React methods)
    ["@babel/preset-react",  runtime: "automatic" ],
  ],
  plugins: plugins,
;

有人知道如何解决这些错误吗?测试文件没有错误,因为没有 Webpack 它们是正确的。

【问题讨论】:

【参考方案1】:

要么从 test 环境的 babel 配置中删除 react-refresh/babel,要么只更改 if 条件,它应该可以工作。

if (process.env.NODE_ENV !== "production" && process.env.NODE_ENV !== "test") ...

编辑:将if 更新为使用and 而不是or

【讨论】:

我注释掉了 if (process.env.NODE_ENV !== "production" || process.env.NODE_ENV !== "test") // plugins.push("react-refresh/babel"); 行,它可以工作,但是更改 If 语句不起作用。应该有另一个可行的解决方案。你可以在这里查看 repo:link

以上是关于带有 JavaScript、React 和 jest 的 Webpack 给出 Babel 错误的主要内容,如果未能解决你的问题,请参考以下文章

使用带有 javascript 导入语法的括号

使用带有 javascript 导入语法的括号

zosftplib submit_wait_job(jcl) 函数不接收 JES 输出

带有React的Rabbit-MQ

包含带有脚本标签的 Kendo React

使用 IEFs-s-rEQ 宏的 MVS JES2 清除作业