如何为 Babel 启用导入断言?

How to enable import assertions for Babel?

在我的 React 应用程序中,我想使用导入断言:

import data from "./json/clients-m.json" assert { type: "json" }

但是,我收到以下错误:

ERROR in ./src/Clients.js Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: E:\src\Clients.js: Support for the experimental syntax 'importAssertions' isn't currently enabled.

Add @babel/plugin-syntax-import-assertions (https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-assertions) to the 'plugins' section of your Babel config to enable parsing.

Line 1:41: Parsing error: This experimental syntax requires enabling the parser plugin: "importAssertions". (1:41)

我已经安装了这个插件:

npm install @babel/plugin-syntax-import-assertions --save-dev

然后我创建了.babelrc.json:

{
  "plugins": [
    "@babel/plugin-syntax-import-assertions"
  ]
}

并且还将此插件添加到 package.json:

{
  "name": "clients-frontend",
  "version": "0.1.0",
  "private": true,
  "babel": {
    "plugins": [
      "@babel/plugin-syntax-import-assertions"
    ]
  },
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.1.1",
    "@testing-library/user-event": "^13.5.0",
    "bootstrap": "^5.1.3",
    "react": "^18.1.0",
    "react-dom": "^18.1.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "devDependencies": {
    "@babel/plugin-syntax-import-assertions": "^7.16.7"
  }
}

但是,我一直收到此错误。

也尝试安装 babel-eslint 软件包。并且,在您的 .eslintrc.json 文件中添加:

{
  "parserOptions": {
    "babelOptions": {
      "parserOpts": {
        "plugins": ["importAssertions"]
      }
    }
  }
}

react-scripts 默认不加载 babel 配置。安装以下软件包

npm i -D customize-cra react-app-rewired

这些包让您可以自定义 react-scripts babel 的默认配置,这样您就可以使用其他插件

现在,更改 package.json

中的脚本
"scripts": {
-    "start": "react-scripts start",
+    "start": "react-app-rewired start",
-    "build": "react-scripts build",
+    "build": "react-app-rewired build",
-    "test": "react-scripts test",
+    "test": "react-app-rewired test"
  }

在您的应用的根目录创建一个文件config-overrides.js,内容如下

/* config-overrides.js */
/* eslint-disable react-hooks/rules-of-hooks */
const { useBabelRc, override } = require('customize-cra');

module.exports = override(useBabelRc());

现在,在包的根目录下创建 .babelrc

{
  "plugins": [
    "@babel/plugin-syntax-import-assertions"
  ]
}

现在,您的 babel 配置将被正确加载。还有另一个库 craco 可让您自定义 react-scripts 配置