To all of the node developer that you must cease utilizing require() in your new challenge. The node has already help for modules and this tutorial will let you know distinction between them and what to make use of as an alternative of require() and likewise will deep down into module a bit extra.
What are you utilizing
const specific = require('specific') // widespread js
What it is best to use
import specific from 'specific' // es module
Did you see ?? how a lot the higher code look in second one. The primary one is commonjs syntax which is current in node from its origin for importing libraries , the second was first launched in browser after which it got here to node.
It makes code a lot readable , fashionable and non – verbose.
Tips on how to use it ?
Its straightforward.
- Initialise new node challenge.
- Go to your bundle.json.
-
Add following to it.
"kind" : "module" ,
-
By default once you initialise your challenge its set to commonjs.
-
That is it now begin utilizing fashionable javascript.
Widespread patterns
As a substitute of explaining it I’m going to point out you commonjs code applied in module format, in an effort to begin it instantly , additionally comeback to this text in future if you end up confuse how one can do sure issues in module format.
Importing
// cjs
const specific = require('specific')
// mjs
import specific from 'specific'
// cjs
const specific = require('specific')
const Router = specific.Router
// mjs
import specific , { Router } from 'specific'
//cjs
const clientRouter = require('specific').Router
// mjs
import { Router as clientRouter } from 'specific'
Exporting
// cjs
module.exports = specific
// mjs
export default specific
// cjs
module.exports = {
router : {...} ,
utils : {...}
}
// mjs
export {
router : {...},
utils : {...}
}
Some extra exporting sample which will come helpful
// mjs
export default perform howdy() {...}
export const bye = "bye"