美文网首页
ES6中import * as xxx from 'xxx'的作

ES6中import * as xxx from 'xxx'的作

作者: 小棋子js | 来源:发表于2021-10-29 11:47 被阅读0次

ES6的模块化分为导出(export)与导入(import)两个模块,其中在项目中,我们会经常看到一种用法import * as obj from,这种写法是把所有的输出包裹到obj对象里

// index.js
export function fn1(data){undefined
  console.log(1)
}
export function fn2(data){undefined
  console.log(2)
}
import * as Fn from './index.js'
Fn.fn1()  // 1
Fn.fn2()  // 2

示例2

let myName = "Jon";
let myAge = 18;
let myfn = function(){undefined
    return "我是"+myName+"!今年"+myAge+"岁了"
}
export {undefined
    myName as name,
    myAge as age,
    myfn as fn
}
import {fn,age,name} from "./test.js";
consolelog(fn()); //我是Jon!今年19岁了
console.log(age); //19
consolelog(name); //Jon

或者

import * as info from "./test.js"; //通过*来批量接收,as 来指定接收的名字
console.log(info.fn()); //我是Jon!今年18岁了
console.log(info.age); //18
console.log(info.name); //Jon

总结:
import * as xxx from ‘xxx’: 会将若干export导出的内容组合成一个对象返回;
import xxx from ‘xxx’:(export default Din)只会导出这个默认的对象作为一个对象

相关文章

网友评论

      本文标题:ES6中import * as xxx from 'xxx'的作

      本文链接:https://www.haomeiwen.com/subject/mvjialtx.html