Re-exporting from multiple modules in ES5

604 Views Asked by At

I have index.js with the following code that works fine on the client, re-exporting functions defined in three other modules:

export * from './validators';
export * from './comparators';
export * from './transforms';

But I want to use these in NodeJS. Our current version, at least, appears not to know this ES6 syntax. I know, in the modules where the functions are defined, how to export them using

module.exports = {
    func1,
    func2
}

But what's the corresponding syntax for use in the re-exporting module?

2

There are 2 best solutions below

0
Bergi On BEST ANSWER

A simple but effective solution would be

Object.assign(module.exports,
    require('./validators'),
    require('./comparators'),
    require('./transforms'),
);

This is similar to what ES6 does, but does not support updating of exported members. For a closer approximation, you'd need to use getters or a proxy.

Of course there's a good alternative: just write ES6 syntax and use a transpiler that knows how to properly translate it to ES5!

0
Green Grasso Holm On

Thanks to @Bergi, that solution worked. I'd also just worked out the following nearly equivalent one but my version has more typing:

const validators = require('./validators');
const comparators = require('./comparators');
const transforms = require('./transforms');

module.exports = {
    ...validators,
    ...comparators,
    ...transforms
};