Skip to content
Advertisement

How to make summary module that re-exports all the exports of sub-modules for ESM modules?

How do you re-export the exports from multiple files in an ESM module without listing each individual export separately?

I have a CommonJS module directory that consists of a number of files that I would like to convert to ESM imports/exports. Currently, I have an index.js file that contains this:

// this just re-exports everything that the sub-modules export
module.exports = [
    './mapConcurrent.js',
    './deferred.js',
    './utils.js',
    './rateMap.js',
    './concurrency.js',
    './retry.js',
].reduce((obj, file) => {
    const m = require(file);
    Object.assign(obj, m);
    return obj;
}, {});

This re-exports all the exports of all the files in the module directory so that a client of this module can just import one file and get all the entry points for all the files without having to know which entry point is in which file and so on. This works fine for CommonJS.

How do you accomplish something similar in the ESM module world without having to explicitly name each export from all the sub-files?

Advertisement

Answer

You can use a star export for each of them:

export * from './mapConcurrent.js';
export * from './deferred.js';
export * from './utils.js';
export * from './rateMap.js';
export * from './concurrency.js';
export * from './retry.js';

It will re-export all the named exports from the respective module, but not the default export (those you’d need to rename or they would collide).

So no, you don’t have to explicitly name each export, but you must explicitly declare all of the sub-files.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement