在ES6之前,JS文件之间的导入、导出是需要借助require.js、sea.js。现在,可以使用import、export来实现原生JavaScript的导入、导出了。
export
1.导出变量或者常量
export const name = 'hello'
export let addr = 'Beijing'
export var list = [1, 2, 3]
或者
const name = 'hello3'
let addr = 'Beijing'
let list = [1, 2, 4]
export default name
export {
addr,
list
}
2.导出函数
export function say(content) {
console.log(content)
}
export function run() {
console.log('i am running')
}
或者
const say = (content) => {
console.log(content)
}
const run = () => {
console.log('i am running')
}
export {
say,
run
}
3.导出Object
export ({
code: 0,
message: 'success'
})
或者
const des = {
age: 20,
addr: 'Beijing'
}
export default {
des
}
4.导出Class
class Test{
constructor(){
this.id = 2
}
}
export{
Test
}
或者
export class Test {
constructor () {
this.id = 6
}
}
5.修改导出名称
const name = 'hello'
let addr = 'Chengdu City'
var list = [1,2,3]
export{
name as cname,
addr as caddr,
list
}
6.设置默认导出
const name = 'hello'
let addr = 'Chengdu City'
var list = [1,2,3]
export{
name as cname,
addr as caddr
}
export default list
import
1.直接导入
假设导出模块A是这样的:
const name = 'hello'
let addr = 'Chengdu City'
var list = [1,2,3]
export{
name as cname,
addr as caddr
}
export default list
则导入:
import list, {cname, caddr} from A
2.修改导入名称
import list, { cname as name, caddr } from A
3.批量导入
import list, * as mod from A
console.log(list)
console.log(mod.cname)
console.log(mod.caddr)