In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
JavaScript introduction module of the history of what is, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.
As our application gets bigger and bigger, we want to split it into multiple files, called "module". A module can contain classes or libraries for a specific purpose.
For a long time, JavaScript had no language-level module syntax. This is not a problem, because the initial script is small and simple, so there is no need to modularize it.
But eventually the script became more and more complex, so the community invented many ways to organize the code into modules, using special libraries to load modules on demand.
List some (for historical reasons):
AMD, one of the oldest modular systems, was originally implemented by the require.js library.
CommonJS-A modular system created for the Node.js server.
UMD, another module system, is recommended as a general module system, which is compatible with both AMD and CommonJS.
Now, they are slowly becoming part of history, but we can still find them in the old scripts.
Language-level module systems appeared in the standard (ES6) in 2015 and have evolved since then and are now supported by all major browsers and Node.js. Therefore, we will learn about modern JavaScript modules (module) from now on.
What is a module?
A module is a file. A script is a module. It's that simple.
Modules can be loaded with each other, and special instructions export and import can be used to exchange functions, calling functions of one module from another module:
The export keyword marks variables and functions that can be accessed from outside the current module.
The import keyword allows you to import functionality from other modules.
For example, we have a sayHi.js file that exports a function:
/ / sayHi.js export function sayHi (user) {alert (`Hello, ${user}! `);}
…… Then another file may import and use this function:
/ / main.js import {sayHi} from'. / sayHi.js'; alert (sayHi); / / function... SayHi ('John'); / / Hello, John!
The import instruction loads the module relative to the path of the current file. / sayHi.js and assigns (assign) the imported function sayHi to the corresponding variable.
Let's run this example in a browser.
Because modules support special keywords and functions, we must tell the browser by using attribute that this script should be treated as a module (module).
Like this:
Import {sayHi} from'. / say.js'; document.body [XSS _ clean] = sayHi ('John')
The browser automatically acquires and parses (evaluate) the imported module (and can analyze the module's import, if necessary), and then runs the script.
The module works only through HTTP (s), not in local files
If you try to open a web page locally through the file:// protocol, you will find that the import/export command does not work. You can use a local Web server, such as static-server, or use the editor's "real-time server" feature, such as VS Code's Live Server Extension, to test the module.
Second, the core function of the module
How is a module different from a "regular" script?
Here are some core features that work for both browser and server-side JavaScript.
Always use "use strict"
Modules always use use strict by default, for example, assigning a value to an undeclared variable will result in an error.
A = 5; / / error
IV. Module-level scope
Each module has its own top-level top-level scope. In other words, the top-level scoped variables and functions in one module are not visible in other scripts.
In the following example, we imported two scripts where hello.js tried to use the variable user declared in user.js and failed:
Modules expect to export what they want to be accessed externally and import what they need.
So instead of relying on global variables, we should import user.js into hello.js and get the functionality we need from it.
This is the correct variant:
Import {user} from'. / user.js'; document.body [XSS _ clean] = user; / / John
In browsers, each has a separate top-level scope (error information can be seen in the browser console).
/ / variables are only visible in this module script let user = "John"; alert (user); / / Error: user is not defined
If we really need to create a global variable for window-level, we can explicitly assign it to window and access it as window.user. But it requires you to have a good enough reason, otherwise don't do it.
The module code is parsed only on the first import
If the same module is imported to multiple other locations, its code will only be executed on the first import, and then the contents of the export (export) will be provided to all imports (importer).
This has a very important impact. Let's look at this through an example:
First, if executing code in a module causes side effects (side-effect), such as displaying a message, importing it multiple times will only trigger the display once-that is, the first time:
/ / alert.js
Alert ("Module is evaluated!")
/ / Import the same module / / 1.js import `. / alert.js` in different files; / / Module is evaluated! / / 2.js import`. / alert.js`; / / (nothing is displayed)
In actual development, the top-level module code is mainly used for initialization, the creation of internal data structures, and if we want something to be reused-please export it.
The following is an example of an advanced point.
Let's assume that a module exports an object:
/ / admin.js export let admin = {name: "John"}
If the module is imported into multiple files, the module is parsed only the first time it is imported, creates an admin object, and then passes it in to all imports.
All imports get only a unique admin object:
/ / 1.js import {admin} from'. / admin.js'; admin.name = "Pete"; / / 2.js import {admin} from'. / admin.js'; alert (admin.name); / / Pete / / 1.js and 2.js import the same object / / changes made to the object in 1.js and are also visible in 2.js
So, let's repeat-- the module is only executed once. Generate an export, and it is shared with all imports to it, so if an admin object is modified somewhere, other modules can see the change as well.
This behavior allows us to set up the module on the first import. We only need to set its properties once, and then we can use them directly in further imports.
For example, the following admin.js module may provide specific functionality, but you want the credential to enter the admin object from the outside:
/ / admin.js export let admin = {}; export function sayHi () {alert (`Ready to serve, ${admin.name}! `);}
In init.js, our first script for APP, set up admin.name. It is now visible at every location, including calls within the admin.js.
/ / init.js import {admin} from'. / admin.js'; admin.name = "Pete"
Another module can also see admin.name:
/ / other.js import {admin, sayHi} from'. / admin.js'; alert (admin.name); / / Pete sayHi (); / / Ready to serve, Pete!
VI. Import.meta
The import.meta object contains information about the current module.
Its content depends on its environment. In the browser environment, it contains the URL of the current script or, if it is in HTML, the URL of the current page.
Alert (import.meta.url); / / the URL of the script (or, for embedded scripts, the URL of the current HTML page)
In a module, "this" is undefined
This is a small feature, but for completeness, we should mention it.
In one module, the top-level this is undefined.
Comparing it with non-modular scripts shows that the top-level this of non-modular scripts is a global object:
Alert (this); / / window alert (this); / / undefined
VIII. Browser-specific functions
Scripts with the type= "module" logo have some browser-specific differences compared to regular scripts.
If you are reading it for the first time or you are not going to use JavaScript in your browser, you can skip this section.
IX. Module scripts are delayed
Module scripts are always delayed, as the defer feature (described in the script: async,defer chapter) has the same impact on external and inline scripts (inline script).
In other words:
Downloading external module scripts does not block HTML processing; they are loaded in parallel with other resources.
Module scripts wait until the HTML documents are fully ready (even if they are small and load faster than HTML) before running.
Maintain the relative order of scripts: the scripts at the top of the document are executed first.
One side effect of this is that module scripts always "see" fully loaded HTML pages, including the HTML elements below them.
For example:
Alert (typeof button); / / object: the script can "see" the following button / / because the module is delayed (deferred, so the module script will not run until the entire page has been loaded compared to the following regular script: alert (typeof button) / / button is undefined, the script cannot see the following elements / / the regular script will run immediately, and the regular script will run Button before processing the rest of the page
Please note that the second script above actually runs before the previous one! So we'll see undefined first, then object.
This is because the module script is delayed, so it will not be executed until the HTML document is processed. The regular script runs immediately, so we will see the output of the regular script first.
When using module scripts, we should know that the HTML page is displayed when it is loaded, and the JavaScript module is not executed until the HTML page is loaded, so users may see the page before the JavaScript application is ready. Some features may not be in use at that time. We should place a "load indicator (loading indicator)", otherwise, make sure that it does not confuse the user.
10. Async is suitable for inline scripts (inline script)
For non-modular scripts, the async feature (attribute) applies only to external scripts. Asynchronous scripts are run as soon as they are ready, independent of other scripts or HTML documents.
For module scripts, it also applies to inline scripts.
For example, the following inline script has the async feature, so it doesn't wait for anything.
It performs the import (fetch. / analytics.js) and runs when the import is ready to complete, even if the HTML document is not yet complete or other scripts are still waiting to be processed.
This is great for features that don't rely on anything else, such as counters, advertisements, document-level event listeners.
Import {counter} from'. / analytics.js'; counter.count ()
11. External script
External scripts (external script) with type= "module" differ in two ways:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
External scripts with the same src are run only once:
External scripts obtained from another source (such as another Web site) require CORS header, as we talked about in the chapter Fetch: cross-source requests. In other words, if a module script is obtained from another source, the remote server must provide a header Access-Control-Allow-Origin that indicates that it is allowed to be obtained. Doing this by default ensures better security.
12. Naked modules are not allowed ("bare" module)
In the browser, the import must give a relative or absolute URL path. A module without any path is called a "bare" module. This module is not allowed in import.
For example, the following import is invalid:
Import {sayHi} from 'sayHi'; / / Error, the "naked" module / / module must have a path, such as'. / sayHi.js' or any other path
Some environments, such as Node.js or packaging tools (bundle tool), allow naked modules without any path because they have their own methods and hook to find modules to fine-tune them. However, browsers do not support naked modules.
XIII. Compatibility, "nomodule"
Old browsers didn't understand type= "module". Scripts of unknown types are ignored. For this, we can use the nomodule feature to provide a backup:
Alert ("Runs in modern browsers"); alert ("Modern browsers know both type=module and nomodule, so skip this") alert ("Old browsers ignore script with unknown type=module, but execute this.")
XIV. Build tools
In actual development, browser modules are rarely used in "raw" form. Typically, we use special tools, such as Webpack, to package them together and deploy them to a server in a production environment.
One of the benefits of using packaging tools is that they have more control over how modules are parsed, allowing us to use naked modules and more features, such as CSS/HTML modules.
The build tool does the following:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Start with a "master" module that you plan to put in HTML.
Analyze its dependency: its import, as well as its import and so on.
Build a file (or multiple files, which is adjustable) with all the modules, and replace the native import call with a packaged function (bundler function) to make it work. "special" module types such as HTML/CSS modules are also supported.
During processing, other transformations and optimizations may be applied: removing inaccessible code. Delete unused exports ("tree-shaking"). Delete development-specific statements like console and debugger. You can use Babel to convert cutting-edge modern JavaScript syntax into an old JavaScript syntax with similar functionality. Compress the resulting file (remove spaces, replace variables with short names, etc.).
If we use the packaging tool, the script is packaged into a single file (or several files), and the import/export statements in these scripts are replaced with special packaging functions (bundler function). Therefore, the final packaged script does not contain any import/export, nor does it require a type= "module", which we can put into the regular:
In other words, native modules are also available. So, we won't use Webpack here: you can configure it later.
15. Summary
Here is a summary of the core concepts of the module:
A module is a file. The browser needs to be used for import/export to work. The module differs from regular scripts in a few ways: the default is deferred. Async can be used for inline scripts. CORS header is required to load external scripts from another source (domain / protocol / port). Duplicate external scripts will be ignored
The module has its own local top-level scope and can be exchanged through import/export.
Modules always use use strict.
The module code is executed only once. The export is created only once and is then shared between imports.
When we use modules, each module implements specific functions and exports them. Then we use import to import it directly to where we need it. The browser automatically loads and parses the script.
In a production environment, developers often use packaging tools such as Webpack to package modules together for performance and other reasons.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, 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.
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.