ES6:" import * as alias" vs"导入别名"

时间:2017-08-15 16:52:27

标签: javascript ecmascript-6 es6-modules

之间有什么区别:

import utils from 'utils'

import * as utils from 'utils'

如果是A:

//utils.js
export function doSomething()
{
//...
}

如果是B:

//utils.js
export function doSomething()
{
//...
}
export default function doSomethingDefault()
{
//...
}

更新

我被vscode的intellisense功能误导了,但正如推荐的那样,对节点+ babel的一个小测试表明了差异:

//index.js
import utilsCaseA from './utils1'
import * as utilsCaseAWildcard from './utils1'
var utilsCaseARequire = require('./utils1')

import utilsCaseB from './utils2'
import * as utilsCaseBWildcard from './utils2'
var utilsCaseBRequire = require('./utils2')

var compareObjects = 
{
    utilsCaseA, utilsCaseAWildcard, utilsCaseARequire,utilsCaseB,utilsCaseBWildcard,utilsCaseBRequire
};
console.log(compareObjects);

enter image description here

2 个答案:

答案 0 :(得分:9)

从你的例子:

案例A:

//utils.js
export function doSomething()
{
//...
}

案例B:

//utils.js
export function doSomething()
{
//...
}
export default function doSomethingDefault()
{
//...
}

结果:

import utils from 'utils'
utils() // (Case A: undefined, Case B: doSomethingDefault)

import * as utils from 'utils'
utils // (Case A: utils = { doSomething: function }, Case B: utils = { doSomething: function, doSomethingDefault: function })

import { doSomething } from 'utils'
doSomething() // (both Case A and Case B: doSomething = doSomething)

案例A和案例B之间的区别在于,在案例A import utils from 'utils'中,utils将为undefined,因为没有默认导出。如果是B,utils将引用doSomethingDefault

使用import * as utils from 'utils',案例A utils将有一个方法(doSomething),而案例B utils将有两个方法(doSomethingdoSomethingDefault)。

答案 1 :(得分:6)

import utils from 'utils'默认来自' utils'包。在提供的案例中undefined

import * as utils from 'utils'使用所有可用的命名导出(包括默认值)导入整个模块exports对象。

相关问题