How to enable import assertions for Babel?

Viewed 1469

In my React app I want to use import assertion:

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

However, I get the following error:

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)

I have installed this plugin:

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

Then I created .babelrc.json:

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

And also added this plugin into 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"
  }
}

However, I keep getting this error.

4 Answers

react-scripts doesn't load babel configuration by default. Install the following packages

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

These packages let you customize react-scripts's default configuration for babel so you can use additional plugins

Now, change the scripts in your 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"
  }

Create a file config-overrides.js at the root of your app with the following content

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

module.exports = override(useBabelRc());

Now, create .babelrc at the root of your package

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

Now, your babel configuration will be loaded correctly. There's another library craco that lets you customize the react-scripts configuration

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

Try installing the babel-eslint package as well. And, in your .eslintrc.json file add:

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

If you (like me) use an ejected react-script app, maybe you need to set your configuration in webpack.config.js in the 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),
    // ...
  },
},

But NOT here:

// 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/,
  // ...
Related