简体   繁体   English

Webpack 与 JavaScript,反应和开玩笑给出 Babel 错误

[英]Webpack with JavaScript, React and jest gives Babel Error

I have set up Webpack and want to make it usable for almost anything you can imagine.我已经设置了 Webpack 并希望它可以用于几乎任何你能想象到的东西。 But when I want to implement jest for testing it gives me an error on Babel.但是当我想实现jest进行测试时,它在 Babel 上给了我一个错误。

在此处输入图像描述

My webpack.config.js我的 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,
  },
};

And the package.json和 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 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,
};

Does anyone have an idea of how to solve these errors?有谁知道如何解决这些错误? The test files don't have an error, because without Webpack they are correct.测试文件没有错误,因为没有 Webpack 它们是正确的。

Either remove react-refresh/babel from babel config for test environment or just change the if condition and it should work.test环境的 babel 配置中删除react-refresh/babel ,或者只是更改if条件,它应该可以工作。

if (process.env.NODE_ENV !== "production" || process.env.NODE_ENV !== "test") {...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM