In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you the "sample analysis of Modules in ES6", which is easy to understand and clear. I hope it can help you solve your doubts. Let the editor lead you to study and study the "sample analysis of Modules in ES6".
Some simple background
Take-as-you-go is a mechanism that we all want to implement.
The same is true in Javascript, where a large Javascript program is divided into different parts, and which part is used will be taken.
NodeJS has had this capability for a long time, and later, more and more libraries and frameworks have modular capabilities, such as CommonJS, or implementations based on AMD models (such as RequireJs), as well as subsequent Webpack, Babel, and so on.
By 2015, a standard modular system has been born, which is what we are going to talk about today-the ES6 model system.
At first glance, it is not difficult to find that the model system of ES6 is very similar to the syntax of CommonJS. After all, the model system of ES6 comes from the era of CommonJS and is deeply influenced by CommonJS.
Look at a simple example, such as in CommonJs: (https://flaviocopes.com/commonjs/)
/ / file.jsmodule.exports = value;// introduces valueconst value = require ('file.js')
In ES6:
/ / const.jsexport const value = 'xxx';import {value} from' const.js'
The grammar is very similar.
Let's focus on import and export, and a few related features to learn more about ES6 Modules.
Benefits of modularization
There are two main benefits of modularization:
1. Avoid global variable pollution 2. Deal with dependencies effectively
With the evolution of the times, browsers have begun to support es6 import and export syntax natively.
Let's start with a simple example:
Import {addTextToBody} from'/ util.js'; addTextToBody ('Modules are pretty cool.'); / / util.js export function addTextToBody (text) {const p = document.createElement (' p'); p.textContent = text; document.body.appendChild (p);}
If you want to deal with events, it's the same thing. Look at a simple example:
Show Message// showImport.jsimport {showMessage} from'/ show.js'document.getElementById ('test'). Onclick = function () {showMessage ();} / show.jsexport function showMessage () {alert ("Hello World!")}
If you want to run this demo, pay attention to a simple service:
$http-server
Otherwise, you will see a CORS throw error.
As for the specific reasons and other details of the error, it is not the focus of this article. Interested can read the following link for details.
Https://jakearchibald.com/2017/es-modules-in-browsers/
Strict mode
Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
The use strict' statement is no stranger to us, and we used it a lot in the es5 era, usually at the top of the file, in order to disable the less friendly part of Javascript and help us write more rigorous code.
This feature is enabled by default in es6 syntax. If there is less strict code in the code, an error will be reported, such as:
Here are some of the parts I extracted from MDN that are disabled in strict mode:
Variables can't be left undeclaredFunction parameters must have unique names (or are considered syntax errors) with is forbiddenErrors are thrown on assignment to read-only propertiesOctal numbers like 00840 are syntax errorsAttempts to delete undeletable properties throw an errordelete prop is a syntax error, instead of assuming delete global [pro] eval doesn't introduce new variables into its surrounding scopeeval and arguments can't be bound or assigned toarguments doesn't magically track changes to method parametersarguments.callee throws a TypeError, no longer supportedarguments.caller throws a TypeError No longer supportedContext passed as this in method invocations is not "boxed" (forced) into becoming an ObjectNo longer able to use fn.caller and fn.arguments to access the JavaScript stackReserved words (e.g protected, static, interface, etc) cannot be bound
Several uses of exports
ES6 module only supports static export, you can only use export in the outermost scope of the module, not in conditional statements, nor in function scope.
In terms of classification superiors, there are three main types of exports:
1. Named Exports (Zero or more exports per module)
2. Default Exports (One per module)
3 、 Hybrid Exports
Exports Overview:
/ / Exporting inpidual featuresexport let name1, name2, … , nameN; / / also var, constexport let name1 =... , name2 =... ,... , nameN; / / also var, constexport function functionName () {...} export class ClassName {...} / / Export listexport {name1, name2,... , nameN}; / / Renaming exportsexport {variable1 as name1, variable2 as name2, … , nameN}; / / Exporting destructured assignments with renamingexport const {name1, name2: bar} = otactic hand / Default exportsexport default expression;export default function (…) {... } / / also class, function*export default function name1 (…) {... } / / also class, function*export {name1 as default, … }; / / Aggregating modulesexport * from … / / does not set the default exportexport * as name1 from … ; export {name1, name2, … , nameN} from... ; export {import1 as name1, import2 as name2, … , nameN} from... ; export {default} from …
Now I'll introduce some common uses of exports.
1. Named exports (export each function / variable)
Export with a name. Multiple functions are exported in this way, usually using tool-class function sets such as utils, tools, common, or site-wide unified variables, etc.
Just precede the variable or function with the export keyword.
/ /-lib.js-export const sqrt = Math.sqrt;export function square (x) {return x * x;} export function diag (x, y) {return sqrt (square (x) + square (y)); / /-main.js usage 1-import {square, diag} from 'lib';console.log (square (11)); / / 121console.log (diag (4,3)) / / 5 main.js main.js usage 2-import * as lib from 'lib';console.log (lib.square (11)); / / 121console.log (lib.diag (4,3)); / / 5
We can also export a list directly. For example, the above lib.js can be rewritten as:
/ /-lib.js-const sqrt = Math.sqrt;function square (x) {return x * x;} function add (x, y) {return x + y;} export {sqrt, square, add}
2. Default exports (export a default function / class)
This method is relatively simple and is generally used in a class file or a function file with a single function.
There can be only one export default default output in a module.
There are two main differences between export default and export:
Do not need to know the specific variable name of the export, import (import) do not need {}.
/ /-myFunc.js-export default function () {}; / /-main.js-import myFunc from 'myFunc';myFunc ()
Export a class
/ /-MyClass.js-class MyClass {} export default MyClass;//- Main.js-import MyClass from 'MyClass'
Note that {} is not required for export by default.
3. Mixed exports (mixed export)
Mixed derivation, that is, the combination of the first and second points above. The more common ones, such as Lodash, are all in this way.
/ /-lib.js-export var myVar =...; export let myVar =...; export const MY_CONST =...; export function myFunc () {/ /...} export function* myGeneratorFunc () {/ /...} export default class MyClass {/ /...} / /-main.js-import MyClass, {myFunc} from 'lib'
Another example is lodash:
/ /-lodash.js-export default function (obj) {/ /...}; export function each (obj, iterator, context) {/ /...} export {each as forEach}; / /-main.js-import _, {forEach} from 'lodash'
4. Re-exporting (alias export)
In general, the variable output by export is the name defined in the original file, but you can also use the as keyword to specify an alias, which is generally done to simplify or semantic the function name of export.
/ /-lib.js-export function getUserName () {/ /...}; export function setName () {/ /...}; / / output aliases. In import, you can use both the original function name and alias export {getName as get, / / allow you to output getName as getNameV2, setName as set} twice with different names
5. Module Redirects (export of transit module)
Sometimes, in order to prevent the upper module from importing too many modules, we may use the underlying module as a transit and directly export the contents of another module as follows:
/ /-myFunc.js-export default function () {...}; / /-lib.js-export * from 'myFunc';export function each () {...}; / /-main.js-import myFunc, {each} from' lib' Export only supports static export in the outermost layer, and only supports exporting variables, functions, and classes. The following uses are incorrect. Export usage of `error `: / / directly output the value of the variable export 'Mark';// without brackets or without default// when there is only one derived number, you need to add default, or use brackets var name =' Mark';export name;//export do not output the variable in the block scope function () {var name = 'Mark';export {name};}
Several uses of import
The usage of import corresponds to export, but import supports both static import and dynamic import, while dynamic import supports later and less compatible.
Let me summarize the basic usage of import:
1. Import All things
When export has multiple functions or variables, such as the first point of export in the article, you can use the * as keyword to export all functions and variables, while the name followed by as is used as the namespace of the module.
/ / all functions and variables import * as lib from 'lib';// of lib are called using lib as the namespace, similar to object console.log (lib.square (11)); / / 121
2. Import a single/multiple export from a module
Import single or multiple functions from a module file, unlike * as namepage, which is imported on demand. Examples are as follows:
/ / Import square and diag functions import {square, diag} from 'lib';// only import square one function import {square} from' lib';// import default module import _ from 'lodash';// import default module and single function, this is mainly to simplify the call to import _, {each} from' lodash' of a single function
3. Rename multiple exports during import
Like export, aliases can be set with the as keyword. When the names of the two classes of import are the same, you can use as to reset the name of the import module, or you can use as to simplify the name. For example:
/ / simplify the function name import {reallyReallyLongModuleExportName as shortName, anotherLongModuleName as short} from'/ modules/my-module.js';// with as to avoid duplicate names import {lib as UserLib} from "alib"; import {lib as GlobalLib} from "blib"
4. Import a module for its side effects only
Sometimes we just want to import a module, such as a style, or a class library.
/ / Import style import'. / index.less';// Import Class Library import 'lodash'
5. Dynamic Imports
Static import downloads all module resources when it is first loaded.
When we are actually developing, sometimes we need dynamic import (dynamic import).
For example, click a tab to load some new modules:
/ / when dynamic import, a promiseimport ('lodash'). Then (lodash) = > {/ / Do something with lodash is returned. }); / / the above sentence is actually equivalent to const lodash = await import ('lodash')
New usage of es7:
Async function run () {const myModule = await import ('. / myModule.js'); const {export1, export2} = await import ('. / myModule.js'); const [module1, module2, module3] = await Promise.all ([import ('. / module1.js'), import ('. / module2.js'), import ('. / module3.js'),]);} run () The above is all the content of the article "sample Analysis of Modules in ES6". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.