The difference between “require(x)” and import x

2019-02-01 20:31发布

问题:

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

回答1:

There are bunch of resource on online for your question even on SO. You can see here but the simple answer that helps me to understand the difference between require and import is Using Node.js require vs. ES6 import/export

With simple picture :



回答2:

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. But now most people would use babel to compile import and export, which will make import act the same as require, but the future version of Node.js might support import itself (actually, experimental version already did), 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?



回答3:

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