如何为 Babel 启用导入断言?

问题描述 投票:0回答:5

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

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

但是,我收到以下错误:

./src/Clients.js 中的错误 模块构建失败(来自 ./node_modules/babel-loader/lib/index.js): SyntaxError: E:\src\Clients.js: 当前未启用对实验性语法“importAssertions”的支持。

添加@babel/plugin-syntax-import-assertions(https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-assertions)到“插件”部分您的 Babel 配置以启用解析。

第 1:41 行:解析错误:此实验性语法需要启用解析器插件:“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"
  }
}

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

reactjs babeljs
5个回答
2
投票

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 可让您自定义反应脚本配置


1
投票

也尝试安装

babel-eslint
包。并且,在您的
.eslintrc.json
文件中添加:

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

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

babel.config.cjs

module.exports = function (api) {
  api.cache(true);
  let presets = [];
  let plugins = [];

  switch (process.env['NODE_ENV']) {
    case 'test':
      presets = [
        [
          '@babel/preset-env',
          {
            targets: {
              node: 'current',
            },
          },
        ],
      ];
      plugins = [
        'babel-plugin-transform-import-meta',
        '@babel/plugin-proposal-export-default-from',
        '@babel/plugin-syntax-import-assertions'
      ];
      break;
    default:
      presets = [
        [
          '@babel/preset-env',
          {
            modules: false, //Setting this to false will preserve ES services
            targets: {
              node: 'current',
            },
          },
        ],
      ];
      plugins = ['@babel/plugin-syntax-import-assertions'];
      break;
  }

  return {
    presets,
    plugins,
  };
};


0
投票

如果你(像我一样)使用 ejected 反应脚本应用程序,也许你需要在

webpack.config.js
中设置你的配置在 application-scope
babel-loader
:

// Process application JS with Babel.
// The preset includes JSX, Flow, TypeScript, and some ESnext features.
{
  test: /\.(js|mjs|jsx|ts|tsx)$/,
  include: paths.appSrc,
  loader: require.resolve('babel-loader'),
  options: {
    customize: require.resolve('babel-preset-react-app/webpack-overrides',),
    presets: [/* ... */],
    plugins: [ // ADD THIS 👇
      require.resolve('@babel/plugin-syntax-import-assertions'),
      [require.resolve('babel-plugin-direct-import'), {
        modules: [
          require.resolve('@mui/material'),
          require.resolve('@mui/icons-material'),
          require.resolve('@mui/lab'),
          require.resolve('@mui/base'),
          require.resolve('@mui/system'),
        ],
      }],
      isEnvDevelopment && shouldUseReactRefresh && require.resolve('react-refresh/babel'),
    ].filter(Boolean),
    // ...
  },
},

但不在这里:

// Process any JS outside of the app with Babel.
// Unlike the application JS, we only compile the standard ES features.
{
  test: /\.(js|mjs)$/,
  exclude: /@babel(?:\/|\\{1,2})runtime/,
  // ...

-2
投票

我有同样的问题。我尝试遵循 Haseeb Anwar 的解决方案,但它一直失败。两者都

.babelrc

config-overrides.js

应该放在项目的根目录下对吗?

© www.soinside.com 2019 - 2024. All rights reserved.