文章目录
export 和 import 是es6模块的一个功能,下面主要记录一下几种常见的用法
1,导出 / 导入单个模块
a.js 导出:export const username = ‘huluwa’
b.js 导入:import { username } from ‘a.js’
2,导出列表
a.js 导出:export const username = ‘huluwa’
export const userage = 20
b.js 导入:import { username, userage } from ‘a.js’
3,重命名导出
a.js 导出:const name = ‘huluwa’
const age = 20
export { name as username, age as userage }; // 把name 重命名为username,age重命名为userage
b.js 导入:import { username, userage } from ‘a.js’
4,解构导出并重命名
a.js
const obj = { name: ‘huluwa’, age: 20 }
export const { name: username, age: userage } = obj
b.js
import { userage, userage } from ‘a.js’
默认导出
a.js
const name = ‘huluwa’
export default name;
b.js
import username from ‘a.js’
当 export 后面有 default 时,对应的import 导入时不需要 大括号({ })
export 和 import 复合写法
a.js
const username = ‘huluwa’
export default username
b.js
const userage = 20
export default userage
c.js
export { default as username } from ‘a.js’
export { default as userage } from ‘b.js’
index.js
import { username, userage } from ‘c.js’