为什么 package.json 文件中有“type: module”?

Reb*_*eca 35 node.js vue.js nuxt.js

我升级了节点并构建了现有文件。

但它没有构建,并且出现了错误。

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module:                          ?
   ?   ~~/nuxt.config.js                                      ?
   ?   require() of ES modules is not supported.                                            ?
   ?   require() of ~~/nuxt.config.js from                    ?
   ?   ~~/config.js is an ES   ?
   ?   module file as it is a .js file whose nearest parent package.json contains "type":   ?
   ?   "module" which defines all .js files in that package scope as ES modules.            ?
   ?   Instead rename nuxt.config.js to end in .cjs, change the requiring code to use       ?
   ?   import(), or remove "type": "module" from                                            ?
   ?   ~~/package.json.  
Run Code Online (Sandbox Code Playgroud)

所以我删除了 package.json 文件中的“类型:模块”。

去掉可以吗?

Afs*_*bbi 57

当 package.json 文件中有 'type: module' 时,您的源代码应该使用import语法。当你没有时,你应该使用require语法。

添加'type': 'module'package.json启用 ES 6 模块。有关更多信息,请参见此处

  • @Alex“type”:“module”用于 ES 模块。我认为你应该删除你的评论。另请检查 https://developer.okta.com/blog/2019/12/04/whats-new-nodejs-2020 (6认同)
  • 我认为 Alex 想说的是,从 `package.json` 中省略 `type` 与将其设置为 CJS 具有相同的效果。(规范是这样说的:“如果最近的父 package.json 缺少“type”字段,或包含“type”:“commonjs”,则 .js 文件将被视为 CommonJS。如果到达卷根并且没有包找到 .json,Node.js 遵循默认值,即没有“type”字段的 package.json。”) (3认同)
  • 啊,一个逗号有多么不同啊!不,“type”:模块意味着....是不正确的,但是No type:module意味着....是正确的哈哈。请澄清@alex (2认同)

kis*_*ssu 30

截至 2022 年中期更新

如果您使用的是 Node.js v16,而且您应该尽可能使用它,因为它是 LTS,您只需type: module按照此处的说明使用: https: //blog.logrocket.com/es-modules-in-node-today/


如果由于某些原因您仍然使用较低版本的 Node.js,您可以关注 Flavio 的这篇博客文章:https ://flaviocopes.com/how-to-enable-es-modules-nodejs/

并执行以下操作:

  • 添加"type": "module"您的package.json
  • --experimental-modules启动应用程序时使用,例如:node --experimental-modules app.js

或者,如果已经在现代版本的 Node 上,您可以执行其中一项操作:

  • 添加"type": "module"您的package.json
  • 使用扩展名重命名文件.mjs,最终结果将如下所示node app.mjs

  • 除非我遗漏了什么,否则您仍然需要 (a) 在 package.json 中声明 `"type": "module"` 或 (b) 在使用 Node 14 时使用 .mjs 文件扩展名(使用版本 14.17.3 进行测试) 。否则,您会从 Node 收到错误,例如“警告:要加载 ES 模块,请在 package.json 中设置“type”:“module”或使用 .mjs 扩展名。”和“语法错误:无法在模块外部使用 import 语句” 。这也适用于节点 16.5.0。 (5认同)