Skip to content
Advertisement

Add functions in other folder, to an object in this folder

I want to create an object that would import functions from another folder and it would look something like this:

JavaScript

The functions would be inside of a different folder, however, I want to make some sort of importer in which it would make new classes for each new function/file it finds inside of the folder.

someFunction.js Function File:

JavaScript

So I would like for something to look like this:

JavaScript

No, I do not want to have it hard coded into the object, I want to import all functions from a folder and create functions like that.

Advertisement

Answer

Well, first I wan’t to answer your question as I think you want, even if I also think it is not the correct way to proceed.

I’ll also assume that with class you are not referring to an actual ES6 Class, but we are talking about a plain object.

So this is the code:

JavaScript

For this to work, all your functions in your files should be exported like:

JavaScript

To use the ‘importer’, you just do:

JavaScript

A final important note about this odd method: This will only ever work in a NodeJS environment. Even if functions could have worked in other environments (like a browser). The next method, will work for any ECMAScript environment after proper building process: transpilation (EX: Babel) and bundling (EX: Webpack).


Suggested Solution

Use ES6 Static import / export like modern JS libraries do. This comes with huge benefits, from static code analysis to tree shaking and more.

Let’s suppose the following hierarchy:

JavaScript

internals/module-1.js

JavaScript

internals/module-2.js

JavaScript

internals/index.js

JavaScript

index.js

JavaScript

Finally, where you import your moduleGroup, you can do:

JavaScript

Obviously this is a basic scenario, but this is, IMHO, the correct way to deliver a group of functions and other stuff. Please let me know if you have any doubt.

Advertisement