1
0
mirror of https://github.com/ruanyf/es6tutorial.git synced 2025-05-24 18:32:22 +00:00

docs(module): 加入解释export default var a = 1为什么不对

This commit is contained in:
ruanyf 2016-02-17 09:57:16 +08:00
parent c957ce868a
commit 19506b0b56
2 changed files with 23 additions and 2 deletions

View File

@ -248,7 +248,7 @@ export default function () {
上面代码是一个模块文件`export-default.js`,它的默认输出是一个函数。 上面代码是一个模块文件`export-default.js`,它的默认输出是一个函数。
其他模块加载该模块时import命令可以为该匿名函数指定任意名字。 其他模块加载该模块时,`import`命令可以为该匿名函数指定任意名字。
```javascript ```javascript
// import-default.js // import-default.js
@ -256,7 +256,7 @@ import customName from './export-default';
customName(); // 'foo' customName(); // 'foo'
``` ```
上面代码的import命令可以用任意名称指向`export-default.js`输出的方法,这时就不需要知道原模块输出的函数名。需要注意的是,这时`import`命令后面,不使用大括号。 上面代码的`impor`t命令可以用任意名称指向`export-default.js`输出的方法,这时就不需要知道原模块输出的函数名。需要注意的是,这时`import`命令后面,不使用大括号。
`export default`命令用在非匿名函数前,也是可以的。 `export default`命令用在非匿名函数前,也是可以的。
@ -307,11 +307,31 @@ function add(x, y) {
return x * y; return x * y;
}; };
export {add as default}; export {add as default};
// 等同于
// export default add;
// app.js // app.js
import { default as xxx } from 'modules'; import { default as xxx } from 'modules';
// 等同于
// import xxx from 'modules';
``` ```
正是因为`export default`命令其实只是输出一个叫做`default`的变量,所以它后面不能跟变量声明语句。
```javascript
// 正确
export var a = 1;
// 正确
var a = 1;
export default a;
// 错误
export default var a = 1;
```
上面代码中,`export default a`的含义是将变量`a`的值赋给变量`default`。所以,最后一种写法会报错。
有了`export default`命令输入模块时就非常直观了以输入jQuery模块为例。 有了`export default`命令输入模块时就非常直观了以输入jQuery模块为例。
```javascript ```javascript

View File

@ -190,6 +190,7 @@
- Dave Herman, [Static module resolution](http://calculist.org/blog/2012/06/29/static-module-resolution/): ES6模块的静态化设计思想 - Dave Herman, [Static module resolution](http://calculist.org/blog/2012/06/29/static-module-resolution/): ES6模块的静态化设计思想
- Jason Orendorff, [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/): ES6模块设计思想的介绍 - Jason Orendorff, [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/): ES6模块设计思想的介绍
- Ben Newman, [The Importance of import and export](http://benjamn.github.io/empirenode-2015/#/): ES6模块的设计思想 - Ben Newman, [The Importance of import and export](http://benjamn.github.io/empirenode-2015/#/): ES6模块的设计思想
- ESDiscuss, [Why is "export default var a = 1;" invalid syntax?](https://esdiscuss.org/topic/why-is-export-default-var-a-1-invalid-syntax)
## 工具 ## 工具