I have a Vue SPA app. Now I want to extend this app with app modules so I thought to make a folder src/modules that contain the modules folders. I want to put at the root of each folder some configuration js files (store.js, route.js, and so on).
The question is: in the main files (src/store/index.js, src/router/index.js, etc.), how can I loop for every folder in src/modules and check if some configuration file exists to add its content at the main config? Of course this operation should be executed at build time, modules install is not intended to be dynamically.
Thanks a lot
1 Answer
You can use require.context
const configurations = require.context('./modules', true, /config\.js$/i);
configurations.keys().forEach(filename =>
{
console.log(filename);
// file contents will be inside configurations[filename]
});
4 Comments
NicolaM94
Hi there! Follow up question: how do you read the content of the file? Trying to console log contents[filename] gives undefined
IVO GELOV
@NicolaM94 Do you have a reproduction, e.g. on CodeSandbox or similar ?
NicolaM94
I don't unfortunately, but I solved by populating an array with
configurations.keys().map(configurations) (I needed to iterate over json files. I'm starting to learn JS and all of this seems really confusing hahahaha. Thank's for the help nevertheless!IVO GELOV
Yes, this is the example from the Webpack documentation
fsmainly orreadFileSyncetc). Frontend cannot really scan local folders, just use static paths hardcoded as far as I know.