STOP using require() in node backend

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
Enter fullscreen mode

Exit fullscreen mode

What it is best to use

import specific from 'specific' // es module
Enter fullscreen mode

Exit fullscreen mode

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.

  1. Initialise new node challenge.
  2. Go to your bundle.json.
  3. Add following to it.

    "kind" : "module" ,
    
  4. By default once you initialise your challenge its set to commonjs.

  5. 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'
Enter fullscreen mode

Exit fullscreen mode

// cjs
const specific = require('specific')
const Router = specific.Router
// mjs
import specific , { Router } from 'specific'
Enter fullscreen mode

Exit fullscreen mode

//cjs
const clientRouter = require('specific').Router
// mjs
import { Router as clientRouter } from 'specific'
Enter fullscreen mode

Exit fullscreen mode



Exporting

// cjs
module.exports = specific
// mjs
export default specific
Enter fullscreen mode

Exit fullscreen mode

// cjs
module.exports = {
    router : {...} ,
    utils : {...}
}
// mjs
export {
    router : {...},
    utils : {...}
}
Enter fullscreen mode

Exit fullscreen mode



Some extra exporting sample which will come helpful

// mjs
export default perform howdy() {...}
export const bye = "bye"
Enter fullscreen mode

Exit fullscreen mode

Add a Comment

Your email address will not be published. Required fields are marked *