Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ES6 Export & Import #28

Closed
PolluxLee opened this issue May 14, 2018 · 0 comments
Closed

ES6 Export & Import #28

PolluxLee opened this issue May 14, 2018 · 0 comments

Comments

@PolluxLee
Copy link
Owner

PolluxLee commented May 14, 2018

ES6 Export & Import

Import 命令会被 JavaScript 引擎静态分析(必须在代码的顶层,比如在 if, for, 或 function 里会报错),先于模块内的其他语句执行(具有提升效果)

Export

1. 因为要规定对外的接口,所以要加花括号

export var m = 1
export function f() {}

/*--------------div--------------*/

// or
var m = 1
export {m}
function f() {}
export {f}

/*--------------div--------------*/

var a = 1
var b = 2
export {a, b}

2. 重命名

var m = 1
export {m as n}

3. export default命令,为模块指定默认输出
一个模块只能有一个默认输出

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

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

/*--------------div--------------*/

// right
var a = 1;
export default a;

// wrong
export default var a = 1;

Import

1. 导入 default 变量不需要加花括号

// a.js
var str = 'hello'
export default str

// b.js
// import 命令可以为 default 变量指定任意名字
import hello from './a'
console.log(hello)

2. 除了 default 之外的导入都需要加花括号

// a.js
var m = 1
var n = 2
export {m, n}
function f() { console.log('hello') }
export {f}

// b.js
import {m, n as num, f} from './a'
console.log(m, num)
f()

ES6 模块与 CommonJS 模块的差异

  • CommonJS 模块输出的是一个值的拷贝,ES6 模块输出的是值的引用
  • CommonJS 模块是运行时加载,ES6 模块是编译时输出接口

CommonJS

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

// main.js
var mod = require('./lib');

console.log(mod.counter);  // 3
mod.incCounter();
console.log(mod.counter); // 3

ES6

// lib.js
export let counter = 3;
export function incCounter() {
  counter++;
}

// main.js
import { counter, incCounter } from './lib';
console.log(counter); // 3
incCounter();
console.log(counter); // 4
@PolluxLee PolluxLee changed the title ES6 Export & Import ES6 Module May 14, 2018
@PolluxLee PolluxLee changed the title ES6 Module ES6 Export & Import Jun 21, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant