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';
其中,我们的 example.json 文件内容如下
module.exports = {
"person": {
"name": "alice",
"country": "austria",
"tasks": ["develop", "design", "test"],
"age": 30
}
}
上面这行抛出了一个错误,因为我们需要明确指出我们正在导入一个 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 语法。
package.json
{ "type": "module", // ... rest }
简而言之,导入断言提议为模块导入语句添加了内联语法。
在导入无法执行代码的 json 模块和类似模块类型时,引入了该语法以提高安全性。
这可以防止服务器以不同的 mime 类型响应,从而导致代码意外执行的情况。
assert {type: 'json'}
语法使我们能够指定我们正在导入一个不会被执行的 json 或类似的模块类型。
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
node.js 中的 http 发送 post 请求
发布时间:2023/03/27 浏览次数:456 分类:node.js
-
在本文中,我们将学习如何使用 node.js 使用第三方包发出发送 post 请求。
node.js 与 react js 的比较
发布时间:2023/03/27 浏览次数:173 分类:node.js
-
本文比较和对比了两种编程语言,node.js 和 react。react 和 node.js 都是开源 javascript 库的示例。 这些库用于构建用户界面和服务器端应用程序。