New Features of ES6: Use export and import to implement modular explanation, es6export

Source: Internet
Author: User

New Features of ES6: Use export and import to implement modular explanation, es6export

Before ES6, the front end implemented modularization using RequireJS or seaJS. requireJS is a modular Library Based on AMD specifications, while seaJS is a modular Library Based on CMD specifications, both of them are intended to promote the front-end modular tools. For more information about the differences between AMD and CMD, refer to the following links;

Now ES6 comes with modularization, which is the first time JS supports modules. After a long time, we can directly use import and export to import and export modules in the browser, A js file represents a js module;

Modern browsers have different levels of support for modules. Currently, babelJS is used, or Traceur converts ES6 code into js Code compatible with ES5;

ES6 modular basic rules or features:

ES6 modular basic rules or features, please add:

1: Each module is loaded only once, and each JS is executed only once. If you load files in the same directory next time, you can directly read them from the memory. A module is a Singleton, or an object;

2: variables declared in each module are local variables and do not pollute the global scope;

3: internal variables or functions of the module can be exported through export;

4: one module can be imported into another module.

Run the following code:

// Lib. js // export constant export const sqrt = Math. sqrt; // export function square (x) {return x * x;} // export function diag (x, y) {return sqrt (square (x) + square (y);} // main. jsimport {square, diag} from '. /lib '; console. log (square (11); // 121console. log (diag (4, 3); // 5

The basic syntax of Several import and export types is listed below:

Method 1:

In the lib. js file, use the export {interface} to export the interface. The interface name in braces is the variable defined above, and the import and export correspond to each other;

Run the following code:

// Lib. js file let bar = "stringBar"; let foo = "stringFoo"; let fn0 = function () {console. log ("fn0") ;}; let fn1 = function () {console. log ("fn1") ;}; export {bar, foo, fn0, fn1} // main. js File import {bar, foo, fn0, fn1} from ". /lib "; console. log (bar + "_" + foo); fn0 (); fn1 ();

Method 2:

When using the export interface, we can use XX as YY to change the name of the exported interface, for example, closureFn as sayingFn. If we change the names of these interfaces to what we can do without reading the document:

Run the following code:

// Lib. js file let fn0 = function () {console. log ("fn0") ;}; let obj0 ={} export {fn0 as foo, obj0 as bar}; // main. js File import {foo, bar} from ". /lib "; foo (); console. log (bar );

Method 3:

This method defines the export function directly in the export, or the variable:

Run the following code:

// Lib. js File export let foo = () => {console. log ("fnFoo"); return "foo"}, bar = "stringBar"; // main. js File import {foo, bar} from ". /lib "; console. log (foo (); console. log (bar );

Method 4:

You do not need to know the variable name for this export method. Instead, you can directly export the developed interface to the export;

If a js module file has only one function, you can use export default to export the file;

Run the following code:

//lib.jsexport default "string";//main.jsimport defaultString from "./lib";console.log(defaultString);

Method 5:

The export can also export functions by default. During import, the name can be written as needed, because the default Interface of each module is one:

Run the following code:

//lib.jslet fn = () => "string";export {fn as default};//main.jsimport defaultFn from "./lib";console.log(defaultFn());

Method 6:

Use the wildcard * to re-export the interfaces of other modules (in fact, it is to repost the article without specifying the source );

Run the following code:

// Lib. jsexport * from ". /other "; // if you only want to export some interfaces, you only need to list the interface names/export {foo, fnFoo} from ". /other "; // other. jsexport let foo = "stringFoo", fnFoo = function () {console. log ("fnFoo")}; // main. jsimport {foo, fnFoo} from ". /lib "; console. log (foo); console. log (fnFoo ());

Others: ES6 import and export provides a considerable number of import and export syntaxes;

During import, you can use the wildcard * to import external modules:

Run the following code:

import * as obj from "./lib";console.log(obj);

All imported ES6 modules are references:

Every imported js module is active, every access to the module variables or functions are the latest, this is one of the differences between the native ES6 module and AMD and CMD, the following code modified from the http://exploringjs.com/es6/ch_modules.html#_imports-are-read-only-views-on-exports

Run the following code:

//lib.jsexport let counter = 3;export function incCounter() {  counter++;}export function setCounter(value) {  counter = value;}//main.jsimport { counter, incCounter ,setCounter} from './lib';// The imported value `counter` is liveconsole.log(counter); // 3incCounter();console.log(counter); // 4setCounter(0);console.log(counter); // 0

In main. in js, counter always points to lib. counter, a local variable in js, is copied Based on the urgency of JS, such as the original value of a number, string type, or Boolean value, instead of being assigned an address;

Loop dependency problems:

NodeJS's circular dependency is handled as follows: open;

Circular dependency is a problem caused by JS modularization. On the Browser Side, use RequireJS to test modularization. For example, a file file0.js depends on file1.js, while file1.js depends on file0.js, so who will execute file0.js and file1.js first?

Run the following code:

//index.html<!DOCTYPE html>

The output in the console is as follows:

Run the following code:

Undefined
Object {file1: "file1 "}
Object {file0: "file0 "}

When file1.js is executed, file0.js is not executed, so undefined is output. The output result is the same as that of NodeJS;

Then I tried the mass-framework of situ's great god. The Great God's framework directly prompts me: "The module has circular dependency with some previous modules ", this is even better. requireJS directly executes the circular dependency module for the circular dependency, which will lead to self-mining during development ....;

Next I will perform a test under babel-node: below are some tests that can be ignored:

I will try to use the ES6 module. as long as each module is referenced, the module's export has been exported no matter whether the module has been executed. If the exported function is:

Run the following code:

//cyclic.jsimport fn0 from "./file0";fn0();//file0.jsimport fn1 from "./file1";fn1();console.log("file0.js runs");export default function() {console.log("file0 export runs")}//file1.jsimport fn0 from "./file0";fn0();console.log("file1.js runs");export default function() {console.log("file1 export runs")}

If the exported string is:

Run the following code:

//cyclic.jsimport str from "./file0";console.log(str);//file0.jsimport str1 from "./file1";console.log(str1)console.log("file0.js runs");export default "str0";//file1.jsimport str0 from "./file0";console.log(str0)console.log("file1.js runs");export default "str1";

If the exported object is:

In this case, the first line outputs an initial value {}, and the object exported by file0.js is output only after file0.js and file1.js are executed;

If it is an array:

In this case, the first line outputs an initial undefined value that has been statically analyzed, and the object exported by file0.js is output only after file0.js and file1.js are executed;

If it is a Boolean value:

Then, the first line outputs an initial value undefined that has been statically analyzed. The Boolean value exported by file0.js is output only after file0.js and file1.js are executed;

Why? I seem to have found the answer here: http://exploringjs.com/es6/ch_modules.html#_modules, ES6 import and export are pushed to the top level of js, In the function or object, or the basic value is exported to advance by the static analysis, refer to: http://www.ecma-international.org/ecma-262/6.0/#sec-parsemodule, http://www.ecma-international.org/ecma-262/6.0/#sec-toplevelmoduleevaluationjob

Conclusion: when using ES6's export to export data interfaces, it is best to use functions in a unified manner to avoid loop dependencies, because JS will statically resolve different types of objects into different initial values;

Browser compatibility:

  1. Currently, chrome does not support import or export;
  2. Firefox has limited support and is better than chrome;
  3. I use babel;

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.