Home > Web Front-end > JS Tutorial > Learn more about modules, import and export in JavaScript

Learn more about modules, import and export in JavaScript

青灯夜游
Release: 2020-12-04 17:35:05
forward
9382 people have browsed it

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 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 linked them as a separate script. 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>Answers</h1>
    <h2>
<strong></strong> and <strong></strong>
</h2>

    <h3>Addition</h3>
    <p></p>

    <h3>Subtraction</h3>
    <p></p>

    <h3>Multiplication</h3>
    <p></p>

    <h3>pision</h3>
    <p></p>

    <script></script>
    <script></script>
  
Copy after login

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

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

After saving, open index.html in the browser to see all the results:

Learn more about 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 the window object. If you plan to use another one named sum in another file variable, it will be difficult to know which value variable is used elsewhere in the script, because they all use the same window.sum variable. The only way to make a variable private is to put it In the scope of the function. Even the id named x in the DOM may conflict with var 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 is a set of codes that provide functions used by other modules and can use the functions of other modules. export modules provide code, import modules 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 模块

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

<script>
</script>
<script>
</script>
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 来实现。

原文地址: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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template