search
HomeWeb Front-endJS TutorialComparison of import and export of AMD and ES6 modules in JavaScript (code example)

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//这么写会报错
}

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'

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}

input.js

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

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}

input.js

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

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' }

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}

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] }

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}

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' }

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' }
    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); //支持
}

require path support variables

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

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;

SoThe following two ways of writing are equivalent

exports.a ='valueA1'
module.exports.a='valueA1'
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;
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

input.js

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

Continue to look at the codeoutput.js

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

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

Look at another piece of codeoutput.js

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

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

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

交叉使用

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

demo1

output.js

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

inputj.s

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

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}

input.js

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

总结

  • 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
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

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 vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

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.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

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 in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

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.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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 the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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 vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

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 Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

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),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor