To all the node developer you need to stop using require() in your new project. The node has already support for modules and this tutorial will tell you difference between them and what to use instead of require() and also will deep down into module a bit more.
What are you using
const express = require('express') // common js
What you should use
import express from 'express' // es module
Did you see ?? how much the better code look in second one. The first one is commonjs syntax which is present in node from its origin for importing libraries , the second one was first introduced in browser and then it came to node.
It makes code so much readable , modern and non - verbose.
How to use it ?
Its easy.
- Initialise new node project.
- Go to your package.json.
-
Add following to it.
"type" : "module" ,
By default when you initialise your project its set to commonjs.
That's it now start using modern javascript.
Common patterns
Instead of explaining it I am going to show you commonjs code implemented in module format, so that you can start it immediately , also comeback to this article in future when you are confuse how to do certain things in module format.
Importing
// cjs
const express = require('express')
// mjs
import express from 'express'
// cjs
const express = require('express')
const Router = express.Router
// mjs
import express , { Router } from 'express'
//cjs
const clientRouter = require('express').Router
// mjs
import { Router as clientRouter } from 'express'
Exporting
// cjs
module.exports = express
// mjs
export default express
// cjs
module.exports = {
router : {...} ,
utils : {...}
}
// mjs
export {
router : {...},
utils : {...}
}
Some more exporting pattern that may come handy
// mjs
export default function hello() {...}
export const bye = "bye"
Top comments (2)
You are right about this but there is a problem that need to be addressed before using this immediately. What do you do when the module you use does not support import statements yet ? You cannot use require in that case as it throws errors.
Thank you for your explaining