Let's take a look at modules, Import and Export in JavaScript
javascriptThe column introduces the usage of modules, Import and Export
Recommended (Free): javascript (Video)
In the prehistoric era of the Internet, websites were mainly developed using HTML and CSS. If JavaScript is loaded into a page, it usually provides effects and interactions in small fragments. Generally, all JavaScript code is written in one file and loaded into a script
tag. Even though JavaScript can be split into multiple files, all variables and functions are still added to the global scope.
But then JavaScript played an important role in browsers, and there was an urgent need to use third-party code to complete common tasks, and the code needed to be broken down into modular files to avoid polluting the global namespace.
The ECMAScript 2015 specification introduced module in the JavaScript language, as well as import and export statements. In this article, we learn about JavaScript modules and how to use import
and export
to organize code.
Modular Programming
Before the concept of modules appeared in JavaScript, when we wanted to organize our code into multiple blocks, we usually created multiple files and link them into separate scripts. Let’s give an example below. First create a index.html
file and two JavaScript files “functions.js
and script.js
.
index.html
The file is used to display the sum, difference, product and quotient of two numbers and is linked to two JavaScript files in the script
tag. Open index.html
And add the following code:
index.html
nbsp;html> <meta> <meta> <title>JavaScript Modules</title> <h1 id="Answers">Answers</h1> <h2> <strong></strong> and <strong></strong> </h2> <h3 id="Addition">Addition</h3> <p></p> <h3 id="Subtraction">Subtraction</h3> <p></p> <h3 id="Multiplication">Multiplication</h3> <p></p> <h3 id="pision">pision</h3> <p></p> <script></script> <script></script>
This page is very simple, so I won’t explain it in detail.
The functions.js
file contains the math functions that will be used in the second script. Open the file and add the following content:
functions.js
function sum(x, y) { return x + y } function difference(x, y) { return x - y } function product(x, y) { return x * y } function quotient(x, y) { return x / y }
Finally, the script.js
file is used to determine the values of x and y, as well as call the previous functions and display the results:
script.js
const x = 10 const y = 5 document.getElementById('x').textContent = x document.getElementById('y').textContent = y document.getElementById('addition').textContent = sum(x, y) document.getElementById('subtraction').textContent = difference(x, y) document.getElementById('multiplication').textContent = product(x, y) document.getElementById('pision').textContent = quotient(x, y)
After saving, open index.html
in the browser to see all the results:
For websites that only require some small scripts, This is an effective way to organize code. However, there are some problems with this method:
-
Polluting the global namespace: All variables you create in the script (
sum
,difference
, etc.) now exist in thewindow
object. If you plan to use another one namedsum
in another file variable, it will be difficult to know which value variable is used elsewhere in the script, because they all use the samewindow.sum
variable. The only way to make a variable private is to put it In the scope of the function. Even theid
namedx
in the DOM may conflict withvar x
. -
Dependencies Management: Scripts must be loaded from top to bottom to ensure that the correct variables are used. Saving scripts as separate files creates the illusion of separation, but is essentially the same as placing them in a single
on the page
.
Before ES6 added native modules to the JavaScript language, the community tried to provide several solutions. The first solution was written in native JavaScript , such as writing all code in objects or immediately invoked function expressions (IIFEs) and placing them on a single object in the global namespace. This is an improvement over the multi-script approach, but still has the problem of putting at least one object into the global namespace and doesn't make the problem of consistently sharing code between third parties any easier.
After that, some module solutions appeared: CommonJS is a synchronous method implemented in Node.js, Asynchronous Module Definition (AMD) is an asynchronous method, and there are general methods that support the previous two styles. ——Universal module definition (UMD).
The emergence of these solutions makes it easier for us to share and reuse code in the form of packages, that is, modules that can be distributed and shared, such as npm. But since many solutions exist, and none are native to JavaScript, you need to rely on tools like Babel, Webpack, or Browserify to use them in the browser.
Because the multi-file approach has many problems and complex solutions, developers are very interested in bringing modular development methods to the JavaScript language. So ECMAScript 2015 began to support JavaScript module.
module 是一组代码,用来提供其他模块所使用的功能,并能使用其他模块的功能。 export 模块提供代码,import 模块使用其他代码。模块之所以有用,是因为它们允许我们重用代码,它们提供了许多可用的稳定、一致的接口,并且不会污染全局命名空间。
模块(有时称为 ES 模块)现在可以在原生 JavaScript 中使用,在本文中,我们一起来探索怎样在代码中使用及实现。
原生 JavaScript 模块
JavaScript 中的模块使用import
和 export
关键字:
-
import
:用于读取从另一个模块导出的代码。 -
export
:用于向其他模块提供代码。
接下来把前面的的 functions.js
文件更新为模块并导出函数。在每个函数的前面添加 export
。
functions.js
export function sum(x, y) { return x + y } export function difference(x, y) { return x - y } export function product(x, y) { return x * y } export function quotient(x, y) { return x / y }
在 script.js
中用 import
从前面的 functions.js
模块中检索代码。
注意:import
必须始终位于文件的顶部,然后再写其他代码,并且还必须包括相对路径(在这个例子里为./
)。
把 script.js
中的代码改成下面的样子:
script.js
import { sum, difference, product, quotient } from './functions.js' const x = 10 const y = 5 document.getElementById('x').textContent = x document.getElementById('y').textContent = y document.getElementById('addition').textContent = sum(x, y) document.getElementById('subtraction').textContent = difference(x, y) document.getElementById('multiplication').textContent = product(x, y) document.getElementById('pision').textContent = quotient(x, y)
注意:要通过在花括号中命名单个函数来导入。
为了确保代码作为模块导入,而不是作为常规脚本加载,要在 index.html
中的 script
标签中添加type="module"
。任何使用 import
或 export
的代码都必须使用这个属性:
index.html
<script> </script> <script> </script>
由于受限于 CORS 策略,必须在服务器环境中使用模块,否则会出现下面的错误:
Access to script at 'file:///Users/your_file_path/script.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
模块与常规脚本不一样的地方:
- 模块不会向全局(
window
)作用域添加任何内容。 - 模块始终处于严格模式。
- 在同一文件中把同一模块加载两次不会出问题,因为模块仅执行一次
- 模块需要服务器环境。
模块仍然经常与打包程序(如 Webpack)一起配合使用,用来增加对浏览器的支持和附加功能,但它们也可以直接用在浏览器中。
接下来探索更多使用 import
和 export
语法的方式。
命名导出
如前所述,使用 export
语法允许你分别导入按名称导出的值。以这个 function.js
的简化版本为例:
functions.js
export function sum() {} export function difference() {}
这样允许你用花括号按名称导入 sum
和 difference
:
script.js
import {sum, difference} from './functions.js'
也可以用别名来重命名该函数。这样可以避免在同一模块中产生命名冲突。在这个例子中,sum
将重命名为 add
,而 difference
将重命名为 subtract
。
script.js
import { sum as add, difference as subtract } from './functions.js' add(1, 2) // 3
在这里调用 add()
将产生 sum()
函数的结果。
使用 *
语法可以将整个模块的内容导入到一个对象中。在这种情况下,sum
和 difference
将成为 mathFunctions
对象上的方法。
script.js
import * as mathFunctions from './functions.js' mathFunctions.sum(1, 2) // 3 mathFunctions.difference(10, 3) // 7
原始值、函数表达式和定义、异步函数、类和实例化的类都可以导出,只要它们有标识符就行:
// 原始值 export const number = 100 export const string = 'string' export const undef = undefined export const empty = null export const obj = {name: 'Homer'} export const array = ['Bart', 'Lisa', 'Maggie'] // 函数表达式 export const sum = (x, y) => x + y // 函数定义 export function difference(x, y) { return x - y } // 匿名函数 export async function getBooks() {} // 类 export class Book { constructor(name, author) { this.name = name this.author = author } } // 实例化类 export const book = new Book('Lord of the Rings', 'J. R. R. Tolkein')
所有这些导出都可以成功被导入。接下来要探讨的另一种导出类型称为默认导出。
默认导出
在前面的例子中我们导出了多个命名的导出,并分别或作为一个对象导入了每个导出,将每个导出作为对象上的方法。模块也可以用关键字 default
包含默认导出。默认导出不使用大括号导入,而是直接导入到命名标识符中。
以 functions.js
文件为例:
functions.js
export default function sum(x, y) { return x + y }
在 script.js
文件中,可以用以下命令将默认函数导入为 sum
:
script.js
import sum from './functions.js' sum(1, 2) // 3
不过这样做很危险,因为在导入过程中对默认导出的命名没有做任何限制。在这个例子中,默认函数被导入为 difference
,尽管它实际上是 sum
函数:
script.js
import difference from './functions.js' difference(1, 2) // 3
所以一般首选使用命名导出。与命名导出不同,默认导出不需要标识符——原始值本身或匿名函数都可以用作默认导出。以下是用作默认导出的对象的示例:
functions.js
export default { name: 'Lord of the Rings', author: 'J. R. R. Tolkein', }
可以用以下命令将其作为 book
导入:
functions.js
import book from './functions.js'
同样,下面的例子演示了如何将匿名箭头函数导出为默认导出:
functions.js
export default () => 'This function is anonymous'
可以这样导入:
script.js
import anonymousFunction from './functions.js'
命名导出和默认导出可以彼此并用,例如在这个模块中,导出两个命名值和一个默认值:
functions.js
export const length = 10 export const width = 5 export default function perimeter(x, y) { return 2 * (x + y) }
可以用以下命令导入这些变量和默认函数:
script.js
import calculatePerimeter, {length, width} from './functions.js' calculatePerimeter(length, width) // 30
现在默认值和命名值都可用于脚本了。
总结
模块化编程设计允许我们把代码分成单个组件,这有助于代码重用,同时还可以保护全局命名空间。一个模块接口可以在原生 JavaScript 中用关键字 import
和 export
来实现。
The above is the detailed content of Let's take a look at modules, Import and Export in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

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 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

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.