如何将文件夹中的所有文件作为模块导入,以及将所有文件导出为对象? [英] How do I import all files in a folder as an module and export all as an object?
问题描述
我正在尝试将每个文件作为模块导出到某个文件夹中,以作为单个对象导入.我该怎么办?
I'm trying to make every file exported as module in a certain folder, to be imported used as a single object. How should I do this?
我用一个很长很长的单个文件制作了一个javascript插件.现在我正在尝试使其被多个文件分开.我正在使用Webpack.
I had made a javascript plugin with a long long single file. and I'm now trying to make it to be separated by several files. I'm using Webpack for it.
然后,在我的插件代码中,有一个名为"fn"的巨大对象,其中包含40〜50个函数,每个函数有200〜300行.为了拆分它们,我创建了一个名为"fn"的文件夹,并将每个函数作为每个文件放置.文件的每个名称和函数的名称都相同.因此默认情况下,名为"foo"的函数会导出到"fn"文件夹中名为"foo.js"的文件中.
And, in my plugin code, there was a huge object named "fn" which contains 40~50 functions with 200~300lines each. To split them, I made a folder named "fn" and puts each functions as each files. Each name of file and name of function are identical. so function named "foo" is exported by default in a file named "foo.js" in "fn" folder.
现在我正尝试将它们全部导入,并像这样将其导出为单个对象.
And now I'm trying to import them all and export it as a single object like this.
src/fn/foo_or_whatever.js
export default function aFunctionWhichIUse(){
// return whatever;
}
src/fn/index.js
import foo from './foo';
import bar from './bar';
import fooz from './fooz';
import baz from './baz';
import kee from './kee';
import poo from './poo';
import tar from './tar';
import doo from './doo';
.
.
.
import foo_or_whatever from './foo_or_whatever';
export default {
foo,
bar,
fooz,
baz,
kee,
poo,
tar,
doo,
.
.
.
foo_or_whatever,
}
src/index.js
import fn from './fn'
但是我认为这没有道理.现在,我必须每四次键入相同的单词,才能在"fn"对象中添加一个函数.
But I don't think it does make sense. Now I have to type same word every four times just to add a function in a "fn" object.
我发现导入/导出系统不支持从文件夹导入所有文件.然后,我应该使用什么以及应该如何编写代码来做到这一点?
I've found that importing all files from folder is not supported in import/export system. then, What should I use and how should I write code to do that?
有没有办法做到这一点?不管该方法是否为导入/导出系统,只要该方法适用于webpack即可.
Is there some way to do like this? I don't matter whether the way is or not import/export system, as long as if the way works on the webpack.
src/index.js
import * as fn from './fn';
推荐答案
const fs = require('fs');
const path = require('path');
const basename = path.basename(__filename);
const functions = {}
fs
.readdirSync("./")
.filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'))
.map((file) => {functions[file.slice(0, -3)] = require(path.join(__dirname, file})))
module.exports = functions;
这样的帮助吗?
这篇关于如何将文件夹中的所有文件作为模块导入,以及将所有文件导出为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!