Javascript ES-2015模块是否能够自我感知?
在javascript ES-2015模块中,模块成员能否知道还有哪些其他模块成员 例如,在CommonJS模块中,这是可能的:Javascript ES-2015模块是否能够自我感知?,javascript,es6-modules,Javascript,Es6 Modules,在javascript ES-2015模块中,模块成员能否知道还有哪些其他模块成员 例如,在CommonJS模块中,这是可能的: function square(x) { return x * x; } function whoAmI() { return Object.keys(module.exports); // ['square','whoAmI'] } module.exports = { square: square, whoAmI: whoAmI }
function square(x) {
return x * x;
}
function whoAmI() {
return Object.keys(module.exports); // ['square','whoAmI']
}
module.exports = {
square: square,
whoAmI: whoAmI
};
在等效的ES-2015模块中,我们如何编写whoAmI()
函数
export function square(x) {
return x * x;
}
export function whoAmI() {
// ?????
}
您可以从自己导入
*
,然后导出对象。结果的键为:
// myModule.js
import * as exports from './myModule';
export function square(x) { return x * x; }
export let whoAmI = Object.keys(exports);
// consumer.js
import {whoAmI} from `./myModule';
console.log(whoAmI);
> ['square']
这将不包括whoAmI
,因此要包括它:
export let whoAmI = Object.keys(exports).concat('whoAmI');
不要忘记whoAmI
也需要返回自身。所以输出是['square','whoAmI']
,顺便说一句,这种循环的自我依赖是完全合法的@torazaburo,为什么导出密钥中不包含whoAmI
?(我同意@4castle,并相信它会。)@Constablebrew好吧,事实并非如此,因为循环进口的解决方式。