Author: Tania rascia
Crazy technology house
Original text:https://www.taniarascia.com/j…
In the era of the Internet, websites are mainly developed with HTML and CSS. If you load JavaScript into a page, it usually provides effects and interactions in the form of small fragments. Generally, all JavaScript code is written in a file and loaded into a filescript
Tag. Although JavaScript can be split into multiple files, all variables and functions are still added to the global scope.
However, JavaScript plays an important role in the browser. It is urgent to use third-party code to complete common tasks, and decompose the code into modular files to avoid polluting the global namespace.
The ECMAScript 2015 specification introduces themoduleThere are also import and export statements. In this article, let’s learn about JavaScript modules and how to use themimport
andexport
To organize the code.
Modular programming
Before the concept of modules appeared in JavaScript, when we wanted to organize our code into blocks, we usually created multiple files and linked them into separate scripts. Here’s an example. 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 link toscript
Two JavaScript files in the tag. openindex.html
And add the following code:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JavaScript Modules</title>
</head>
<body>
<h1>Answers</h1>
<h2><strong id="x"></strong> and <strong id="y"></strong></h2>
<h3>Addition</h3>
<p id="addition"></p>
<h3>Subtraction</h3>
<p id="subtraction"></p>
<h3>Multiplication</h3>
<p id="multiplication"></p>
<h3>Division</h3>
<p id="division"></p>
<script></script>
<script></script>
</body>
</html>
This page is very simple and will not be explained in detail.
functions.js
The file contains the mathematical functions that will be used in the second script. Open the file and add the following:
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
}
last,script.js
The file is used to determine the values of X and y, and to 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('division').textContent = quotient(x, y)
Open in browser after savingindex.html
You can see all the results:
This is an effective way to organize code for websites that only need a few small scripts. However, this method has some problems
- Pollute global namespace: all variables you create in the script(
sum
、difference
Now it’s all therewindow
Object. If you plan to use another file calledsum
It is difficult to know which value variable is used in other parts of the script, because they are all the samewindow.sum
Variable. The only way to make a variable private is to put it in the scope of a function. It’s even calledx
Ofid
May be withvar x
There is a conflict. - Dependency management: the script must be loaded from top to bottom to ensure that the correct variables can be used. Saving scripts as separate files creates the illusion of separation, but is essentially the same as a single file on a page
<script>
Same as in.
Before ES6 added native modules to the JavaScript language, the community tried to offer several solutions. The first solution is written in native JavaScript, such as writing all the code in objects or immediately called function expressions (Iife) and placing them on a single object in the global namespace. This is an improvement on the multi script method, but there is still the problem of putting at least one object into the global namespace, which does not make it easier to share code consistently among third parties.
Then came some modular solutions: commonjs is a Node.js Asynchronous module definition (AMD) is an asynchronous method, and there is a general method supporting the first two styles — universal module definition (UMD).
The emergence of these solutions makes it easier for us topackageSharing and reusing code, that is, modules that can be distributed and shared, such as NPM. However, because there are many solutions and none of them are native to JavaScript, you need to rely on tools such as Babel, webpack or browserify to use in browsers.
Because there are many problems in the multi file method and the solution is very complex, developers are very interested in introducing modular development method into JavaScript language. So ECMAScript 2015 started to support JavaScriptmodule。
moduleIs a set of code that provides the functions used by other modules and can use the functions of other modules.exportThe module provides code,importModules use other code. Modules are useful because they allow us to reuse code, they provide many stable, consistent interfaces available, and do not pollute the global namespace.
Modules (sometimes called es modules) can now be used in native JavaScript. In this article, we’ll explore how to use and implement them in code.
Native JavaScript module
Module usage in JavaScriptimport
andexport
keyword:
import
: used to read code exported from another module.export
: used to provide code to other modules.
Next, take the front onefunctions.js
The file is updated to a module and the function is exported. Add before each functionexport
。
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
}
stayscript.js
of useimport
From the frontfunctions.js
Module.
be careful:
import
You must always be at the top of the file before you write any other code, and you must also include the relative path (in this case, the./
)。
holdscript.js
Change the code in to look like this:
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('division').textContent = quotient(x, y)
Note: you can import by calling a list of functions in curly braces.
To ensure that the code is imported as a module and not loaded as a regular script, theindex.html
Mediumscript
Add in tagtype="module"
。 Any useimport
orexport
Must use this property for all code of
index.html
<script
type="module">
</script>
<script
type="module">
</script>
Due to the CORS policy, the module must be used in the server environment, otherwise the following error will appear:
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.
The differences between modules and regular scripts are as follows:
- Modules are not global(
window
)Scope adds anything. - The module is always in strict mode.
- Loading the first mock exam two times in the same file will not be a problem, because the module will only execute once.
- The module requires a server environment.
Modules are still often used with wrappers (such as webpack) to increase browser support and additional functionality, but they can also be used directly in browsers.
Next, explore more usesimport
andexport
The way of grammar.
Named export
As mentioned earlier, use theexport
Syntax allows you to import values exported by name separately. With thisfunction.js
For example, a simplified version of
functions.js
export function sum() {}
export function difference() {}
This allows you to import by name with curly bracessum
anddifference
:
script.js
import {sum, difference} from './functions.js'
You can also rename the function with an alias. The first mock exam can avoid naming conflicts in the same module. In this case,sum
Rename toadd
, anddifference
Rename tosubtract
。
script.js
import {
sum as add,
difference as subtract
} from './functions.js'
add(1, 2) // 3
Call hereadd()
Will producesum()
Function.
use*
Syntax can import the contents of an entire module into an object. under these circumstances,sum
anddifference
Will becomemathFunctions
Object.
script.js
import * as mathFunctions from './functions.js'
mathFunctions.sum(1, 2) // 3
mathFunctions.difference(10, 3) // 7
Primitive values, function expressions and definitions, asynchronous functions, classes, and instantiated classes can be exported as long as they have identifiers:
//Original value
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']
//Function expression
export const sum = (x, y) => x + y
//Function definition
export function difference(x, y) {
return x - y
}
//Anonymous function
export async function getBooks() {}
//Class
export class Book {
constructor(name, author) {
this.name = name
this.author = author
}
}
//Instantiation class
export const book = new Book('Lord of the Rings', 'J. R. R. Tolkein')
All of these exports can be imported successfully. Another type of export to explore next is called default export.
Default export
In the previous example, we exported multiple named exports and imported each export separately or as an object, each as a method on the object. Modules can also use keywordsdefault
Contains the default export. The default export does not import with braces, but is imported directly into the named identifier.
withfunctions.js
For example:
functions.js
export default function sum(x, y) {
return x + y
}
stayscript.js
File, you can import the default function assum
:
script.js
import sum from './functions.js'
sum(1, 2) // 3
However, this is dangerous because there are no restrictions on the naming of the default export during the import process. In this example, the default function is imported asdifference
Even though it issum
Function:
script.js
import difference from './functions.js'
difference(1, 2) // 3
Therefore, it is generally preferred to use named export. Unlike named exports, the default export does not require an identifier — either the original value itself or anonymous functions can be used as the default export. The following is an example of an object used as the default export:
functions.js
export default {
name: 'Lord of the Rings',
author: 'J. R. R. Tolkein',
}
It can be used asbook
Import:
functions.js
import book from './functions.js'
Similarly, the following example demonstrates how to export anonymous arrow functions as default exports:
functions.js
export default () => 'This function is anonymous'
You can import as follows:
script.js
import anonymousFunction from './functions.js'
Named export and default export can be used together. For example, in this module, two named values and one default value are exported
functions.js
export const length = 10
export const width = 5
export default function perimeter(x, y) {
return 2 * (x + y)
}
You can import these variables and default functions with the following command:
script.js
import calculatePerimeter, {length, width} from './functions.js'
calculatePerimeter(length, width) // 30
Both default and named values are now available for scripting.
summary
Modular programming allows us to divide code into individual components, which helps code reuse while protecting the global namespace. A module interface can use keywords in native JavaScriptimport
andexport
To achieve.
This article starts with WeChat official account: front-end pioneer.
Welcome to scan the two-dimensional code to pay attention to the official account, and push you every day to send fresh front-end technical articles.
Welcome to read the other great articles in this column:
- Deep understanding of shadow v1
- Step by step teaching you to use webvr to realize virtual reality games
- 13 modern CSS frameworks to improve your development efficiency
- Fast start bootstrap Vue
- How does the JavaScript engine work? Everything you need to know from call stack to promise
- Websocket: real time communication between node and react
- 20 interview questions about Git
- In depth analysis Node.js Of console.log
- Node.js What is it?
- 30 minutes Node.js Build an API server
- Object copy of JavaScript
- Programmer 30 years old before the monthly salary is less than 30K, where to go
- 14 best JavaScript data visualization Libraries
- 8 top-level vs code extensions for the front end
- Node.js A complete guide to multithreading
- Four schemes and implementation of transforming HTML into PDF