Home > Web Front-end > JS Tutorial > Detailed introduction to require and import usage in Node

Detailed introduction to require and import usage in Node

巴扎黑
Release: 2017-08-15 10:20:30
Original
1638 people have browsed it

This article mainly introduces the detailed explanation of the difference between require and import of the imported module in Node. It has certain reference value. Interested friends can refer to it.

After the ES6 standard was released, module became the standard. The standard use is to export the interface with the export command and introduce the module with import. However, in our usual node module, we adopt the CommonJS specification and use require to introduce the module. , use module.exports to export the interface.

If the require and import are not sorted out clearly, it will be very ugly in future standard programming.

Module in the require era

One of the most important ideas in node programming is the module, and it is this idea that makes large-scale JavaScript projects possible. Modular programming is popular in the js world, and it is also based on this. Later, on the browser side, toolkits such as requirejs and seajs also appeared. It can be said that under the corresponding specifications, require dominated all modular programming before ES6, even now , this will still be the case until the ES6 module is fully implemented.

Node's module follows the CommonJS specification, requirejs follows AMD, and seajs follows CMD. Although they are different, we still hope to maintain a relatively unified code style.


// a.js

// -------- node -----------
module.exports = {
 a : function() {},
 b : 'xxx'
};

// ----------- AMD or CMD ----------------
define(function(require, exports, module){
 module.exports = {
  a : function() {},
  b : 'xxx'
 };
});
Copy after login

It can be seen that in order to maintain a high degree of unity in style, in addition to using a define function in the browser-side module to provide the closure of the module, other codes can Totally consistent.


// b.js

// ------------ node ---------
var m = require('./a');
m.a();

// ------------ AMD or CMD -------------
define(function(require, exports, module){
  var m = require('./a');
  m.a();
});
Copy after login

is also very similar in use. Although AMD or CMD provides richer styles, our article mainly discusses the node environment, so we will not extend it.

Module in ES6

The module released by ES6 does not directly use CommonJS, not even require, which means that require is still just a private part of the node. Global methods and module.exports are just global variable attributes private to node, and have nothing to do with standard methods.

export export module interface

The usage of export is quite complicated. You can see here for details. Here are a few examples:


// a.js
export default function() {}
export function a () {}

var b = 'xxx';
export {b}; // 这是ES6的写法,实际上就是{b:b}
setTimeout(() => b = 'ooo', 1000);
export var c = 100;
Copy after login

Add the export command in front of the interface to be exported.

After export, b can also be modified, which is hugely different from CommonJS. Regarding the internal mechanism, this article will shamelessly omit it.

Note that the following syntax has serious errors:


// 错误演示
export 1; // 绝对不可以
var a = 100;
export a;
Copy after login

When exporting an interface, it must have a one-to-one correspondence with the variables inside the module. . It makes no sense to export 1 directly, and it is impossible to have a variable corresponding to it when importing. Although export a seems to be valid, the value of a is a number and cannot be deconstructed at all, so it must be written in the form of export {a}. Even if a is assigned to a function, it is not allowed. Moreover, most styles suggest that it is best to use an export at the end of the module to export all interfaces, for example:


export {fun as default,a,b,c};
Copy after login

import import module

The syntax of import is different from require, and import must be placed at the beginning of the file, and no other logical code is allowed in front, which is consistent with the style of all other programming languages.

The use of import is the same as export, and it is quite complicated. You can get a general understanding here. To give a few examples:


import $ from 'jquery';
import * as _ from '_';
import {a,b,c} from './a';
import {default as alias, a as a_a, b, c} from './a';
Copy after login

There are some pitfalls here, which I will not disclose for the time being, but will be discussed below.

The form of import followed by curly braces is the most basic usage. The variables in the curly braces correspond to the variables after export. Here, you must understand the knowledge of object destructuring and assignment. Without this knowledge, you can't show off here at all. Understanding destructuring assignment, the "one-to-one correspondence" relationship here can be understood in detail.

as keyword

It is easy for programming students to understand as. To put it simply, it is just an alias. It can be used in export, and it can actually be used in import:


// a.js
var a = function() {};
export {a as fun};

