模塊化 export 和 import
import 導(dǎo)入模塊、export 導(dǎo)出模塊
可以直接在任何變量或者函數(shù)前面加上一個 export 關(guān)鍵字,就可以將它導(dǎo)出。
在一個文件中:
export const sqrt = Math.sqrt; export function square(x) { return x * x; } export function diag(x, y) { return sqrt(square(x) + square(y)); }
import { square, diag } from 'lib'; console.log(square(11)); console.log(diag(4, 3));
總結(jié)
export let a = 12; export let b = 5; export let json = { a, b }; export let show = function(){ return 'welcome'; }; export class Person{ constructor(){ this.name = 'jam'; } showName(){ return this.name; } } import { a, b, json, show, Person } from './mod.js'; console.log(a); console.log(b); console.log(json.a); console.log(json.b); console.log(show()); console.log(new Person().showName()); let a = 12; let b = 5; let c = 10; export { a, b, c as cc }; import { a, b, cc } from './mod1.js'; console.log(a); console.log(b); console.log(cc); 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; } }; import mainAttr from './mod2.js'; var str = ' '; console.log(`我的英文名是:${mainAttr.name}我的年齡是${mainAttr.age}`); mainAttr.default(); console.log(mainAttr.getName()); console.log(mainAttr.getAge()); var name = 'jam'; var age = '28'; export function getName(){ return name; }; export function getAge(){ return age; }; import * as fn from './mod3.js'; console.log(fn.getName());