ES6 模塊知識(shí)點(diǎn)總結(jié)

2020-8-26    前端達(dá)人

模塊化 export 和 import

import 導(dǎo)入模塊、export 導(dǎo)出模塊
可以直接在任何變量或者函數(shù)前面加上一個(gè) export 關(guān)鍵字,就可以將它導(dǎo)出。
在一個(gè)文件中:

export const sqrt = Math.sqrt; export function square(x) { return x * x; } export function diag(x, y) { return sqrt(square(x) + square(y)); }  
    然后在另一個(gè)文件中這樣引用:
import { square, diag } from 'lib'; console.log(square(11)); // 121 console.log(diag(4, 3));  

總結(jié)

//mod.js // 第一種模塊導(dǎo)出的書寫方式(一個(gè)個(gè)的導(dǎo)出) // 導(dǎo)出普通值 export let a = 12; export let b = 5; // 導(dǎo)出json export let json = { a, b }; // 導(dǎo)出函數(shù) export let show = function(){ return 'welcome'; }; // 導(dǎo)出類 export class Person{ constructor(){ this.name = 'jam'; } showName(){ return this.name; } } //index.js //導(dǎo)出模塊如果用default了,引入的時(shí)候直接用,若沒有用default,引入的時(shí)候可以用{}的形式 // 導(dǎo)入模塊的方式 import { a, b, json, show, Person } from './mod.js'; console.log(a); // 12 console.log(b); // 5 console.log(json.a); // 12 console.log(json.b); // 5 console.log(show()); // welcome console.log(new Person().showName()); // jam //mod1.js // 第二種模塊導(dǎo)出的書寫方式 let a = 12; let b = 5; let c = 10; export { a, b, c as cc // as是別名,使用的時(shí)候只能用別名,特別注意下 }; //index1.js // 導(dǎo)入模塊的方式 import { a, b, cc // cc是導(dǎo)出的,as別名 } from './mod1.js'; console.log(a); // 12 console.log(b); // 5 console.log(cc); // 10 //mod2.js // 第三種模塊導(dǎo)出的書寫方式 ---> default // default方式的優(yōu)點(diǎn),import無需知道變量名,就可以直接使用,如下 // 每個(gè)模塊只允許一個(gè)默認(rèn)出口 var name = 'jam'; var age = '28'; export default { name, age, default(){ console.log('welcome to es6 module of default...'); }, getName(){ return 'bb'; }, getAge(){ return 2; } }; //index2.js // 導(dǎo)入模塊的方式 import mainAttr from './mod2.js'; var str = ' '; // 直接調(diào)用 console.log(`我的英文名是:${mainAttr.name}我的年齡是${mainAttr.age}`); mainAttr.default(); // welcome to es6 module of default... console.log(mainAttr.getName()); // bb console.log(mainAttr.getAge()); // 2 //mod3.js var name = 'jam'; var age = '28'; export function getName(){ return name; }; export function getAge(){ return age; }; //index3.js // 導(dǎo)入模塊的方式 import * as fn from './mod3.js'; // 直接調(diào)用 console.log(fn.getName()); // 


分享本文至:

日歷

鏈接

個(gè)人資料

存檔