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' }; });
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(); });
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;
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;
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};
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';
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();
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() {};
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};
When importing, you can use it like this:
import a from './d'; // 等效于,或者说就是下面这种写法的简写,是同一个意思 import {default as a} from './d';
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';
import后面第一个 $ 是 {defalut as $} 的替代写法。
*符号
*就是代表所有,只用在import中,我们看下两个例子:
import * as _ from '_';
在意义上和 import _ from '_'; 是不同的,虽然实际上后面的使用方法是一样的。它表示的是把 '_' 模块中的所有接口挂载到 _ 这个对象上,所以可以用 _.each调用某个接口。
另外还可以通过*号直接继承某一个模块的接口:
export * from '_'; // 等效于: import * as all from '_'; export all;
*符号尽可能少用,它实际上是使用所有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模块导出的是一个数组
你在使用时,完全可以忽略模块化这个概念来使用require,仅仅把它当做一个node内置的全局函数,它的参数甚至可以是表达式:
require(process.cwd() + '/a');
但是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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.