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学习笔记(模块) #4

Open
NoName4Me opened this issue May 27, 2018 · 1 comment
Open

ES6学习笔记(模块) #4

NoName4Me opened this issue May 27, 2018 · 1 comment

Comments

@NoName4Me
Copy link
Owner

基本用法

// out.js
export function hi() {
  // ...
}

export function hello() {
  // ...
}

// export { hi as sayHi };

// in.js
import { hi as sayHi, hello } from 'out';
sayHi();

// 可以修改对象属性,但是不可以直接修改对象
hello = {}; // error
hello.xx = 'xxx'; // ok

// 整体加载
import * as out from 'out';
out.hi();
out.hello();

// 注意不能对 out 以及 out 上 export 的属性进行修改
out = {}; // error
out.hi = 1; // error
out.hi.xxx = 'xxx'; // ok

export default

它让你可以在 import 时无需关注实际的名字:

// out.js
export default function () {
  // 即使 function 有名字也无妨
  // ...
}

// in.js
import anyNameYouLike from 'out';
// 也不需要用 {} 包裹名字

注意 :由于是编译阶段执行,所以在 import 中使用运行时语法是不错误的,比如使用 import { 'hell' + 'o'} from 'out'

CommonJs 和 ES6 模块区别

  • 前者是运行时加载且是值拷贝(如果不清楚缓存,那么得到的值不是改变后的,而是加载时的),后者是异步加载,是引用(该引用是只读的,在编译阶段生成一个引用,运行时去读取对应模块)
@NoName4Me
Copy link
Owner Author

add 一篇文章:深入理解 ES Modules (手绘示例)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant