node.js 中 typeerror [err-ag捕鱼王app官网

当前位置:ag捕鱼王app官网 > > 编程语言 > node.js >

node.js 中 typeerror [err_import_assertion_type_missing]

作者:迹忆客 最近更新:2023/05/09 浏览次数:

使用导入断言解决错误“typeerror [err_import_assertion_type_missing]: module needs an import assertion of type json”,例如 import myjson from './example.json' assert {type: 'json'}。 此语法指示模块是 json 并且不被执行。

nodejs typeerror err_import_assertion_type_missing .jpg

这是发生该错误的示例。

// ⛔️ 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 中编码 url

发布时间:2023/03/27 浏览次数:401 分类:node.js

在这篇简短的文章中,我们将学习如何在 node.js 中进行 url 编码。

在 node.js 中编码 base64

发布时间:2023/03/27 浏览次数:278 分类:node.js

在本文中,我们将学习如何在 node.js 中将字符串或文本转换为 base64。

node.js 与 react js 的比较

发布时间:2023/03/27 浏览次数:173 分类:node.js

本文比较和对比了两种编程语言,node.js 和 react。react 和 node.js 都是开源 javascript 库的示例。 这些库用于构建用户界面和服务器端应用程序。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便
网站地图