Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to import and export modules in JavaScript

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Today, I will talk to you about how to import and export modules in JavaScript. Many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.

Brief introduction

The early Web website was mainly composed of HTML and CSS. If there is any JavaScript code that needs to be executed on the page, it is usually in the form of small code snippets to provide functionality and interactivity. The result is that usually the JavaScript code is written in a file and then loaded into the page through the script tag. Developers can split JavaScript code into multiple js files, but all JavaScript variables and functions are added to the global scope.

But with the development of Web framework technologies such as Angular, React and Vue, and most companies are developing advanced Web applications rather than desktop applications, JavaScript becomes more and more important. It is necessary to encapsulate the reusable code logic into common code and modularize it without global namespace pollution.

The ECMAScript 2015 specification introduces the concept of modules that allows the use of import and export statements. In this tutorial, you will learn what the JavaScript module is and how to manage the code structure using import and export.

Modular programming

Before JavaScript introduced the concept of modularity, when developers wanted to encapsulate the code, they needed to create multiple files and link them as separate scripts. To illustrate this point, the author created an example: the index.html file and two JavaScript files, functions.js and script.js.

The index.html file will display the results of the sum, difference, product and quotient of the two numbers and link to the two JavaScript files in the script tag. Create a new index.html in the text editor and add the following code:

JavaScript Modules Answers and Addition

Subtraction

Multiplication

Division

The HTML displays the values of the variables x and y in the h3 tag and the operational values of those variables in the p element below them. Element id attribute to facilitate DOM operations in the script.js file, the script.js file also sets the values of x and y. For more information about HTML, please refer to my series on how to use HTML to create a website.

The functions.js file provides the mathematical functions that will be used in the second script. Open the functions.js file and add the following:

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 calculates the values of x and y and displays the results:

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)

After you have done the above, you can open index.html in the browser to view the running result:

This is a very efficient code splitting scheme for website applications with only a small number of script files. However, there are some problems with this approach:

Pollute the global namespace: all variables created in the script, including sum, difference, and so on, will be stored in the global window object. If you try to use a variable named sum in a file, it will be difficult to know which script we are using sum in, because they all use the same global window.sum variable. The only way to privatize a variable is to put the variable in the scope of the function. There is also a conflict between the id attribute named x in DOM and the variable var id (because if the id attribute is used in DOM, the browser declares a global variable with the same name).

Dependency management: script must be loaded from top to bottom to ensure that variables are available correctly. The introduction of separate files in turn gives the illusion of separation, but this approach is essentially the same as using a single to introduce script code in a browser page.

Before ES6 added the concept of native modules to the JavaScript language, the community tried several solutions. The first solution is implemented through normal JavaScript objects, such as writing all the code in objects or immediately called function expressions (IIFE) and placing them in a single object in the global scope. This is an improvement on the multi-scripting approach, but there will still be the same problem of putting at least one object into the global namespace, and the problem of sharing code between multiple scripts has never been solved.

After that, there are some modular solutions: CommonJS, a synchronous loading module implemented in Node.js, an asynchronous module definition (AMD), an asynchronous loading module, and a generic module definition (UMD), designed to become a general solution that can support both loading modes.

The emergence of these solutions makes it easier for developers to share and reuse code in the form of package, and these modules can also be forwarded and shared, such as some packages that can be found on npm. However, since there are so many solutions and none of them are native to JavaScript, in order to use modules in browsers, some tools have emerged, such as Babel, Webpack, and Browserify.

Because there are many problems with the multi-file solution and the proposed solution is complex, developers are interested in introducing modular programming into the JavaScript language. Therefore, ECMAScript 2015 supports the use of JavaScript modules.

A module is a block of code that can provide functional functions for other modules, and can also rely on functions in other modules. The exports in the module is used to export and the imports is used to reference. Modules are useful because they allow developers to reuse code, they provide stable, consistent interfaces that many developers can use, and they do not pollute the global namespace.

Modules (sometimes called ECMAScript modules or ES modules) can now be used directly in JavaScript, and in the rest of this tutorial, you will explore how to use and implement them in your code.

Native JavaScript module

Modules in JavaScript use the import and export keywords:

Import: used to read code exported from another module.

Export: used to provide code to other modules.

