search
HomeWeb Front-endJS TutorialDetailed introduction to require and import usage in Node

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!

Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

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.