Home > database >  Best practice use of import instead of require with functions and reused variables
Best practice use of import instead of require with functions and reused variables

Time:09-10

What is the best practice of using import instead of require of called functions and reused variables - For example how should these require-lines look like as import?

const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);

CodePudding user response:

One possible way is to import the required functions and modules and use them in a next step:

import express from 'express';
import {createServer} from 'http';
import socketIo from 'socket.io';

const app = express();
const server = createServer(app);
const io = socketIo(server);

CodePudding user response:

import and require both of them are good to use. But by convention in node almost use require over than import.

If you are very fond of ES6, then you can use import and other es6 features. But one thing should bear in mind that, when you are using es6, it is a good practice to bundle your code with bundeller (like webpack,babel)

  • Related