eslint 在使用断言的动态 es6 模块导入 json 时失败

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

我正在动态导入 JSON 文件

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

我收到此错误(运行节点 18.15)

$ eslint .

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

✖ 1 problem (1 error, 0 warnings)

我无法删除断言部分,如果我这样做,我会遇到此错误:

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

我的 eslint(版本 8.29.x)配置文件

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

那么我该怎么做才能告诉 eslint 我的代码是有效的?

node.js eslint es6-modules
2个回答
0
投票

关于此讨论:https://github.com/eslint/eslint/discussions/15305

N。 Zakas(Eslint 的创建者)说

我们的政策是等到第四阶段,因为我们不知道它最终会进入哪个 ECMA 版本。一旦导入断言进入 ECMAScript 版本,我们就可以考虑在 ESLint 中添加支持。同时,您需要使用 Babel ESLint 解析器之类的东西来获得支持。

在评论中提出一个建议,通过babel来解决这个问题。将其添加到 eslint 配置文件(此处为 eslintrc.yml)

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

然后跑

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

看起来效果不错。等待断言到达 Ecma


0
投票

对于动态导入,需要注意一点:

assert
已从规范中删除。现在使用正确的语法
with
,如下所示。

来自

import("foo.json", { assert: { type: "json" } });

import("foo.json", { with: { type: "json" } });

参考:https://github.com/tc39/proposal-import-attributes

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