Skip to content

Commit

Permalink
模块
Browse files Browse the repository at this point in the history
  • Loading branch information
dptms committed Oct 25, 2017
1 parent 95b73d0 commit dec31e9
Showing 1 changed file with 76 additions and 0 deletions.
76 changes: 76 additions & 0 deletions 16.modules.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# 模块
> ES6之前,如果你想要模块化你的代码,或许你需要引入很多个 script 标签,然后还得小心翼翼的注意不要弄错了他们的顺序。或者,你需要通过某个工具把他们给合并成一个文件...喜!大!普!奔!ES6 终于开始支持模块啦!
### 模块的导出导入
> 虽然很像解构赋值,但是只是一种导入的语法规范
* 通过 `export default` 命令默认导出
```js
// 导出
export default {
apiKey: 'abc123'
}
// 导入
import key from './config.js';
```
值得注意的是,一个模块中,只能有一个默认导出。并且在导入的过程中,可以随意命名。

* 通过 `export` 命名导出
```js
// 导出
export const apiKey = 'abc123';
// 导入
import { apiKey } from './config.js';
```
值得注意的是,导入的时候,命名必须跟导出的命名一致,并用花括号 `{}` 包裹。

命名导出的时候,可以有多个导出内容。
```js
// 可以用as取别名,那么在导入的时候也取别名
export { name as n , age , greet }
```
示例
```json
{
"dependencies": {
"lodash": "^4.17.4",
"md5": "^2.2.1",
"moment": "^2.19.1"
},
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.24.1",
"webpack": "^3.0.0"
}
}
```
```js
// config.js
export const url = 'https://www.baidu.com/'

// user.js
import { url } from './config';
import md5 from 'md5';
export default function User(name, email) {
return {
name, email
}
}
function createUrl(email) {
return `${url}/user/${email}`;
}
function getAvatar(email) {
return `https://www.gravatar.com/avatar/${md5(email)}`;
}
export { createUrl, getAvatar };

// app.js
import userprofile, { createUrl, getAvatar } from './src/user';
const user = new userprofile('dp', '[email protected]');
const profile = createUrl(user.email);
const pic = getAvatar(user.email);
console.log(user);
console.log(profile);
console.log(pic);
```

0 comments on commit dec31e9

Please sign in to comment.