Home>Article>Web Front-end> Learn more about modules, import and export in JavaScript
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 ascript
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 introducedmodulein the JavaScript language, as well as import and export statements. In this article, we learn about JavaScript modules and how to useimport
andexport
to organize code.
Before the concept of modules appeared in JavaScript, when we wanted to organize our code into multiple blocks, we usually created multiple files and linked them as a separate script. Let’s give an example below. First create aindex.html
file and two JavaScript files “functions.js
andscript.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 thescript
tag. Openindex.html
And add the following code:
index.html
nbsp;html>JavaScript Modules Answers
and
Addition
Subtraction
Multiplication
pision
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, thescript.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, openindex.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:
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
.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 ofpackages, 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 JavaScriptmodule.
moduleis a set of codes that provide functions used by other modules and can use the functions of other modules.exportmodules provide code,importmodules consume other code. Modules are useful because they allow us to reuse code, they provide many stable, consistent interfaces available, and they do not pollute the global namespace.
模块(有时称为 ES 模块)现在可以在原生 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
由于受限于 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
来实现。
原文地址:https://www.taniarascia.com/javascript-modules-import-export/
作者:Tania Rascia
译文地址:https://segmentfault.com/a/1190000038275195
更多编程相关知识,请访问:编程学习!!
The above is the detailed content of Learn more about modules, import and export in JavaScript. For more information, please follow other related articles on the PHP Chinese website!