有什么区别:
从'utils'导入utils
和
从“utils”导入 * 作为 utils
?
情况 A:
//utils.js
export function doSomething()
{
//...
}
情况 B:
//utils.js
export function doSomething()
{
//...
}
export default function doSomethingDefault()
{
//...
}
更新:
我被 vscode 的 intellisense 功能误导了,但正如推荐的那样,在 node+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);
最佳答案
从你的例子:
案例 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, default: 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
将有两个方法(doSomething
和 default
)。
关于javascript - ES6 : "import * as alias" vs "import alias",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45697628/