Skip to content Skip to sidebar Skip to footer

Dynamically Export A Module By Reading All Files In A Directory In Node.js

So today i was trying read all default exports from some directory which has index.js. Try to wrap it inside one object and export it back again. Is there a better way to handle t

Solution 1:

I guess i'd do something like this - not sure if this is better - w/e better is ^^

webpack: require.context

functionexpDefault(path, mode = "sync"){

    const modules = {}
    const context = require.context(path, false, /\.js$/, mode)
    context.keys().forEach(file => {
        const name = fileName.replace(/^.+\/([^/]+)\.js$/, "$1")
        modules[name] = context(name).default
    })
    return modules
}
exportdefaultexpDefault(__dirname)

Post a Comment for "Dynamically Export A Module By Reading All Files In A Directory In Node.js"