ES6 Module Usage Details of new features, es6module

Source: Internet
Author: User
Tags es6 class

ES6 Module Usage Details of new features, es6module

This article describes how to use the Module of the new features of ES6. We will share this with you for your reference. The details are as follows:

I. Module Introduction

ES6 Class is only the syntactic sugar of object-oriented programming. It upgrades the prototype chain inheritance of ES5 constructor and does not solve the modularization problem. The Module function is proposed to solve this problem.

In history, Javascript has never had a module system, so it is impossible to split a large program into small files that depend on each other, and then assemble it in a simple way. This feature is available in other languages.

Before ES6, the community developed some module loading solutions, mainly including CommonJS and AMD. The former is used for servers, and the latter is used for browsers. ES6 implements module functions in terms of language specifications and is quite simple to implement. It can completely replace the existing CommonJS and AMD specifications and become a common module solution for browsers and servers.

The design philosophy of the ES6 module is to make it as static as possible, so that the dependencies of the module can be determined during compilation (this kind of loading is called "compile-time loading"), as well as input and output variables. The CommonJS and AMD modules can only determine these items at runtime.

The syntax for the browser to use the ES6 module is as follows.

<script type="module" src="fs.js"></script>

The code above inserts a module fs. js into the webpage. Because the type attribute is set to module, the browser knows that this is an ES6 module.

// ES6 loading module import {stat, exists, readFile} from 'fs ';

The code above loads a Module through import and loads some of the methods.

Ii. import and export

The module function consists of two Commands: export and import. The export command is used to specify the external interface of the module. The import command is used to enter the functions provided by other modules.

A module is an independent file. All variables in the file cannot be obtained from the outside. If you want external users to read a variable in the module, you must use the export keyword to output the variable. The following is a JS file that uses the export command to output variables.

// profile.jsexport var firstName = 'Michael';export var lastName = 'Jackson';export var year = 1958;

In addition to writing export, there is another method. (This is recommended, because we can see at a glance what variables are output at the end of the script .)

// profile.jsvar firstName = 'Michael';var lastName = 'Jackson';var year = 1958;export {firstName, lastName, year};

In addition to the output variables, the export command can also output functions or classes ). Normally, the variable output by the export is the original name, but can be renamed using the as keyword.

function v1() { ... }function v2() { ... }export {  v1 as streamV1,  v2 as streamV2,  v2 as streamLatestVersion};

After the external interface of the module is defined using the export command, other JS files can be loaded using the import command ).

// main.jsimport {firstName, lastName, year} from './profile';function setName(element) {  element.textContent = firstName + ' ' + lastName;}

The import command of the code above is used to load the profile. js file and input variables from it. The import command accepts an object (in braces), which specifies the variable name to be imported from other modules. The variable name in the braces must be the same as the name of the external interface of the imported module (profile. js.

If you want to rename the input variable, use the as keyword in the import command to rename the input variable.

import { lastName as surname } from './profile';

The import command can be upgraded to the header of the entire module. First, execute the command.

foo();import { foo } from 'my_module';

Iii. Overall module Loading

In addition to loading an output value, you can also use the overall loading function, that is, using an asterisk (*) to specify an object. All output values are loaded on this object.

There is a circle. js file that outputs two methods, area and circumference.

Now, load this module.

// Main. jsimport {area, circumference} from '. /circle '; console. log ('Circular area: '+ area (4); console. log ('circle perimeter: '+ circumference (14 ));

The above statement specifies the method to be loaded one by one. The overall loading statement is as follows.

Import * as circle from '. /circle '; console. log ('circle area: '+ circle. area (4); console. log ('circle perimeter: '+ circle. circumference (14 ));

Iv. export default

To make it easier for users to load modules without reading the document, they need to use the export default command to specify the default output for the module.

// export-default.jsexport default function () {  console.log('foo');}

The code above is a module File export-default.js, and its default output is a function.

When other modules load the module, the import command can specify any name for the anonymous function.

// import-default.jsimport customName from './export-default';customName(); // 'foo'

Note that braces are not used after the import command.

In essence, export default is to output a variable or method called default, and then the system allows you to take any name for it. It cannot be followed by a variable declaration statement.

// Correct var a = 1; export default a; // error export default var a = 1;

V. essence of ES6 module Loading

The loading mechanism of the ES6 module is completely different from that of the CommonJS module. The CommonJS module outputs a copy of a value, while the ES6 module outputs a reference of the value.

The CommonJS module outputs a copy of the output value, that is, once a value is output, changes within the module will not affect this value. See the following example of the module File lib. js.

// lib.jsvar counter = 3;function incCounter() { counter++;}module.exports = { counter: counter, incCounter: incCounter,};

The code above outputs the internal variable counter and the internal method of rewriting this variable incCounter. Then, load the module in main. js.

// main.jsvar mod = require('./lib');console.log(mod.counter); // 3mod.incCounter();console.log(mod.counter); // 3

The code above shows that after the lib. js module is loaded, its internal changes will not affect the output mod. counter. This is because mod. counter is a value of the original type and will be cached. The internal variable value can be obtained only when a function is written.

// lib.jsvar counter = 3;function incCounter() { counter++;}module.exports = { get counter() {  return counter }, incCounter: incCounter,};

In the code above, the counter attribute output is actually a calculator function. Now execute main. js to correctly read the changes to the internal variable counter.

The operating mechanism of the ES6 module is different from that of CommonJS. When the module loads the command import, it does not execute the module, but only generates a dynamic read-only reference. When it is really necessary to use it, go to the module to take the value. In other words, ES6 input is a bit like a Unix System "symbolic connection", and the original value has changed, the import value also changes. Therefore, the ES6 module is a dynamic reference and does not cache values. The variables in the module are bound to the module where they are located.

Let's look at the above example.

// lib.jsexport let counter = 3;export function incCounter() { counter++;}// main.jsimport { counter, incCounter } from './lib';console.log(counter); // 3incCounter();console.log(counter); // 4

The code above demonstrates that the counter variable entered by the ES6 module is active and fully reflects the changes within the lib. js module.

Because the module variable entered by ES6 is only a "symbolic connection", this variable is read-only and an error is returned when you assign a value to it.

// lib.jsexport let obj = {};// main.jsimport { obj } from './lib';obj.prop = 123; // OKobj = {}; // TypeError

In the above Code, main. js inputs the variable obj from lib. js. You can add an attribute to obj, But if you assign a value again, an error is returned. The variable obj points to a read-only address and cannot be assigned a value again. This is like main. js creates a const variable named obj.

Finally, the export outputs the same value through the interface. Different scripts load this interface to get the same instance.

// mod.jsfunction C() { this.sum = 0; this.add = function () {  this.sum += 1; }; this.show = function () {  console.log(this.sum); };}export let c = new C();

The above script mod. js outputs a C instance. Load this module using different scripts to get the same instance.

// x.jsimport {c} from './mod';c.add();// y.jsimport {c} from './mod';c.show();// main.jsimport './x';import './y';

Execute main. js and Output 1. This proves that x. js and y. js load the same instance of C.

I hope this article will help you design the ECMAscript program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.