To demonstrate how to use module import and export, use module export for functions in the functions.js file. Add the export keyword before each function, which allows the exported function to be used in other modules.

Add the following code to the file:

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;}

Now, in script.js, you can use import at the top of the functions.js file to import code from other modules.

Note: import must always be at the top of the file. In this example, you must also use a relative path (in this example,. /).

Add the following code to 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)

Notice that you import them by naming individual functions in curly braces.

To ensure that this code is loaded as a module rather than a regular script, add type = "module" to the script tag in index.html. Any code that uses import or export must use this property:

...

Refresh the page to reload the code, and the page is loaded using the module. Although browsers have high support for modules, we can check the support of different browsers through caniuse. Note that if you use the file as a straight chain of the local file, you will encounter this error:

OutputAccess 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.

Because of cross-domain resource sharing, the module must be used in a server environment and can be set up on the Internet either locally or through a managed service provider.

The difference between modules and regular scripts:

The module does not add anything to the global (window) scope.

The module is always in strict mode.

Referencing the same module multiple times in the same file will not work because the module will only be executed once.

The module needs to run in a server environment.

Modules are also often used with packaging tools such as Webpack to add browser support and some additional functionality, but they can also be used directly in browsers.

Next, we'll explore more ways to use import and export syntax.

Export by name

As mentioned earlier, using the export syntax allows values exported by name to be imported separately. For example, use the following simplified version of function.js:

Export function sum () {} export function difference () {}

This will allow you to import sum and difference by name using curly braces:

Import {sum, difference} from ". / functions.js"

You can also use aliases to rename the function to avoid naming conflicts in the same module. In this example, sum will be renamed to add,difference and renamed to subtract.

Import {sum as add, difference as subtract} from ". / functions.js"; add (1,2); / / 3

Calling add () here produces the result of the sum () function.

Using the * syntax, you can import the contents of an entire module into an object. In the following cases, sum and difference will become methods on the mathFunctions object.

Import * as mathFunctions from ". / functions.js"; mathFunctions.sum (1,2); / / 3 mathFunctions.difference (10,3); / / 7

Underlying types, function expressions, function definitions, asynchronous functions, classes, and instances of classes can also be exported, as long as they have identifiers:

/ / basic type 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 } / / Arrow function export async function getBooks () {} / / Class export class Book {constructor (name, author) {this.name = name; this.author = author;}} / / instance of class export const book = new Book ("Lord of the Rings", "J. R. R. Tolkien")

All of these exports can be successfully import. Another type of export we will explore in the next section-default export.

Default export

In the previous example, we made several named exports and imported them separately or as an object, and also tried to treat the export as an object, each as a method for that object. The module can also use the keyword default to include the default export. The default export is not imported using curly braces, but directly into a named identifier.

For example, add the following to the functions.js file:

Export default function sum (x, y) {return x + y;}

In the script.js file, you can import the default function as sum using the following command:

Import sum from ". / functions.js"; sum (1,2); / / 3

This is dangerous because there are no restrictions on the naming of default exports during the import process. In the following example, the default function is imported as difference, although it is actually a sum function:

Import difference from ". / functions.js"; difference (1,2); / / 3

Therefore, it is generally preferred to use named export. Unlike named exports, default exports do not require identifiers-- values of the underlying type or anonymous functions can be used as default exports. The following is an example of an object used as a default export:

Export default {name: "Lord of the Rings", author: "J. R. R. Tolkien",}

You can import it as book using the following command:

Import book from ". / functions.js"

Similarly, the following example shows the default export of the arrow function:

Export default () = > "This function is anonymous"

You can introduce the arrow function in script.js as follows:

Import anonymousFunction from ". / functions.js"

Named and default exports can be used at the same time, for example, in the following module, two named values and a default value are exported:

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

We can import these variables and default functions using the following code:

Import calculatePerimeter, {length, width} from ". / functions.js"; calculatePerimeter (length, width); / / 30

Both default and named values can now be used in script.

Modular programming practices can split code into separate components, improving code reuse and consistency, while protecting global namespaces from contamination. The modular interface can be implemented using the native JavaScript keywords import and export.

After reading the above, do you have any further understanding of how to import and export modules in JavaScript? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report