Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  51] [ 4]  / answers: 1 / hits: 17052  / 5 Years ago, mon, march 25, 2019, 12:00:00

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?



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.



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'


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?



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';

More From » webpack

 Answers
13
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;


Would something like this help?


[#52357] Thursday, March 21, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lewis

Total Points: 739
Total Questions: 100
Total Answers: 94

Location: Nepal
Member since Mon, Jan 4, 2021
3 Years ago
;