【问题标题】:Unable to understand Export in Node.js无法理解 Node.js 中的导出
【发布时间】:2021-12-31 08:31:14
【问题描述】:

当我从 Node.js 的一个文件夹中导出函数时,我遇到了一些歧义。

出口声明:

function getPosts(req, res){
    res.send("Server is Running");
}
export { getPosts };

进口声明:

import express from "express";
import { getPosts } from "../controllers/posts.js";
const router = express.Router();

router.get("/", getPosts);

export default router;

Packet.json:

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "nodemon index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.1",
    "cors": "^2.8.5",
    "express": "^4.17.2",
    "mongoose": "^6.1.4"
  }
}

错误: Error in the console

但是当我使用这个语句时:export { getPosts };,那里没有错误。

packet.json 我添加了"type": "module"

谁能解释一下何时使用export 以及何时使用module.exports

【问题讨论】:

  • module.exports,不是module.export
  • module.exportmodule.exports 不同。
  • 即使我使用了module.exports,它仍然显示错误
  • @ReeKid “an error” 不幸的是不是很有帮助。 什么错误?什么是堆栈跟踪?你的代码实际上是什么样子的? How to Ask

标签: node.js node-modules


【解决方案1】:

嗯,是的。 module.exportsexport 不同。两者的工作方式略有不同。 module.exports 用于 CommonJS 模块。 export 用于 ESM 模块。 importexport 在 ESM 模块中可以很好地协同工作。 module.exportsrequire() 在 CommonJS 模块中可以很好地协同工作。有一些方法可以在两种模块类型之间实现一些可组合性,但这是一个高级主题。如果可能,请在任何地方使用相同的模块类型和匹配的语法。

在 packet.json 中我添加了"type": "module"

这将您的顶级入口点声明为 ESM 模块(您将在其中使用 importexport

谁能解释一下何时使用export 以及何时使用module.exports

export 用于 ESM 模块。当您添加 "type": "module" 时,这使您的模块成为 ESM 模块,您应该在该模块中使用 import 来加载其他 ESM 模块文件。而且,在那些其他 ESM 模块文件中,您应该使用 export 来声明要导出的内容。

module.exports 用于 CommonJS 模块(旧版本的 nodejs 模块)。尽可能避免混合 CommonJS 和 ESM 模块。而且,由于您已声明 "type": "module",整个目录将被 nodejs 视为 ESM 模块文件。

【讨论】:

    猜你喜欢
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 2015-07-31
    相关资源
    最近更新 更多