模块化 export 和 import
import 导入模块、export 导出模块
可以直接在任何变量或者函数前面加上一个 export 关键字,就可以将它导出。
在一个文件中:
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));
总结
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());