標(biāo)簽: 導(dǎo)入
正文
一、export
1.在聲明前導(dǎo)出
// 導(dǎo)出數(shù)組
export let months = ['Jan', 'Feb', 'Mar','Apr', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
// 導(dǎo)出 const 聲明的變量
export const MODULES_BECAME_STANDARD_YEAR = 2015;
// 導(dǎo)出類
export class User {
constructor(name) {
this.name = name;
}
}
//注意:導(dǎo)出 class/function 后沒(méi)有分號(hào)
2.導(dǎo)出與聲明分開(kāi)
//say.js
function sayHi(user) {
alert(`Hello, ${user}!`);
}
function sayBye(user) {
alert(`Bye, ${user}!`);
}
export {sayHi, sayBye}; // 導(dǎo)出變量列表
二后控、Import *
1.通用
import {sayHi, sayBye} from './say.js';
sayHi('John'); // Hello, John!
sayBye('John'); // Bye, John!
2.as
import * as say from './say.js';
say.sayHi('John');
say.sayBye('John');
import {sayHi as hi, sayBye as bye} from './say.js';
hi('John'); // Hello, John!
bye('John'); // Bye, John!
3.Export “as”
/ say.js
export {sayHi as hi, sayBye as bye};
現(xiàn)在 hi 和 bye 是在外面使用時(shí)的正式名稱:
// main.js
import * as say from './say.js';
say.hi('John'); // Hello, John!
say.bye('John'); // Bye, John!
三庙曙、Export default
// 模塊提供了一個(gè)特殊的默認(rèn)導(dǎo)出 export default 語(yǔ)法,以使“一個(gè)模塊只做一件事”的方式看起來(lái)更好浩淘。
// user.js
export default class User { // 只需要添加 "default" 即可
constructor(name) {
this.name = name;
}
}
請(qǐng)記住捌朴,import 命名的導(dǎo)出時(shí)需要花括號(hào),而 import 默認(rèn)的導(dǎo)出時(shí)不需要花括號(hào)张抄。
請(qǐng)注意在 {...} 中的 import/export 語(yǔ)句無(wú)效砂蔽。