Search code examples
javascriptnode.jsimportmodulerequire

How do I change these require statements for these modules to use import statements instead?


I am looking to stop using require() statements for the following modules since Node version 11 now supports ES6, but I cannot locate any documentation on how to write the following except express as an import statement:

import express from "express";
const http = require('http');
import bodyParser from 'body-parser';
const morgan = require('morgan');

Is it the same as with bodyParser for morgan and http?

For example for morgan I have only seen:

import logger from 'morgan';

and for http I have only seen:

import * as http from 'http';


Solution

  • require is the primary syntax (in Node) for modules. As Patrick Roberts mentioned, you can only use them for a .mjs (module JS) file. require is how you import an NPM package/Node module:

    const express = require("express");
    const http = require("http");
    const bodyParser = require("body-parser");
    const morgan = require("morgan");
    

    If you do wish to use ES6 import/export, you need to use .mjs, as stated here.