以为Es6,javascript第一次支持了module。ES6的模块化分为导出(export)与导入(import)两个模块,其中在项目中,我们会经常看到一种用法import * as obj from,这种写法是把所有的输出包裹到obj对象里。
1 2 3 4 5 6 7 |
1 2 3 | import * as Fn from './index.js' Fn.fn1() // 1 Fn.fn2() // 2 |
1 2 3 4 5 6 7 8 9 10 | let myName = "Jon"; let myAge = 18; let myfn = function(){ return "我是"+myName+"!今年"+myAge+"岁了" } export { myName as name, myAge as age, myfn as fn } |
1 2 3 4 |
1 2 3 4 |
重命名export和import,如果导入的多个文件中,变量名字相同,即会产生命名冲突的问题,为了解决该问题,ES6为提供了重命名的方法,当你在导入名称时可以这样做。
1 2 3 4 5 6 7 8 9 10 | /*************test1.js*****************/ export let myName = "我来自test1.js"; /*************test2.js*****************/ export let myName = "我来自test2.js"; /*************index.js****************/ import {myName as name1} from "./test1.js"; import {myName as name2} from "./test2.js"; console.log(name1); //我来自test1.js console.log(name2); //我来自test2.js |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | # a.js导出单个特性 // 导出一个变量 export let name = 'Jack'; // 导出一个函数 export function numProduct(num1, num2) { return num1 * num2; } // 导出一个类 export class Person { constructor(height, width) { this.height = height; this.width = width; } calcArea() { return this.height * this.width; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | # b.js import { name, numProduct, Person } from './a.js'; // {}中的变量名要与export导出的变量名保持一致 console.log(name); // Jack console.log(numProduct(1, 7)); // 7 let p = new Person(10, 20); console.log(p.height, p.width, p.calcArea()); // 10 20 200 // 导出的变量较多时可以使用*通配符代替变量名 import * as all from './a.js'; console.log(all); console.log(all.name); console.log(all.numProduct(1, 7)); let p = new all.Person(10, 20); console.log(p); console.log(p.height, p.width, p.calcArea()); |
1 2 | const x = 1024; export default x; |
1 2 | import y from './a.js'; // 此处的变量名不加{},不需要与export default后面的名称保持一致,导入者可以直接重命名 console.log(y); // 1024 |
支付宝扫一扫打赏
微信扫一扫打赏
共 0 条评论关于"浅谈ES6中import * as xxx from几种常见导出基本用法"
最新评论