Table of Contents
export export module
Named export
默认导入
default关键字
Home Web Front-end JS Tutorial Introduction to JavaScript module export and import (detailed explanation)

Introduction to JavaScript module export and import (detailed explanation)

Feb 25, 2019 am 10:27 AM
es6 import javascript

This article brings you an introduction (detailed explanation) about JavaScript module export and import. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

I recently looked at some programs written in the Vue framework and found that my front-end knowledge was still a few years ago. I found that there are various imports of modules in Javascript programs now. At first glance, the imports It is quite similar to the syntax of python, except that the two keywords from and import are used in the reverse order. If you look carefully, the import module is quite different from Python. The premise is that the module has exports, and it is also divided into default exports and named exports, which is a bit troublesome. So today’s article summarizes all export forms and corresponding import uses.

ES6 implements module functions at the level of language standards and becomes a universal module solution for browsers and servers. It can completely replace CommonJS and AMD specifications. The basic features are as follows:

  • Each module is only loaded once, and each JS is only executed once. If you load the same file in the same directory next time, it will be read directly from the memory;

  • Every The variables declared in a module are all local variables and will not pollute the global scope;

  • Variables or functions inside the module can be exported through export;

  • A module can import other modules

2. The module function mainly consists of two commands: export and import. The export command is used to specify the external interface of the module, and the import command is used to input the functions provided by other modules;

3. A module is an independent file, and all variables inside the file cannot be obtained externally. If you want the outside to be able to read a variable inside the module, you must use the export keyword to output the variable;

var year = '2018';
var month = 'Febuary';
export {year, month};
Copy after login

export export module

export syntax statement is used to export functions, objects, Specifies the original value of the file (or module). There are two module export methods: named export (name export) and default export (definition export) . Each module can have multiple named exports, while each default export Only one module.

Named export

The module can declare the export object through the export prefix keyword, and the export object can be multiple. These export objects are distinguished by names, which are called named exports

export { func }; // 导出一个已定义的函数func
export const foo = Math.sqrt(100); // 导出一个常量
Copy after login

We can use the * and from keywords to implement module inheritance:

export * from 'base_module';
Copy after login

When exporting a module, you can specify the module exported members. Exported members can be considered as public members in the class, while non-exported members can be considered as private members in the class:

var name = 'Kevin的居酒屋';
var domain = 'http://coffee.toast.com';
 
export {name, domain}; // 相当于导出{name:name,domain:domain}
Copy after login

When the module is exported, we can use the as keyword to rename the exported members, as shown above Export can be written like this:

export {name as siteName, domain}
Copy after login

Note the syntax errors:

export 1; 
var a = 100;
export a;
Copy after login

When exporting the interface, it must have a one-to-one correspondence with the variables inside the module. Directly exporting 1 makes no sense, and it is impossible to have a variable corresponding to it when importing export aAlthough it seems to be true, the value of a is a number, and deconstruction cannot be completed at all, so it must be written as ## The form of #export {a}. Even if a is assigned to a function, it is not recommended to use the above form to export because most styles suggest that it is best to use an export at the end of the module to export all interfaces, just like the examples above.

Default export

Default export is also called defined export. Named export can export multiple values, but when importing a reference, the same name must also be used to reference the corresponding value. The default export only exports a single value. This output can be a function, class or other type of value, which will be easier to reference when the module is imported.

export default function() {}; // 导出一个函数
export default class(){}; // 导出一个类
Copy after login
Default export can be understood as another form of named export. Default export can be considered as a named export using the default name.

The following two export methods are equivalent:

const D = 123; 
export default D;
export { D as default };
Copy after login
When exporting a module using a name:

// "my-module.js" 模块
function cube(x) {
    return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
export { cube, foo };
Copy after login
In another module (js file), we can like Quote as follows:

import { cube, foo } from 'my-module';
console.log(cube(3));
console.log(foo);
Copy after login
When using the default export of a module:

// "my-module.js"模块
export default function (x) {
return x * x * x;
}
Copy after login
In another module, we can quote as follows, which is simpler to use than name export:

import cube from 'my-module';
console.log(cube(3)); // 27
Copy after login
import import module

The import syntax statement is used to import functions, objects, and the original values ​​​​of specified files (or modules) from exported modules and scripts. The import module import corresponds to the export module export function. There are also two module import methods: named import (name import) and default import (definition import).

Note: The import must be placed at the beginning of the file, and no other logical code is allowed in front. This is consistent with the import style of all other programming languages.

Named import

We can insert imported members into the current scope by specifying a name. You can import a single member or multiple members:

Note that the variables in the curly braces correspond to the variables after export

import {myMember} from "my-module";
import {foo, bar} from "my-module";
Copy after login

通过*符号,我们可以导入模块中的全部属性和方法。当导入模块全部导出内容时,就是将导出模块(’my-module.js’)所有的导出绑定内容,插入到当前模块(’myModule’)的作用域中:

import * as myModule from "my-module";
Copy after login

默认导入

在模块导出时,可能会存在默认导出。同样的,在导入时可以使用import指令导入这些默认值。直接导入默认值:

import defaultName from "my-module";
import myDefault, {foo, bar} from "my-module"; // 指定成员导入和默认导入
Copy after login

default关键字

// my-module.js
export default function() {}
 
// 等效于:
function func() {};
export {func as default};
Copy after login

在import的时候,可以这样用:

import a from './my-module';
 
// 等效于,或者说就是下面这种写法的简写
import {default as a} from './my-module';
Copy after login

这个语法糖的好处就是import的时候,可以省去{}。

简单的说,如果import的时候,你发现某个变量没有花括号括起来(没有*号),那么你在脑海中应该把它还原成有花括号的{default as ...}语法,所以import $,{each,map} from 'jquery';import后面第一个$是{default as $}的替代写法。

The above is the detailed content of Introduction to JavaScript module export and import (detailed explanation). For more information, please follow other related articles on the PHP Chinese website!

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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles