0

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

3
  • Hmm, maybe using a build tool like Webpack or a shell script of some kind? Commented Oct 27, 2022 at 9:20
  • @user115014 I don't want to use a shell script, I prefer to use javascript inside main files. Could you answer the question with the way to achive the solution with webpack? Thank you. Commented Oct 27, 2022 at 9:27
  • 1
    Check how to access the filesystem from a stand point of a Node.js app (using fs mainly or readFileSync etc). Frontend cannot really scan local folders, just use static paths hardcoded as far as I know. Commented Oct 27, 2022 at 10:41

1 Answer 1

1

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]
});
Sign up to request clarification or add additional context in comments.

4 Comments

Hi there! Follow up question: how do you read the content of the file? Trying to console log contents[filename] gives undefined
@NicolaM94 Do you have a reproduction, e.g. on CodeSandbox or similar ?
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!
Yes, this is the example from the Webpack documentation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.