目录
ES6 模块化导入导出
export
使用
导出一个变量
export var name = '小明';
导出一个函数
export function say(msg){}
常用导出方式(推荐)
// person.js
var name = '小明'
var age = 18
function say(msg) {
console.log(msg)
}
export {name, age, say}
as 用法
const name = '小明';
export {
name as n,
name as m
}
可以利用 as 将模块输出多次。
某些情况下,一个模块中包含某个的功能,我们并不希望给这个功能命名,而且让导入者可以自己来命名 这个时候就可以使用 export default
:
// person.js
export default function() {
console.log('default func')
}
// useperson.js
import myFunc from './person.js'
myFunc()
import
使用
首先,我们需要在 HTML 代码中引入两个 js 文件,并且类型需要设置为 module
:
<script src="./js/person.js" type="module"></script>
<script src="./js/useperson.js" type="module"></script>
一般用法
import {name, age, say} from './person.js';
as 用法
import { name as personName } from './person.js';
整体模块加载 *
//person.js
export var name = '小明'
export var age = 18
export function say(msg) {
console.log(msg)
}
//逐一加载
import {name, age, say} from './person.js';
//整体加载
import * as person from './person.js';
console.log(person.name);
person.say('hi')
export default
使用
其实 export default
,在项目里用的非常多,一般一个 Vue 组件我们都是使用 export default
命令,需要注意的是使用 export default
命令时,import
是不需要加{}
的。而不使用 export default
时,import
是必须加{}
,示例如下:
export default function() {
console.log('default func')
}
import myFunc from './person.js'
myFunc()
export default
其实是导出一个叫做 default
的变量,所以其后面不能跟变量声明语句。
注意:
export default
在同一个模块中,不允许同时存在多个。