`import * as Thing from '...' 是什么类型的?
What type does `import * as Thing from '...'` make?
import * as MyModule from 'module-name'
创建什么类型?
我假设它是一个普通的 javascript 对象,键是导出值的名称,但我不确定。
示例:
./module-that-exports.js
export const a = 'foo';
export const b = 'bar';
./module-that-imports.js
import * as thing from './module-that-exports';
typeof thing; // what does this print? what is its type?
具体来说,我正在使用 webpack。我不知道这是否有所作为。
假设您有一个文件:
const doSomething = () => console.log('hello');
const doSomethingElse = () => console.log('world');
export default {
doSomething,
doSomethingElse
}
并且您有另一个使用它的文件。您不想命名所有字段,因此您没有这样做,而是将它们分组在一个对象中。
import * as something from './doSomething'
这将创建一个包含这两个函数的对象..
console.log(something);
将打印:
{
doSomething: function() { ... }
doSomethingElse: function() { ... }
}
这样做的好处是你不需要一些长的导入,只需要使用 something
对象。
something.doSomething();
something.toSomethingElse();
是的,它是一个对象(不可调用),所以 typeof
将产生 "object"
。
但是,它不是一个普通对象,它是一个奇异的对象 module namespace object. It does not inherit from Object.prototype
, it is not extensible,并且它的所有属性都是解析为导出绑定的不可写 getter。不过,您的 transpiler/module 加载程序可能无法完全模拟这一点。
import * as MyModule from 'module-name'
创建什么类型?
我假设它是一个普通的 javascript 对象,键是导出值的名称,但我不确定。
示例:
./module-that-exports.js
export const a = 'foo';
export const b = 'bar';
./module-that-imports.js
import * as thing from './module-that-exports';
typeof thing; // what does this print? what is its type?
具体来说,我正在使用 webpack。我不知道这是否有所作为。
假设您有一个文件:
const doSomething = () => console.log('hello');
const doSomethingElse = () => console.log('world');
export default {
doSomething,
doSomethingElse
}
并且您有另一个使用它的文件。您不想命名所有字段,因此您没有这样做,而是将它们分组在一个对象中。
import * as something from './doSomething'
这将创建一个包含这两个函数的对象..
console.log(something);
将打印:
{
doSomething: function() { ... }
doSomethingElse: function() { ... }
}
这样做的好处是你不需要一些长的导入,只需要使用 something
对象。
something.doSomething();
something.toSomethingElse();
是的,它是一个对象(不可调用),所以 typeof
将产生 "object"
。
但是,它不是一个普通对象,它是一个奇异的对象 module namespace object. It does not inherit from Object.prototype
, it is not extensible,并且它的所有属性都是解析为导出绑定的不可写 getter。不过,您的 transpiler/module 加载程序可能无法完全模拟这一点。