In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
How to understand the ES module in JavaScript? in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
Modules can be found in every programming language. It is a way to introduce the module functionality of another code into one code block. These modules are code with specific features developed by developers and can be reused elsewhere in the project. Modularity provides you with some benefits, such as code reusability and modularity.
If you have been using JavaScript to develop code, you will know that early JavaScript did not have such module functionality. Developers have to use HTML tags in order to load js files into their pages. It was only later that several module definition specifications began to emerge.
Module.export and require syntax used in CommonJS-Node.js
Asynchronous Module Definition (AMD)
Universal Module Definition (UMD)
ES Modules
First of all, let's take a look at why these modular definitions are needed.
Why do we need modularization?
Whenever you think about how programs work, what they do is variable management. It assigns values to variables, modifies variables, combines two variables together, and so on. But when the number of variables increases with the size of your application, you will find your code very troublesome to manage.
The solution to this problem is to consider only a few variables. The way JavaScript achieves this goal is called scope. Functions cannot access variables defined in other functions because of the way scope is defined in JavaScript. Although this makes your variables inaccessible to other functions, it gives rise to another problem-it is difficult to share variables between different functions. To solve this problem is to define them in the global scope.
Although this method can solve the problem, it is not recommended. Your script tags should be in the correct order, and you have to make sure that no one changes that order. If the order does change, your application will throw an error. This makes code management tricky. You never know what will destroy what. Any function can be accessed, so you don't know which functions depend on which scripts.
Another problem is that each part of the code in this global scope can be changed by other code. This will allow malicious and non-malicious code to access or even modify your global variables, whether malicious or not.
Therefore, modules need to be introduced to help overcome these problems.
How does modularization solve this problem gracefully?
Modules allow you to better organize and manage variables and functions. Typically, functions and variables that belong to the same function are placed in a module. This puts these variables in the module scope. Module scope can be used to share variables between functions in a module.
This also makes variables available to other modules as well. They can specify which variables, classes, or functions should be available to external modules. This is called export. Once you have an export, other modules can explicitly say that they depend on that variable, class, or function. Because of this clear relationship, you will know which modules will be destroyed if you delete a module.
Once you can import and export variables and functions, you can more easily split and decompose your code into blocks that can work independently. You can build your application later by using these modules, similar to building with Lego bricks.
In order to achieve this super useful functionality, several attempts have been made to add module functionality with JavaScript.
Existing modular system
CommonJS
CommonJS is always used by NodeJS. With Node, you will get the module.exports and require of CommonJS and can be used directly. However, unlike Node, browsers do not support CommonJS. In addition, CommonJS loads modules synchronously, so it is not the best solution for browsers. You can use packaging programs such as Webpack or Browserify to solve this problem.
/ / filename: bar.js / / dependencies var $= require ('jquery'); / / methods function myFunction () {}; / / exposed public method (single) module.exports = myFunction
Asynchronous Module Definition (AMD)
AMD was born out of a group of developers who don't like the direction of CommonJS. In fact, AMD split from CommonJS in the early stages of development. The main difference between AMD and CommonJS is that AMD loads modules asynchronously. This is very popular in browsers because startup time is critical to a good user experience.
/ / filename: bar.js define (['jquery'], function ($) {/ / methods function myFunction () {}; / / exposed public methods return myFunction;})
Since CommonJS and AMD are quite popular in their respective fields, a "generic" model is needed to support both styles. But UMD turned out to be messy and ugly. Although it does support both AMD and CommonJS, it also supports the old-fashioned "global" variable definition.
Universal Module Definition (UMD)
What is the ES module?
It is well known that JavaScript lacks a standard module definition specification. Therefore, a single, native module standard is proposed in ES6. The import and export instructions allow programs to import and export without running code, thus establishing a complete module dependency.
Its syntax format is simple and easy to use, and it is compatible with synchronous and asynchronous operation modes in browsers. The ES module is quickly available in browsers, but in Node.js, it is a bit difficult to come up with a solution that is backward compatible and can implement incremental upgrades. In Node.js, the native ES module is available for a long time after the experimental module flag.
Let's take the ES6 module as an example.
JavaScript
/ /-library.js-export const sqrt = Math.sqrt; export function square (x) {return x * x;} export function diagonal (x, y) {return sqrt (square (x) + square (y));} / /-main.js-import {square, diagonal} from 'library'; console.log (square (13)); / 169console.log (diagonal (12,5)) / / 13 const app = document.getElementById ("app"); app [XSS _ clean] = "Demo App for ES Modules"; const input = document.getElementById ("num"); input.addEventListener ("change", displaySquare); function displaySquare () {var sqrOutput = document.getElementById ("sqr"); sqrOutput.value = square (input.value);}
HTML
ES Modules Demo Input
Output
As shown in the figure above, in the HTML file, you need to specify the type= "module" in the script tag before the browser will treat it as an ECMAScript module.
Compatibility
For backward compatibility, you can include nomodule in the script tag (where the loaded JS file is a single packaged file). Browsers that support ES modules will know to ignore this. This solution works even in the oldest browsers. Willem's answer has explained this question very well.
In the above scenario, we will add such content to HTML.
If you are testing locally, you will need to run this on the server because you will encounter CORS problems. Please read more information here. The module is imported as an absolute or relative reference and must start with "/", ". /" or ". /".
Note:
Dynamic import
The latest version of ES2020 does have dynamic import capabilities. To dynamically import a module, the import keyword can be called as a function. When used in this way, it returns a promise.
Import ('/ modules/library.js'). Then (module) = > {/ / Do something with the module. }); / / or using await let module = await import ('/ modules/library.js')
For more information about the compatibility of es modules, please refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#import and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#export here.
Should you choose to use ES modules?
The ES module is the new standard for browsers. Can be used out of the box asynchronous module loading function, you can get faster startup time for better performance. Although you can use CommonJS with some additional plug-ins in your browser, it is strongly recommended that you switch to ES modules, as they are native modules in browsers.
ES native modules allow you to load a single module instead of a single packaged file. This is quite useful because it reduces the size of the loaded data. Browser compatibility with native modules is also important because it determines whether the native ES module will be implemented, or whether we will fall back to our mode, which will load a single file. One of the problems when you get a single bundle file is that as your application gets larger, the size of the bundle js file increases, affecting startup time and performance. You can avoid this problem by using code splitting, which is a feature of modern balers such as webpack. In some cases, however, we may choose a module baler, such as a webpack instead of an ES module. If you have assets such as CSS, images, fonts, or even data files such as XML or CSV, you may choose the webpack solution because webpack provides file packaging.
You should also consider the browser's support for HTTP2. When you use local modules, your browser will load them separately. But with the help of HTTP2, we can serve multiple requests at the same time with a single connection instead of sending multiple HTTP requests. According to CanIUse, 96.49% of browsers use HTTP2.
But when you develop an application, even the remaining 3.51% should be satisfied, so you may want to switch to webpack. This is because if you insist on using native ES modules, your application will need to send several HTTP requests to load each individual module.
In Node, the situation is completely different. Since this feature is still marked as experimental, you'd better stick with CommonJS. But you can still try the ES module. You can view the source code of the above example here. You can also view the live demo here.
This is the answer to the question about how to understand the ES module in JavaScript. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.