// b.js
import {fun as a} from './a';
a();
Copy after login

The above code, when exported, the external interface provided is fun, which is a.js internal a The alias of this function, but outside the module, a is not recognized, only fun.

The as in import is very simple. When you use a method in the module, you give the method an alias so that it can be used in the current file. The reason for this is that sometimes two different modules may pass the same interface. For example, there is a c.js that also passes the fun interface:


// c.js
export function fun() {};
Copy after login

If you use the two modules a and c at the same time in b.js, you must find a way to solve the problem of duplicate interface names, and as will solve it.

default keyword

Other people write tutorials and put default in the export part, which I think is not conducive to understanding. When exporting, you may use default. To put it bluntly, it is actually the syntactic sugar of the alias:


// d.js
export default function() {}

// 等效于:
function a() {};
export {a as default};
Copy after login

When importing, you can use it like this:


import a from './d';

// 等效于,或者说就是下面这种写法的简写,是同一个意思
import {default as a} from './d';
Copy after login

The advantage of this syntax sugar is that you can omit the curly braces {} when importing. To put it simply, if you find that a variable is not enclosed in curly braces (no * sign) when importing, then you should restore it to the as syntax with curly braces in your mind.

所以,下面这种写法你也应该理解了吧:


import $,{each,map} from 'jquery';
Copy after login

import后面第一个 $ 是 {defalut as $} 的替代写法。

*符号

*就是代表所有,只用在import中,我们看下两个例子:


import * as _ from '_';
Copy after login

在意义上和 import _ from '_'; 是不同的,虽然实际上后面的使用方法是一样的。它表示的是把 '_' 模块中的所有接口挂载到 _ 这个对象上,所以可以用 _.each调用某个接口。

另外还可以通过*号直接继承某一个模块的接口:


export * from '_';

// 等效于:
import * as all from '_';
export all;
Copy after login

*符号尽可能少用,它实际上是使用所有export的接口,但是很有可能你的当前模块并不会用到所有接口,可能仅仅是一个,所以最好的建议是使用花括号,用一个加一个。

该用require还是import?

require的使用非常简单,它相当于module.exports的传送门,module.exports后面的内容是什么,require的结果就是什么,对象、数字、字符串、函数……再把require的结果赋值给某个变量,相当于把require和module.exports进行平行空间的位置重叠。

而且require理论上可以运用在代码的任何地方,甚至不需要赋值给某个变量之后再使用,比如:


require('./a')(); // a模块是一个函数,立即执行a模块函数
var data = require('./a').data; // a模块导出的是一个对象
var a = require('./a')[0]; // a模块导出的是一个数组
Copy after login

你在使用时,完全可以忽略模块化这个概念来使用require,仅仅把它当做一个node内置的全局函数,它的参数甚至可以是表达式:


require(process.cwd() + '/a');
Copy after login

但是import则不同,它是编译时的(require是运行时的),它必须放在文件开头,而且使用格式也是确定的,不容置疑。它不会将整个模块运行后赋值给某个变量,而是只选择import的接口进行编译,这样在性能上比require好很多。

从理解上,require是赋值过程,import是解构过程,当然,require也可以将结果解构赋值给一组变量,但是import在遇到default时,和require则完全不同: var $ = require('jQuery'); 和 import $ from 'jquery' 是完全不同的两种概念。

上面完全没有回答“改用require还是import?”这个问题,因为这个问题就目前而言,根本没法回答,因为目前所有的引擎都还没有实现import,我们在node中使用babel支持ES6,也仅仅是将ES6转码为ES5再执行,import语法会被转码为require。这也是为什么在模块导出时使用module.exports,在引入模块时使用import仍然起效,因为本质上,import会被转码为require去执行。

但是,我们要知道这样一个道理,ES7很快也会发布,js引擎们会尽快实现ES6标准的规定,如果一个引擎连标准都实现不了,就会被淘汰, ES6是迟早的事 。如果你现在仍然在代码中部署require,那么等到ES6被引擎支持时,你必须升级你的代码,而如果现在开始部署import,那么未来可能只需要做很少的改动。

The above is the detailed content of Detailed introduction to require and import usage in Node. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template