Table of Contents
exoprt and export default
exoprt and export default are mixed together
as rename
require
require path support variables
exports and module.exports
Inside each module, the module variable represents the current module. This variable is an object, and its exports attribute (ie module.exports) is the external interface. Loading a module actually loads the module.exports attribute of the module.
交叉使用
demo2
总结
Home Web Front-end JS Tutorial Comparison of import and export of AMD and ES6 modules in JavaScript (code example)

Comparison of import and export of AMD and ES6 modules in JavaScript (code example)

Mar 25, 2019 pm 02:23 PM
es6 javascript

The content of this article is about the comparison of import and export of AMD and ES6 modules in JavaScript (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Our front-end often encounters the import and export functions during the development process.
When importing, sometimes it is require, sometimes it is import
When exporting, sometimes it is exports, module. exports, sometimes export, export default
Today we will briefly introduce these contents

import, export, export default

import, export, export default belong to the ES6 specification

import

import is executed during the compilation process
That is to say, it is executed before the code is executed.
For example, if the path after import is written incorrectly, it will be executed before running the code. An error will be thrown.
When writing code, import does not have to be written at the front of js.
The import command has a lifting effect and will be promoted to the head of the entire module and executed first. (It is executed during the compilation phase)
Import is executed statically
Because import is executed statically, expressions and variables cannot be used, that is, the syntax structure that can only get the result at runtime
For example, it cannot Use import
again in if and else. For another example, the path of from after import can be a relative path or an absolute path, but it cannot be a path obtained based on a variable

//import 路径不可以为变量
var url = './output'
  import {
    a,
    b
  } from url//这么写会报错
//------------------
//import 的引入与否不能和代码逻辑向关联
let status= true
if(status){
     import {
    a,
    b
  } from url//这么写会报错
}
Copy after login

import You can use as to rename
There are many import methods.

  import foo from './output'
  import {b as B} from './output'
  import * as OBj from './output'
  import {a} from './output'
  import {b as BB} from './output'
  import c, {d} from './output'
Copy after login

The import method is somewhat related to the export. When we talk about export below, we will discuss the above import methods one by one. Introduction

exoprt and export default

Put exoprt and export default together because they are closely related
Simply put: export is export, and export default is the default export
A module can have multiple exports, but there can only be one export default. Export default can coexist with multiple exports.
Export default is the default export, and the export is an object wrapped in {}. Existing in the form of key-value pairs
Different ways of exporting will lead to different ways of importing.
So it is recommended to use the same import and export method under the same project to facilitate development
export After default deconstruction, it is export
Let’s look at the difference between export and export default through two intuitive demos
Let’s first look at a piece of code (export)
output.js

const a = 'valueA1'
export {a}
Copy after login

input.js

import {a} from './output.js'//此处的import {a}和export {a},两个a是一一对应关系
console.log(a)//=>valueA1
Copy after login

Note that in the above code, the a exported by export {a} is the same a as the a imported by import {a}
Look at another section of code (export default)

const a = 'valueA1'
export default{a}
Copy after login

input.js

import a from './output.js'//此处的a和export default{a},不是一个a,
console.log(a)//=>{ a: 'valueA1' }
Copy after login

Look at the input.js in the chestnut of export default. We made some changes.

import abc from './output.js'//此处的a和export default{a},不是一个a,
console.log(abc)//=>{ a: 'valueA1' }
Copy after login

We made some changes, but the output did not change. The import imports the objects under export default. , you can call it any name, because there will only be one export default

exoprt and export default are mixed together

exoprt and export default are used in the same module at the same time, which is supported, although we Generally this is not done
Look at a chestnut
output.js

const a = 'valueA1'
const b = 'valueB1'
const c = 'valueC1'
const d = 'valueD1'
function foo() {
  console.log(`foo执行,c的值是${c}`);
}
export {a}
export {b}
export default { b,d,foo}
Copy after login
Copy after login

input.js

import obj, {a,b } from './output'
console.log(a); //=>valueA1
console.log(b); //=>valueB1
console.log(obj); //=>{ b: 'valueB1', d: 'valueD1', foo: [Function: foo] }
Copy after login

as rename

Exported through exoprt and export default When import is introduced, renaming through as is supported
Let’s take a look
It’s still the output.js above

const a = 'valueA1'
const b = 'valueB1'
const c = 'valueC1'
const d = 'valueD1'
function foo() {
  console.log(`foo执行,c的值是${c}`);
}
export {a}
export {b}
export default { b,d,foo}
Copy after login
Copy after login

input.js

import {a as A} from './output'
import {* as A} from './output'//这是不支持的
import * as obj from './output'
console.log(A); //=>valueA1
console.log(obj); //=>{ a: 'valueA1',default: { b: 'valueB1', d: 'valueD1', foo: [Function: foo] },b: 'valueB1' }
Copy after login

The variable after as is yours To be used in input.js, focus on this part

import {* as A} from './output'//这是不支持的
import * as obj from './output'
console.log(obj); //=>{ a: 'valueA1',default: { b: 'valueB1', d: 'valueD1', foo: [Function: foo] },b: 'valueB1' }
Copy after login
    represents everything, including export and export default export
We said import before {} and export{} have a one-to-one correspondence, so exporting in export does not support using import{} require, exports, module.exports (remember the following s)


This is the AMD specification

require

require is a runtime call, so require can theoretically Used anywhere in the code

require supports dynamic introductionFor example, this is supported

let flag = true
if (flag) {
  const a = require('./output.js')
  console.log(a); //支持
}
Copy after login

require path support variables

let flag = true
let url = './output.js'
if (flag) {
  const a = require(url)
  console.log(a); //支持
}
Copy after login

pass The require introduction is a process of assignment

exports and module.exports

According to AMD specifications

Each file is a module and has its own scope. Variables, functions, and classes defined in a file are private and not visible to other files.

Inside each module, the module variable represents the current module. This variable is an object, and its exports attribute (ie module.exports) is the external interface. Loading a module actually loads the module.exports attribute of the module.

For convenience, Node provides an exports variable for each module, pointing to module.exports. This is equivalent to having a line like this at the head of each module.

const exports = module.exports;
Copy after login
Copy after login

SoThe following two ways of writing are equivalent

exports.a ='valueA1'
module.exports.a='valueA1'
Copy after login
As mentioned earlier, provide an exports variable in each module, pointing to module.exports.

So you cannot directly assign a value to exports, the assignment will overwrite

const exports = module.exports;
Copy after login
Copy after login
Assigning a value to exports directly will cut off the relationship between exports and module.exports

Look at a chestnut
output.js

const a = 'valueA1'
const b = 'valueB1'
const c = 'valueC1'
module.exports = { c}
exports.b = b//当直接给 module.exports时,exports会失效
module.exports.a = a
Copy after login

input.js

  const obj = require('./output.js')
  console.log(obj); //=>{ c: 'valueC1', a: 'valueA1' }
Copy after login
Copy after login

Continue to look at the codeoutput.js

//部分省略
exports.b = b//这样可以生效
module.exports.a = a
Copy after login
input.js

  const obj = require('./output.js')
  console.log(obj); //=>{ b: 'valueB1', a: 'valueA1' }
Copy after login

Look at another piece of codeoutput.js

//部分省略
module.exports = { c}
module.exports.a = a
Copy after login
Copy after login
input.js

  const obj = require('./output.js')
  console.log(obj); //=>{ c: 'valueC1', a: 'valueA1' }
Copy after login
Copy after login

当直接给 module.exports时,exports会失效

交叉使用

在ES6中export default 导出的是一个对象
在AMD中exports和module.exports导出的也都是一个对象
所以如果你手中的项目代码支持两种规范,那么事可以交叉使用的(当然不建议这么去做)
通过export导出的不一定是一个对象

demo1

output.js

//部分省略
module.exports = { c}
module.exports.a = a
Copy after login
Copy after login

inputj.s

import obj from './output'
import {a} from './output'
console.log(a);//=>valueA1
console.log(obj);//=>{ c: 'valueC1', a: 'valueA1' }
Copy after login

demo2

output.js

const a = 'valueA1'
const b = 'valueB1'
const c = 'valueC1'
function foo() {
  console.log(`foo执行,c的值是${c}`);
}
export {a}
export default {b,c,foo}
export {b}
Copy after login

input.js

  const a = require('./output.js')
  console.log(a); //=>{ a: 'valueA1',default: { b: 'valueB1', c: 'valueC1', foo: [Function: foo] }, b: 'valueB1' }
Copy after login

总结

  • require,exports,module.export属于AMD规范,import,export,export default属于ES6规范
  • require支持动态导入,动态匹配路径,import对这两者都不支持
  • require是运行时调用,import是编译时调用
  • require是赋值过程,import是解构过程
  • 对于export和export default 不同的使用方式,import就要采取不同的引用方式,主要区别在于是否存在{},export导出的,import导入需要{},导入和导出一一对应,export default默认导出的,import导入不需要{}
  • exports是module.export一种简写形式,不能直接给exports赋值
  • 当直接给module.export赋值时,exports会失效

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的JavaScript视频教程栏目!

The above is the detailed content of Comparison of import and export of AMD and ES6 modules in JavaScript (code example). 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