ES6 Learning--modularity: Import and Export

Source: Internet
Author: User

About the use of JS Modular, we certainly are not unfamiliar, the existing main two types: cmd and AMD, there is a compatible with the CMD and AMD UMD. The general front-end framework supports AMD, and Node.js uses the CMD module syntax.

The import and export syntax for modules is normalized in the ES6, in the 15.2 chapters of the specification. Now browsers do not support, you want to try to use Traceur or Babel. Seemingly angular 2.0 also to adopt ES6 modular syntax, I believe that the browser will certainly gradually support.

This article is just about to introduce the basic grammar, detailed use to stay in the future browser support to say.


export--

There are two basic ways to use it:

Export function foo () {
//.
}
export var awesome =;
var bar = [1,2,3];
export {bar};

function foo () {
//.
}
var awesome =;
var bar = [1,2,3];
Export {foo, awesome, bar};

To rename when exporting:

function foo () {..}
Export {foo as bar};

Default export, each module can have only one default export:

function Foo (..) {
// ..
}
Export default foo;
export{foo as default};

Mixed default exports and normal exports:

function foo () {..}
function bar () {.}
function Baz () {.}
Export {foo as default, bar, Baz, ...};

Exporting from other modules:

Export {foo, bar} from "Baz";
Export {foo as Foo, bar as Bar} from ' Baz ';
Export * from "Baz";


import--

Import {foo} from ' foo ';
Foo ();
Import {foo as thefoofunc} from ' foo ';
Thefoofunc ();
Import foo from "foo";
Or:
import {default as Foo} from ' foo ';

Export default function foo () {.}
Export function Bar () {.}
Export function Baz () {.}

Import Foofn, {bar, Baz as Baz} from "foo";
Foofn ();
Bar ();
BAZ ();

Export function Bar () {.}
export var x =;
Export function Baz () {.}

Import * as Foo from "foo";
Foo.bar ();
foo.x;
Foo.baz ();

The import has a hoisted process, as is the Var declaration variable:

Foo ();
Import {foo} from ' foo ';




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.