无法 export/import 函数 js

Cant export/import functions js

我正在使用 node.js 并尝试从另一个脚本导入函数。

The requested module './Module.js' does not provide an export named 'default' 是我在尝试使用时收到的错误吗

module.exports = randomfunction;

对于上下文,我使用了

import randomfunction from "./module.js";

你的问题是因为 Node.js 认为 Module.js 是一个 ES 模块,但你把它写成一个 CommonJS 模块。

你必须告诉 Node.js 你的模块是 CommonJS(使用 module.exportsrequire)还是 ES(使用 importexport)。

您使用文件扩展名设置模块类型:

  • .cjs 对于 CommonJS
  • .mjs 对于 ES 模块
  • .js 用于包默认

包默认值由 type 属性 决定。如果您指定 "type": "module" 那么 .js 文件将被视为 ES 模块。如果您不指定,那么它将把它们视为 CommonJS 模块。


您似乎已设置 "type": "module",因此您可以在 .js 文件中使用 import

这意味着您必须重命名您的 CommonJS 模块:

import randomfunction from "./module.cjs";

将您的 CommonJS 模块重写为 ES 模块:

export default randomfunction;