Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 11, 2022 04:26 am GMT

STOP using require() in node backend

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.

  1. Initialise new node project.
  2. Go to your package.json.
  3. Add following to it.

    "type" : "module" ,
  4. By default when you initialise your project its set to commonjs.

  5. 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

// cjsconst express = require('express')// mjsimport express from 'express'
// cjsconst express = require('express')const Router = express.Router// mjsimport express , { Router } from 'express'
//cjsconst clientRouter = require('express').Router// mjsimport { Router as clientRouter } from 'express'

Exporting

// cjsmodule.exports = express// mjsexport default express
// cjsmodule.exports = {    router : {...} ,    utils : {...}}// mjsexport {    router : {...},    utils : {...}}

Some more exporting pattern that may come handy

// mjsexport default function hello() {...}export const bye = "bye"

Original Link: https://dev.to/harshkumar77/stop-using-require-in-node-backend-1470

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To