Search code examples
node.jseslintes6-modules

eslint failed on dynamic es6 modules import of json with assert


I'm importing dynamically a JSON file

await import(`${process.cwd()}/some.json`, { assert: { type: 'json' } });
                                         ^-- eslint problem is here

and i get this error (running node 18.15)

$ eslint .

/path/build.js
  5:80  error  Parsing error: Unexpected token ,

✖ 1 problem (1 error, 0 warnings)

i can't remove the assert part, if i do, i've this error:

TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module "file:///file.json" needs an import assertion of type "json"

My eslint (version 8.29.x) config file

env:
  node: true
  es2021: true
  jest/globals: true
plugins:
  - jest
extends:
  - eslint:recommended
  - prettier
parserOptions:
  ecmaVersion: 2023
  sourceType: module

so what can i do to tell eslint my code is valid?


Solution

  • Regarding to this discussion: https://github.com/eslint/eslint/discussions/15305

    N. Zakas (creator of Eslint) said

    We have the policy to wait until stage four because We don’t know which ECMA version it will end up in. Once import assertions have landed in an ECMAScript version, we can look at adding support in ESLint. In the meantime, you’ll need to use some thing like the Babel ESLint parser to get the support.

    A proposition is made in comments, to go over the problem through babel. Add this to eslint config file (here eslintrc.yml)

    parserOptions:
      requireConfigFile: false
      babelOptions:
        plugins:
          - '@babel/plugin-syntax-import-assertions'
    parser: '@babel/eslint-parser'
    

    And run

    yarn add -D @babel/eslint-parser @babel/plugin-syntax-import-assertions
    

    It seems to work well. Waiting that assertions arrived in Ecma