Node.js 中 TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]
使用导入断言解决错误“TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module needs an import assertion of type json”,例如 import myJson from './example.json' assert {type: 'json'}。 此语法指示模块是 JSON 并且不被执行。
这是发生该错误的示例
// ⛔️ TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module
// "init/example.json" needs an
// import assertion of type "json"
import myJson from './example.json';
上面这行抛出了一个错误,因为我们需要明确指出我们正在导入一个 JSON 模块,所以它不能被执行。
import myJson from './example.json' assert {type: 'json'};
// 👇️ {
// name: 'Alice',
// country: 'Austria',
// tasks: [ 'develop', 'design', 'test' ],
// age: 30
// }
console.log(myJson.person);
console.log(myJson.person.name); // 👉️ "Alice"
console.log(myJson.person.country); // 👉️ "Austria"
注意,我们的 package.json 中的 type 属性必须设置为 module,因为我们使用的是 ES6 Modules 语法。
{
"type": "module",
// ... rest
}
导入断言提议为模块导入语句添加了内联语法。
在导入无法执行代码的 JSON 模块和类似模块类型时,引入了该语法以提高安全性。
这可以防止服务器以不同的 MIME 类型响应,从而导致代码意外执行的情况。
assert {type: 'json'} 语法使我们能够指定我们正在导入一个不会被执行的 JSON 或类似的模块类型。

浙公网安备 33010602011771号