Node.js 中的类型错误[ERR_IMPORT_ASSERTION_TYPE_MISSING]
TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING] in Node.js
使用导入断言解决错误“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 // "file://bobbyhadz-js/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"
上面的代码示例假定example.json
在同一目录中有一个文件,其内容如下:
{ "person": { "name": "Alice", "country": "Austria", "tasks": ["develop", "design", "test"], "age": 30 } }
Note that the type
property in your package.json
has to be set to module
,
because we are using
ES6 Modules
syntax.
{ "type": "module", // ... rest }
Here is a screenshot of the output from running the index.js
file.
You can read more about why this is necessary in the
Import assertions proposal page on GitHub.
In short, the import assertion proposal adds an inline syntax for module import
statements.
This prevents a scenario where a server responds with a different MIME type,
causing code to be unexpectedly executed.
The assert {type: 'json'}
syntax enables us to specify that we are importing a
JSON or similar module type that isn’t going to be executed.
您可以在此tc39 GitHub 存储库中阅读有关导入断言提案的更多信息
。