一、export和export default
export和export default都用於導出常量、函數、文件、模塊等,區別是:
1、在一個JS文件中,export可以有多個;export default只能有一個;
2、它們的引用方式不同;
二、import用於引入一個JS文件:
1、如import引入的是依賴包,則不需要相對路徑;
2、如import引入的是自定義的JS文件,則需要相對路徑;
3、import使用export導出的需要用{},使用export導出的不需要{};
例子:
//d1.js
//d1.js是用export導出的
export const str = 'hello world'
export function f0(a){
return a+1
}
export const f1 = (a,b) => {
return a+b
}
export const f2 = (function () {
return 'hello'
})()
引用方式:
//d2.js
//在d2.js中引用d1.js,d1.js是使用export導出的變量和函數,引用時要使用{};
import { str,f0,f1,f2 } from 'd1' //名字要和export相同,d2.js和d1.js在同目錄,如不同目錄則 from '../../d1.js',擴展名可以不寫
const a = f1(1,2)
//也可以寫成:
import {str} from 'd1'
import {f1} from 'd1'
//d3.js
//用export default導出,JS文件中只能有一個
export default const str = 'hello world'
引用:
//d4.js
//引用d3.js,使用export default導出的,引用時不要{}
import str from 'd3' //名字可以任意
如在d3.js中要定義多個,可以先用export,然後再用export default批量導出,這樣:
//修改後的d3.js
export const str = 'hello world'
export function f0(a){
return a+1
}
export const f1 = (a,b) => {
return a+b
}
export default {
str,
f0,
f1
}
引用:
//修改d4.js
import d from 'd3'
const a = d.f0(45)