Let's take a look at modules, Import and Export in JavaScript

coldplay.xixi
Release: 2020-12-29 17:31:49
forward
2455 people have browsed it

javascriptThe column introduces the usage of modules, Import and Export

Let's take a look at modules, Import and Export in JavaScript

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 ascripttag. 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 useimportandexportto 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 aindex.htmlfile and two JavaScript files “functions.jsandscript.js.

index.htmlThe file is used to display the sum, difference, product and quotient of two numbers and is linked to two JavaScript files in thescripttag. Openindex.htmlAnd add the following code:

index.html

nbsp;html>   JavaScript Modules 

Answers

and

Addition

Subtraction

Multiplication

pision

Copy after login

This page is very simple, so I won’t explain it in detail.

The functions.jsfile 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 }
Copy after login

Finally, thescript.jsfile 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)
Copy after login

After saving, openindex.htmlin the browser to see all the results:

Lets take a look at modules, Import and Export in JavaScript

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 thewindowobject. If you plan to use another one namedsumin another file variable, it will be difficult to know which value variable is used elsewhere in the script, because they all use the samewindow.sumvariable. The only way to make a variable private is to put it In the scope of the function. Even theidnamedxin 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 singleon 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.

module是一组代码,用来提供其他模块所使用的功能,并能使用其他模块的功能。export模块提供代码,import模块使用其他代码。模块之所以有用,是因为它们允许我们重用代码,它们提供了许多可用的稳定、一致的接口,并且不会污染全局命名空间。

模块(有时称为 ES 模块)现在可以在原生 JavaScript 中使用,在本文中,我们一起来探索怎样在代码中使用及实现。

原生 JavaScript 模块

JavaScript 中的模块使用importexport关键字:

  • 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 }
Copy after login

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)
Copy after login

注意:要通过在花括号中命名单个函数来导入。

为了确保代码作为模块导入,而不是作为常规脚本加载,要在index.html中的script标签中添加type="module"。任何使用importexport的代码都必须使用这个属性:

index.html

 
Copy after login

由于受限于 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.
Copy after login

模块与常规脚本不一样的地方:

  • 模块不会向全局(window)作用域添加任何内容。
  • 模块始终处于严格模式。
  • 在同一文件中把同一模块加载两次不会出问题,因为模块仅执行一次
  • 模块需要服务器环境。

模块仍然经常与打包程序(如 Webpack)一起配合使用,用来增加对浏览器的支持和附加功能,但它们也可以直接用在浏览器中。

接下来探索更多使用importexport语法的方式。

命名导出

如前所述,使用export语法允许你分别导入按名称导出的值。以这个function.js的简化版本为例:

functions.js

export function sum() {} export function difference() {}
Copy after login

这样允许你用花括号按名称导入sumdifference

script.js

import {sum, difference} from './functions.js'
Copy after login

也可以用别名来重命名该函数。这样可以避免在同一模块中产生命名冲突。在这个例子中,sum将重命名为add,而difference将重命名为subtract

script.js

import { sum as add, difference as subtract } from './functions.js' add(1, 2) // 3
Copy after login

在这里调用add()将产生sum()函数的结果。

使用*语法可以将整个模块的内容导入到一个对象中。在这种情况下,sumdifference将成为mathFunctions对象上的方法。

script.js

import * as mathFunctions from './functions.js' mathFunctions.sum(1, 2) // 3 mathFunctions.difference(10, 3) // 7
Copy after login

原始值、函数表达式和定义、异步函数、类和实例化的类都可以导出,只要它们有标识符就行:

// 原始值 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')
Copy after login

所有这些导出都可以成功被导入。接下来要探讨的另一种导出类型称为默认导出。

默认导出

在前面的例子中我们导出了多个命名的导出,并分别或作为一个对象导入了每个导出,将每个导出作为对象上的方法。模块也可以用关键字default包含默认导出。默认导出不使用大括号导入,而是直接导入到命名标识符中。

functions.js文件为例:

functions.js

export default function sum(x, y) { return x + y }
Copy after login

script.js文件中,可以用以下命令将默认函数导入为sum

script.js

import sum from './functions.js' sum(1, 2) // 3
Copy after login

不过这样做很危险,因为在导入过程中对默认导出的命名没有做任何限制。在这个例子中,默认函数被导入为difference,尽管它实际上是sum函数:

script.js

import difference from './functions.js' difference(1, 2) // 3
Copy after login

所以一般首选使用命名导出。与命名导出不同,默认导出不需要标识符——原始值本身或匿名函数都可以用作默认导出。以下是用作默认导出的对象的示例:

functions.js

export default { name: 'Lord of the Rings', author: 'J. R. R. Tolkein', }
Copy after login

可以用以下命令将其作为book导入:

functions.js

import book from './functions.js'
Copy after login

同样,下面的例子演示了如何将匿名箭头函数导出为默认导出:

functions.js

export default () => 'This function is anonymous'
Copy after login

可以这样导入:

script.js

import anonymousFunction from './functions.js'
Copy after login

命名导出和默认导出可以彼此并用,例如在这个模块中,导出两个命名值和一个默认值:

functions.js

export const length = 10 export const width = 5 export default function perimeter(x, y) { return 2 * (x + y) }
Copy after login

可以用以下命令导入这些变量和默认函数:

script.js

import calculatePerimeter, {length, width} from './functions.js' calculatePerimeter(length, width) // 30
Copy after login

现在默认值和命名值都可用于脚本了。

总结

模块化编程设计允许我们把代码分成单个组件,这有助于代码重用,同时还可以保护全局命名空间。一个模块接口可以在原生 JavaScript 中用关键字importexport来实现。

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!

Related labels:
source:segmentfault.com
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!