當我從 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;
資料包.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"
}
}
錯誤: 控制臺出錯
但是當我使用這個陳述句時:export { getPosts };,那里沒有錯誤。
在packet.json我添加了"type": "module".
誰能解釋一下何時使用export以及何時使用module.exports?
uj5u.com熱心網友回復:
嗯,是的。 module.exports不一樣export。兩者的作業方式略有不同。 module.exports在 CommonJS 模塊中使用。 export用于 ESM 模塊。 import并export在 ESM 模塊中很好地協同作業。 module.exports并require()在 CommonJS 模塊中很好地協同作業。有一些方法可以實作兩種模塊型別之間的一些可組合性,但這是一個高級主題。如果可能,請在任何地方使用相同的模塊型別和匹配的語法。
在 packet.json 我添加了
"type": "module".
這將您的頂級入口點宣告為 ESM 模塊(您將在其中使用import和export.
誰能解釋一下何時使用
export以及何時使用module.exports?
export用于 ESM 模塊。當您添加 時"type": "module",這使您的模塊成為 ESM 模塊,您應該import在該模塊中使用它來加載其他 ESM 模塊檔案。而且,在那些其他 ESM 模塊檔案中,您應該使用export來宣告要匯出的內容。
module.exports用于 CommonJS 模塊(舊版本的 nodejs 模塊)。盡可能避免混合使用 CommonJS 和 ESM 模塊。而且,由于您已經宣告了"type": "module",整個目錄將被 nodejs 視為 ESM 模塊檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/398814.html
