Nitish Kumar
Nitish Kumar

Reputation: 6276

How to get files dynamically from folder, subfolder and its subfolder in webpack javascript

I am trying to build a small application in VueJs with webpack, where I want to includes a config/routing files dynamically from folders. I have a folder structure something like this:

plugins
|----Ecommerce
|--------backend
|--------frontend
|------------config.js
|------------routes.js
|------------components
|----------------products.vue
|----Blog
|--------backend
|--------frontend
|------------config.js
|------------routes.js
|------------components
|----------------posts.vue

For this I am trying to include my files with:

const configRequire = require.context('./../plugins/', true, /\.\/[^/]+\/config\.js$/);
const routesRequire = require.context('./../plugins/', true, /\.\/[^/]+\/routes\.js$/);

But somehow it is not including the files. I guess something wrong with my regex

Edit:

Found out the problem, my files are not getting imported as it is inside folders/subfolder/subfolder, if I keep the folder structure as this:

plugins
|----Ecommerce
|--------backend
|--------config.js
|--------routes.js
|--------frontend
|------------components
|----------------products.vue
|----Blog
|--------backend
|--------config.js
|--------routes.js
|--------frontend
|------------components
|----------------posts.vue

I can see my files getting imported. But doesn't get when I keep my config/routes files inside frontend folder

Help me out in this. Thanks.

Upvotes: 2

Views: 1204

Answers (1)

TommyF
TommyF

Reputation: 7150

Check this to better understand your current regex: https://regex101.com/r/Y9sDZc/1 (remove the first line to see how it doesn't match the second.)

I'm not entirely sure what exactly you want to match and what not, so I can only guess what the correct solution for your case is, but here are some options:
config\.js matches all files called config.js. Directories are taken care of by your require.context parameters. This would also match plugins/foo/bar/config.js/somefile.txt though, if you control all files and are sure this isn't a problem using config\.js is your simplest solution.

A bit more selective would be:
.*\/config\.js$

Hope that helps.

Upvotes: 1

Related Questions