3

In a javascript ES-2015 modules, can a module member be aware of what other module members there are?

For example, in a CommonJS module, this is possible:

function square(x) {
    return x * x;
}
function whoAmI() {
    return Object.keys(module.exports); // ['square','whoAmI']
}
module.exports = {
    square: square,
    whoAmI: whoAmI
};

In the equivalent ES-2015 module, how do we write the whoAmI() function?

export function square(x) {
    return x * x;
}
export function whoAmI() {
    // ?????
}
Kaiido
  • 123,334
  • 13
  • 219
  • 285
Constablebrew
  • 816
  • 1
  • 7
  • 23

1 Answers1

5

You could import * from yourself, and export an Object.keys of the result:

// 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']

This will not include whoAmI, so to include it:

export let whoAmI = Object.keys(exports).concat('whoAmI');
  • Don't forget that `whoAmI` also needs to return itself. So the output is `['square','whoAmI']` – 4castle Nov 17 '16 at 07:03
  • 1
    By the way, this circular self-dependency is perfectly legal. [Related question](http://stackoverflow.com/q/40240659/5743988) – 4castle Nov 17 '16 at 07:06
  • @torazaburo, why wouldn't `whoAmI` be included in the exports keys? (I agree with @4castle and believe it would.) – Constablebrew Nov 17 '16 at 08:14
  • @Constablebrew Well, it's not, because of the way circular imports are resolved. –  Nov 17 '16 at 08:18