Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

javascript - 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?

question from:https://stackoverflow.com/questions/65650975/how-to-make-summary-module-that-re-exports-all-the-exports-of-sub-modules-for-es

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...