Comprehensive analysis of the ECMAScript 6 module system

Source: Internet
Author: User

Tudou Sync update : http://www.tudou.com/plcover/VHNh6ZopQ4E/ 
use HTML to create a Mac OS App video tutorial. QQ Group: (1) app practice 434558944 (2) App learning communication 452180823 Baidu Network Disk synchronization:/HTTP pan.baidu.com/s/1jg1q58m sharing [Chinese documentary] Internet era Http://pan.baidu.com/s/1qWkJfcS

Modularity is common in any large application. The ES6 module provides this feature for JavaScript, and provides many options for exporting and introducing objects to these modules. Ravi Kiran in the Modules in ECMAScript 6 (ES6) article mainly discusses the ES6 module system. The following is a brief translation of the article:

No matter what programming language is used to develop large-scale applications, the most critical feature is the modularity of the code. This concept in different programming languages have different naming, in C for the header file, C + + and C # for the namespace, Java for the package, the name is not the same but solve the same problem. As mentioned in the first article in the ECMAScript 6–new language improvements in JavaScript series, the original JavaScript was not used to write large amounts of code, such as creating large frames, app apps, and so on. Just as we write a lot of code because JavaScript lacks support for modules, open source developers come up with a number of criteria, such as the Commonejs module model, asynchronous module definition (AMD), and some libraries for modularity. Over the past few years, these libraries have gained extensive attention and have been successfully applied to multiple enterprise-scale applications.

ES6 provides module features for JavaScript. It will take some time for the browser to implement this feature because they must define a method to dynamically download the file. Before the browser supports this feature, we can use compilers such as Traceur, 6to5, ES6 module loader, and other transcoding converters that allow ES6 modules to be converted to ES5.

Current status of JavaScript module systems

COMMONJS Module System

Commonjs is a team of open source developers who implement APIs and develop research and development practices around JavaScript. The team proposed a JavaScript module specification. Each file can be treated as a module, and each file has access to two objects: require and export. The require is used to receive the string (module name) and returns the object that the module outputs. The export object is used to derive methods and variables for the module. The Require method returns the Export object. The module is loaded synchronously. The server-side JavaScript engine, node. js, is the module system.

Asynchronous module definition (AMD)

AMD is a modular system that loads dependent modules asynchronously. If the modules are in different files, they will be loaded with XHR. A module will be executed only after the module one by one that it depends on is loaded. The AMD module must be a function and passed into the Define function as a parameter. The return value of the function is transferred to all dependent modules, and the obtained return value is passed as a parameter to the module method. AMD is implemented in the Require.js library.

Typescript Module

TypeScript, as a superset of JavaScript, also provides a modular system. When it is compiled, it starts using JavaScript module mode. The Typescript module uses the module keyword definition, and any objects that are exported must be defined using the Export keyword. The Import keyword is used to load other modules into the module and capture the exported objects of that module. The typescript module is loaded synchronously.

ES6 Module System

The ES6 module system is inspired by the existing modular system, which has the following features:

    1. Export the object using an export keyword. This keyword can be used indefinitely;
    2. Use the Import keyword to import other modules into a module. It can be used to import any number of modules;
    3. Supports asynchronous loading of modules;
    4. Provides programmatic support for loading modules.

Next, let's look at each feature through a specific programming approach.

Exporting objects

In an existing module system, each JavaScript code file is a module in ES6. The module outputs objects only if the objects in the module need to be called externally, and the rest is the private object of the module. This process encapsulates the details and exports only the necessary functionality.

To derive the object from the module, ES6 provides us with a different approach, as discussed below.

Inline export

The objects in the ES6 module can be exported in the declaration in which they were created. Export can be used countless times in a module, and all objects will be exported together. Take a look at the following example:

Exportclass employee{Constructor (ID, name, DOB) {this.id = ID; this.name=name; this.dob= dob;} Getage () {return (new Date ()). GetYear ()- This.dob.getYear (); }}export function getemployee  (ID, name, DOB) {return new Employee (ID, name, DOB);} var emp = new Employee (1,  " Rina ", new Date (1987, 1, 22)) ; 

The module in the case exports two objects: Employee class, GetEmployee function. Because the object EMP is not exported, it is still private to the module.

Export a group of objects

Although inline export is very effective, it is difficult to work in large-scale modules because we may not be able to trace the objects that are being derived from the module. In this case, a better approach would be to export the declaration separately at the end of the module to export all the objects in the module.

Rewrite the module in the previous case with a separate export declaration, with the following results:

class employee{Constructor (ID, name, DOB) {this.id    = ID;    this.name=name; this.dob= dob;} Getage () {return (new Date ()). GetYear ()- This.dob.getYear (); }}function getemployee (ID , name, DOB) {return new Employee (ID, name, DOB);} var x = new Employee (1, new Date (1987, 1, 22)); Export {Employee, getemployee};             

Renaming an object is also possible when exporting. As the following example shows, the employee name is changed to associate when exporting, and the function GetEmployee renamed to Getassociate.

Export {    as Employee, as    getemployee  }; 

Default Export

Using the keyword default, you can label an object as the default object export. The default keyword can only be used once in each module. It can be used for inline export as well as for a set of object export declarations.

The following example shows the use of default in a group export statement:

Default {    Employee,    getemployee};

Import Module

Existing modules can be imported into other modules using the keyword import. A module can be imported into any number of modules. The following shows the different ways to import modules.

No object Import

If the module contains some logic to execute, and no objects are exported, such objects can also be imported into another module. As shown in the following example:

'./module1.js ';

Import Default Objects

The object is exported using the default export, which is assigned directly to a reference in the import declaration, such as "D" in the following example.

'./module1.js ';

To import named objects

As discussed above, a module can export many named objects. If another module wants to import these named objects, they need to be listed in the import declaration. As an example:

'./module1.js ';

Of course, you can also import default objects and named objects in the same declaration. In this case, the default object must define an alias, as in the following example.

Import {'./module1.js ';

Import All Objects

In these cases, only the objects listed in the import declaration are imported and used, while others cannot be used in the import module. This, of course, requires the user to know which objects can be exported and exploited. If a module exports a large number of objects and another module wants to introduce all the exported objects, it must use the following declaration:

'./module1.js ';

AllFromModule1 This alias will point to all objects exported from Module1. In the import module, they can be accessed as properties.

Programmable on-demand import

If you want to load the required modules based on certain conditions or when an event occurs, you can do so by using the programmable API (programmatic API) of the load module. Using the System.import method, you can set the load module according to the program. This is an asynchronous method and returns promise.

The syntax examples for this method are as follows:

System.import ('./module1.js ')    . Then (function (Module1) {        //use module1    function (e) {        //handle Error});    

If the module is successfully loaded and the exported module is successfully passed to the callback function, promise will pass. The promise will fail if the module name is incorrect or the module fails due to network latency.

ES6 Module Usage Status

So far, all browsers have not been able to support the ES6 module naturally, so we need to use the translator (Transpiler) to convert the code to ES5 before the browser loads. Until now, I have been using traceur as my translator, and it is recommended that you use the same tool to translate the module code into a browser-readable code. Let's look at several different ways to compile the ES6 module.

Dynamically compiling ES6 modules with Traceur

When the browser loads the script, we can dynamically compile the ES6 module using Traceur's client library. With this method, you run the module without running any commands. All we have to do is load the Traceur library on the page and add the code script to run Webpagetranscoder.

<script>    new traceur. Webpagetranscoder (Document.location.href). Run (); </script>    

Now we can import any one of the ES6 files by specifying the type as a module within the script tag.

<type="module" > "    ./modules/import1.js";  </script>     

Any script tags of type specified as modules will be fetched and processed by the ES6 client library. The import statement in the above code block sends an AJAX request, captures the corresponding JavaScript file, and loads it. If another module is referenced inside the module, a separate AJAX request is issued to load the file corresponding to the reference module.

Compiling the ES6 module with the traceur command

Use the traceur command to compile the ES6 module into an AMD or COMMONJS module. There are two major advantages to this approach.

    1. The module completes the compilation, the browser does not need to perform additional actions;
    2. If an application has been built using ES5 and AMD (or COMMONJS) module systems, the other half of the program can use ES6 and be compiled into any of these module systems instead of immediately compiling the entire application into ES6.

In order to use the compiled AMD/COMMONJS module, we need to include a library that supports the module system. I personally prefer AMD, so I'll introduce it here. The steps of the Commonjs module are similar to this one.

The following command is used to compile the folders containing the ES6 modules into AMD and store them in a separate folder:

--dir Modules Es5modules--MODULES=AMD

With COMMONJS, you need to use COMMONJS instead of modules in the command above.

Here, modules refers to the folder containing the ES6, es5modules refers to the output directory. If you view any files under the Es5modules folder, you will see the AMD definition block. Require.js supports AMD, so we can use script to introduce require.js in an HTML page, and to specify the start file with the Data-main property, as follows:

<src=data-main="Es5modules/import2.js" ></script>    

Compiling ES6 modules with Traceur Grunt task

Compiling a module with commands is tiring and error-prone. We can use Grunt-traceur to automate the compilation process. At this point, you need to install the NPM package.

NPM Intall Grunt-traceur–save

The grunt task requires the same data as the data provided to the command. Here are some of the tasks ' configurations:

{  options: {    files:' modules ', src: [' Es5modules '}]}}    

Now you can use the following command in the console to run the grunt task above:

Grunt Traceur

As you can see, it has the same effect as the command we use.

Conclusion

In any large application, modularity is necessary. The ES6 module provides this feature for JavaScript, which provides many choices for exporting and importing objects. I'm looking forward to the day when the feature is supported by the browser, so that we can create and load JavaScript modules without having to load any third-party libraries. The current popular client mv* framework Angular.js uses ES6 modularity in its 2.0 version (currently under development).

Let's start using the modular system to make our code more organized and readable.

Comprehensive analysis of the ECMAScript 6 module system

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.