ES-2015模块能自我感知吗?

Can an ES-2015 module be self-aware?

本文关键字:感知 自我 模块 ES-2015      更新时间:2023-09-26

在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
};

在等效ES-2015模块中,我们如何编写whoAmI()函数?

export function square(x) {
    return x * x;
}
export function whoAmI() {
    // ?????
}

您可以从自己导入*,并导出结果的Object.keys:

// 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');