While I was exporting functions from one folder in Node.js, I encountered some ambiguity.
Export Statement:
function getPosts(req, res){
res.send("Server is Running");
}
export { getPosts };
Import Statement:
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: Error in the console
But when i used this statement: export { getPosts };
, there where no error.
In packet.json I have added "type": "module"
.
Can anyone explain when to use export
and when module.exports
?
CodePudding user response:
Well, yeah. module.exports
is not the same as export
. The two work a bit differently. module.exports
is used in a CommonJS module. export
is used in a ESM module. import
and export
work well together in ESM modules. module.exports
and require()
work well together in CommonJS modules. There are some ways to achieve some combability between the two module types, but that is an advanced subject. When possible, just use the same module type and matching syntax everywhere.
In packet.json I have added
"type": "module"
.
That declares your top level entry point as an ESM module (where you would use import
and export
.
Can anyone explain when to use
export
and whenmodule.exports
?
export
is for ESM modules. When you added "type": "module"
, that made your module an ESM module and you should use import
in that module to load other ESM module files. And, in those other ESM module files, you should use export
to declare what you want exported.
module.exports
is for CommonJS modules (the older version of nodejs module). Avoid mixing CommonJS and ESM modules whenever possible. And, since you've declared "type": "module"
, that whole directory will be treated as ESM module files by nodejs.