[node.js] The difference between "require(x)" and "import x"

I've just started working on a small node project that will interface with a MongoDB. However, I cannot seem to get the relevant node modules to import correctly, even though I have installed them correctly via npm.

For example, the following code throws an error, telling me that "express has no default export":

import express from "express";

However, this code works:

const express = require("express");

So my question is, what is the difference in how the import and variable/require methods function? I'd like to fix whatever is plaguing my imports on the project, as it seems likely to cause additional problems down the road.

This question is related to node.js typescript import require

The answer is


The major difference between require and import, is that require will automatically scan node_modules to find modules, but import, which comes from ES6, won't.

Most people use babel to compile import and export, which makes import act the same as require.

The future version of Node.js might support import itself (actually, the experimental version already does), and judging by Node.js' notes, import won't support node_modules, it base on ES6, and must specify the path of the module.

So I would suggest you not use import with babel, but this feature is not yet confirmed, it might support node_modules in the future, who would know?


For reference, below is an example of how babel can convert ES6's import syntax to CommonJS's require syntax.

Say the fileapp_es6.js contains this import:

import format from 'date-fns/format';

This is a directive to import the format function from the node package date-fns.

The related package.json file could contain something like this:

"scripts": {
    "start": "node app.js",
    "build-server-file": "babel app_es6.js --out-file app.js",
    "webpack": "webpack"
}

The related .babelrc file could be something like this:

{
    "presets": [
        [
            "env",
            {
                "targets":
                {
                    "node": "current"
                }
            }
        ]
    ]
}

This build-server-file script defined in the package.json file is a directive for babel to parse the app_es6.js file and output the file app.js.

After running the build-server-file script, if you open app.js and look for the date-fns import, you will see it has been converted into this:

var _format = require("date-fns/format");

var _format2 = _interopRequireDefault(_format);

Most of that file is gobbledygook to most humans, however computers understand it.


Also for reference, as an example of how a module can be created and imported into your project, if you install date-fns and then open node_modules/date-fns/get_year/index.js you can see it contains:

var parse = require('../parse/index.js')

function getYear (dirtyDate) {
  var date = parse(dirtyDate)
  var year = date.getFullYear()
  return year
}

module.exports = getYear

Using the babel process above, your app_es6.js file could then contain:

import getYear from 'date-fns/get_year';

// Which year is 2 July 2014?
var result = getYear(new Date(2014, 6, 2))
//=> 2014

And babel would convert the imports to:

var _get_year = require("date-fns/get_year");

var _get_year2 = _interopRequireDefault(_get_year);

And handle all references to the function accordingly.


Not an answer here and more like a comment, sorry but I can't comment.

In node V10, you can use the flag --experimental-modules to tell Nodejs you want to use import. But your entry script should end with .mjs.

Note this is still an experimental thing and should not be used in production.

// main.mjs
import utils from './utils.js'
utils.print();
// utils.js
module.exports={
    print:function(){console.log('print called')}
}

Ref 1 - Nodejs Doc

Ref 2 - github issue


new ES6:

'import' should be used with 'export' key words to share variables/arrays/objects between js files:

export default myObject;

//....in another file

import myObject from './otherFile.js';

old skool:

'require' should be used with 'module.exports'

 module.exports = myObject;

//....in another file

var myObject = require('./otherFile.js');

Let me give an example for Including express module with require & import

-require

var express = require('express');

-import

import * as  express from 'express';

So after using any of the above statement we will have a variable called as 'express' with us. Now we can define 'app' variable as,

var app = express(); 

So we use 'require' with 'CommonJS' and 'import' with 'ES6'.

For more info on 'require' & 'import', read through below links.

require - Requiring modules in Node.js: Everything you need to know

import - An Update on ES6 Modules in Node.js


I will make it simple,

  • Import and Export are ES6 features(Next gen JS).
  • Require is old school method of importing code from other files

Major difference is in require, entire JS file is called or imported. Even if you don't need some part of it.

var myObject = require('./otherFile.js'); //This JS file will be imported fully.

Whereas in import you can extract only objects/functions/variables which are required.

import { getDate }from './utils.js'; 
//Here I am only pulling getDate method from the file instead of importing full file

Another major difference is you can use require anywhere in the program where as import should always be at the top of file


Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to import

Import functions from another js file. Javascript The difference between "require(x)" and "import x" pytest cannot import module while python can How to import an Excel file into SQL Server? When should I use curly braces for ES6 import? How to import a JSON file in ECMAScript 6? Python: Importing urllib.quote importing external ".txt" file in python beyond top level package error in relative import Reading tab-delimited file with Pandas - works on Windows, but not on Mac

Examples related to require

The difference between "require(x)" and "import x" PHP - Failed to open stream : No such file or directory cannot redeclare block scoped variable (typescript) NodeJs : TypeError: require(...) is not a function Include PHP file into HTML file How to make node.js require absolute? (instead of relative) Ruby 'require' error: cannot load such file Nodejs cannot find installed module on Windows is there a require for json in node.js node.js require all files in a folder?