DDD
DDD

Reputation: 119

How to merge all exports from different files into one?

e.g.

./one.const.js ---------> module.exports = {};
./two.const.js ----------> module.exports = {};
./index.js---------------> module.exports = mergedExports; // mergedExports: {one: {}, two: {}};

In a folder say xyz I have two files with *.const.js filenames and there's one index.js. I want an automated code in index.js which merges all the exports from *.const.js

Upvotes: 2

Views: 3188

Answers (2)

Ayush Gupta
Ayush Gupta

Reputation: 9285

Assuming you want to do this on startup:

const fs = require('fs');

const regex = new RegExp('.const.js$')
const files = fs.readdirSync('.').filter((fileName) => regex.test(fileName))

const mergedExports = {};

for (let i =0; i < files.length; i++) {
    const fileName = files[i].split('.const.js')[0]
    mergedExports[fileName] = require(`./${files[i]}`)
}

module.exports = mergedExports

If you want to merge the exports into a single object, update the for loop to:

for (let i =0; i < files.length; i++) {
    mergedExports = {  ...mergedExports,
                       ...require(`./${files[i]}`),
                    }
}

Upvotes: 1

Zee
Zee

Reputation: 874

In a folder say xyz I have two files with *.const.js filenames and there's one index.js

The default behavior of require() is that it will look inside the xyz folder for an index.js if you don't manually specify which file to import.

index.js

exports.One = require("./one.const.js");
exports.Two = require("./two.const.js");

outside.js

const { One, Two } = require("./xyz");

Upvotes: 3

Related Questions