在 Node v22 中导入 JSON 时出现 "SyntaxError: Unexpected identifier 'assert'" 错误

# 问题背景:

A Node program of mine that worked fine in Node v21 now immediately crashes with a syntax error in Node v22. The line that triggers the error looks like this:

我在 Node v21 中正常工作的一个 Node 程序,现在在 Node v22 中立即因语法错误崩溃。触发错误的代码行如下所示:

import config from "./some-config-file.json" assert { type: "json" };
and the error says:        错误信息:
SyntaxError: Unexpected identifier 'assert'
    at compileSourceTextModule (node:internal/modules/esm/utils:337:16)
    at ModuleLoader.moduleStrategy (node:internal/modules/esm/translators:166:18)
    at callTranslator (node:internal/modules/esm/loader:436:14)
    at ModuleLoader.moduleProvider (node:internal/modules/esm/loader:442:30)
    at async ModuleJob._link (node:internal/modules/esm/module_job:106:19)
Why am I getting this error in code that previously worked, and how should I fix it?

为什么我在以前正常工作的代码中会遇到这个错误,我应该如何修复它?

# 问题解决:

This is due to support for "import assertions" being removed from Node in favour of "import attributes", which are essentially the same thing except you have to use the keyword with instead of assert:

这是因为 Node 移除了对 import assertions 的支持,改为支持 import attributes ,这两者本质上是相同的,只是你需要使用 with 关键字代替 assert

import config from "./some-config-file.json" with { type: "json" }; (That trivial explanation of the change might sound like it must be missing something, but at least for now and in the context of Node, it really isn't. The change happened in Node because the underlying ECMAScript spec proposal made the same name and keyword change, on the grounds that some new import attributes - besides type: "json" - will have behaviours not properly described as "asserting" anything. But Node still supports only one import attribute, type: "json", which behaves exactly the same as it did with the old assert syntax.)

(这个对变更的简单解释可能听起来好像缺少了什么,但至少在当前的 Node 环境中,实际上并没有。这个变化发生在 Node 中,因为底层的 ECMAScript 规范提案做出了相同的名称和关键字更改,理由是一些新的导入属性 —— 除了 type: "json"—— 将具有无法被正确描述为 “断言” 任何东西的行为。但 Node 仍然只支持一个导入属性,type: "json",它的行为与旧的 assert 语法完全相同。)

To fix the error, you could just adopt the new syntax (i.e. change assert to with). However, do note that support for the "import attributes" syntax (with with) was added later than the older "import assertions" syntax (with assert); the latter has been around since Node 17.1 and 16.14, while the former was only added in Node 18.20. Thus, swapping from assert to with will fix your program for Node 22 and later at the expense of breaking it for Node 16 and 17.

要修复这个错误,你可以采用新的语法(即将 assert 改为 with)。但是,请注意, import attributes 语法(使用 with)的支持添加得比旧的 import assertions 语法(使用 assert)晚;后者从 Node 17.1 和 16.14 开始就有,而前者则是在 Node 18.20 中才添加的。因此,从 assert 改为 with 可以修复 Node 22 及之后版本中的问题,但会导致 Node 16 和 17 中的程序无法正常运行