通过读取Node.js目录中的所有文件来动态导出模块 [英] Dynamically export a module by reading all files in a directory in Node.js

查看:123
本文介绍了通过读取Node.js目录中的所有文件来动态导出模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以今天我正尝试读取所有默认导出从具有 index.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 this ?

 export default (() => require('fs')
            .readdirSync(__dirname)
            .filter(fileName => !!/.js$/ig.test(fileName))
            .map(fileName => fileName.split('.')[0])
            .reduce((defaultExportObj, nextFileName) => {
                try {
                    return {
                        ...defaultExportObj,
                        [nextFileName]: require(__dirname + `/${nextFileName}`),
                    };
                }catch(err) { throw err; }
            }, {}))();

推荐答案

我想我会做这样的事情-不确定是否更好-w/e更好是^^

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

webpack: require.context

function expDefault(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
}
export default expDefault(__dirname)

这篇关于通过读取Node.js目录中的所有文件来动态导出模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