How to autogenerate imports or dynamically import in javascript

248 views Asked by At

Hi so I have a folder structure like this:

component A
    --- other files
    extra.js
component B
    --- other files
    extra.js
component C
    --- other files
    extra.js
main.js

In each file called "extra.js", I'm exporting a json containing information I need for my app.

In main.js, I import the json each extra.js, manipulate it and do stuff with it.

The code in main will end up looking like this:

import A from './A/extra';
import B from './B/extra';
import C from './C/extra';

for json in [A, B, C]:
    do stuff with the json

The problem here is the duplication. Every time I create a new component, I have to add the component to main in two places. Every time I delete a component, I have to delete the code in main. Very bug-prone. Should be automated.

One solution I guess could be just to combine all the extra.js into one gigantic json file, but we have a lot of components, and I would prefer to keep them separate since it makes delegating ownership easier.

What I would like to do is:

for folder in './':
    import extra from folder + '/extra';
    do stuff with the json

Or somehow just generate javascript that includes all the imports so the dev doesn't have to do it himself.

create a autogen.js file
for folder in './':
   append 'import ' + folder + ' from ' + folder + '/extra;'

... later import autogen.js into main.js

Not sure how to do this. Any ideas?

0

There are 0 answers