node.js “require(x)”和“import x”的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46677752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The difference between "require(x)" and "import x"
提问by austinthemassive
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.
我刚刚开始研究一个将与 MongoDB 交互的小型节点项目。但是,我似乎无法正确导入相关的节点模块,即使我已通过npm.
For example, the following code throws an error, telling me that "express has no default export":
例如,以下代码抛出错误,告诉我“express 没有默认导出”:
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.
所以我的问题是,import 和 variable/require 方法的功能有何不同?我想修复在项目中困扰我的导入的任何问题,因为它似乎可能会导致其他问题。
回答by Always Sunny
This simple diagram that helps me to understand the difference between requireand import.
这个简单的图表,可以帮助我理解之间的差异require和import。
Apart from that,
除此之外,
You can'tselectively load only the pieces you need with requirebut with imports, you can selectively load only the pieces you need. That can save memory.
你不能有选择地只加载你需要的部分,require但是使用imports,你可以有选择地只加载你需要的部分。这样可以节省内存。
Loading is synchronous(step by step) for requireon the other hand importcan be asynchronous(without waiting for previous import) so it can perform a little better thanrequire.
加载是同步的(逐步),require另一方面import可以是异步的(无需等待先前的导入),因此它的性能比require.
回答by Ayon Lee
The major difference between requireand import, is that requirewill automatically scan node_modulesto find modules, but import, which comes from ES6, won't.
require和之间的主要区别import是require会自动扫描node_modules以查找模块,但是import来自 ES6 的 不会。
Most people use babelto compile importand export, which makes importact the same as require.
大多数人使用babel来编译import和export,这使得import行为与require.
The future version of Node.js might support importitself (actually, the experimental version already does), and judging by Node.js' notes, importwon't support node_modules, it base on ES6, and must specify the path of the module.
Node.js以后的版本可能会支持import自己(其实实验版已经支持了),根据Node.js的说明来看,import不会支持node_modules,它基于ES6,必须指定模块的路径。
So I would suggest you not use importwith babel, but this feature is not yet confirmed, it might support node_modulesin the future, who would know?
所以我建议你不要import和babel一起使用,但是这个功能还没有确认,以后可能会支持node_modules,谁知道呢?
For reference, below is an example of how babel can convert ES6's importsyntax to CommonJS's requiresyntax.
作为参考,下面是 babel 如何将 ES6 的import语法转换为 CommonJS 的require语法的示例。
Say the fileapp_es6.jscontains this import:
假设文件app_es6.js包含此导入:
import format from 'date-fns/format';
This is a directive to import the formatfunction from the node package date-fns.
The related package.jsonfile could contain something like this:
相关package.json文件可能包含如下内容:
"scripts": {
"start": "node app.js",
"build-server-file": "babel app_es6.js --out-file app.js",
"webpack": "webpack"
}
The related .babelrcfile could be something like this:
相关.babelrc文件可能是这样的:
{
"presets": [
[
"env",
{
"targets":
{
"node": "current"
}
}
]
]
}
This build-server-filescript defined in the package.jsonfile is a directive for babel to parse the app_es6.jsfile and output the file app.js.
文件中build-server-file定义的这个脚本package.json是babel解析app_es6.js文件并输出文件的指令app.js。
After running the build-server-filescript, if you open app.jsand look for the date-fnsimport, you will see it has been converted into this:
运行build-server-file脚本后,如果打开app.js并查找date-fns导入,您会看到它已转换为:
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-fnsand then open node_modules/date-fns/get_year/index.jsyou can see it contains:
同样作为参考,作为如何创建模块并将其导入项目的示例,如果您安装date-fns然后打开,node_modules/date-fns/get_year/index.js您可以看到它包含:
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.jsfile could then contain:
使用上面的 babel 过程,您的app_es6.js文件可以包含:
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:
并且 babel 会将导入转换为:
var _get_year = require("date-fns/get_year");
var _get_year2 = _interopRequireDefault(_get_year);
And handle all references to the function accordingly.
并相应地处理对函数的所有引用。
回答by saikiran_hegde
Let me give an example for Including express module with require & import
让我举个例子,包括带有 require 和 import 的 express 模块
-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,
因此,在使用上述任何语句后,我们将拥有一个名为“express”的变量。现在我们可以将“app”变量定义为,
var app = express();
So we use 'require' with 'CommonJS' and 'import' with 'ES6'.
因此,我们将“require”与“CommonJS”一起使用,将“import”与“ES6”一起使用。
For more info on 'require' & 'import', read through below links.
有关“要求”和“导入”的更多信息,请阅读以下链接。
require - Requiring modules in Node.js: Everything you need to know
require -在 Node.js 中需要模块:你需要知道的一切
import - An Update on ES6 Modules in Node.js
import - Node.js 中 ES6 模块的更新
回答by Tianpeng. Xia
Not an answer here and more like a comment, sorry but I can't comment.
这里不是答案,更像是评论,抱歉,我无法发表评论。
In node V10, you can use the flag --experimental-modulesto tell Nodejs you want to use import. But your entry script should end with .mjs.
在节点 V10 中,您可以使用标志--experimental-modules告诉 Nodejs 您要使用import. 但是您的输入脚本应该以.mjs.
Note this is still an experimental thing and should notbe used in production.
请注意,这仍然是一个实验性的东西,不应在生产中使用。
// main.mjs
import utils from './utils.js'
utils.print();
// utils.js
module.exports={
print:function(){console.log('print called')}
}
回答by LaZza
new ES6:
新的 ES6:
'import' should be used with 'export' key words to share variables/arrays/objects between js files:
'import' 应该与 'export' 关键字一起使用,以在 js 文件之间共享变量/数组/对象:
export default myObject;
//....in another file
import myObject from './otherFile.js';
old skool:
老学校:
'require' should be used with 'module.exports'
“require”应该与“module.exports”一起使用
module.exports = myObject;
//....in another file
var myObject = require('./otherFile.js');


