Learning to dynamically access files from various folders and subfolders within webpack using JavaScript

I'm currently working on a project in VueJs using webpack. As part of this, I need to dynamically include config/routing files from specific folders. Here is an example of my folder structure:

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

My approach to including these files is as follows:

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

However, I've encountered an issue where the files are not being included, and I suspect it may be due to an error in my regex pattern.

Update:

After investigating further, I realized that my files were not being imported because they are nested within folders/subfolders. When I restructured my folders like this:

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

I was able to successfully import my files. Unfortunately, I am facing issues when attempting to keep the config/routes files inside the frontend folder.

If anyone can provide guidance on how to resolve this issue, I would greatly appreciate it. Thank you.

Answer №1

If you'd like a better grasp on your current regex, take a look at this link: https://regex101.com/r/Y9sDZc/1 (try removing the first line to see how it doesn't match the second.)

I'm not completely certain about what specifically you're trying to match or avoid, so I can only make educated guesses regarding the appropriate solution for your situation. Here are some options to consider:
config\.js will match all files named config.js. Directory considerations are handled by your require.context parameters. Keep in mind that this pattern would also match

plugins/foo/bar/config.js/somefile.txt
, so if you have control over all the files and are confident that this won't cause any issues, using config\.js is the simplest approach.

A more specific option could be:
.*\/config\.js$

I hope this information proves helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring Vue 3 through the lens of class components

Currently, our project is utilizing Vue 2.x and our components are structured as follows: @Component({ template: ` <div> some code .... <div> ` }) export default class class1 extends Vue { @Prop() data: IsomeData; } Vue-class ...

Can you recommend a straightforward method in Vue.js for validating the format of user input?

Here is how I have implemented an email sending feature in Vue.js: <template> <button @click="sendMail(); $emit('close')">Send</button> </template> <script> methods: { sendMail () { axios ...

The element is being offset by SVG animation that incorporates transform properties

I'm working on creating a halo effect by rotating an SVG circular element using the transform rotate function. I've been using getBox to find the center point of the element, but when the rotation occurs, the overall image is getting misaligned w ...

is there a way to modify the background color of a div element by comparing values in javascript?

Is there a way to dynamically update the background color of a div element within a table based on values stored in a json array from a database? ...

What is the best way to create a new browser window for a pop-up?

Using the following JavaScript code will open a popup: window.open('http://www.google.com','mywindow','width=400,height=200'); If you call it two times like this: window.open('http://www.google.com','mywindow ...

Exploring the potential of Oracle Openscript in combination with Javascript using AngularJS,

I have encountered an issue while using Openscript on a form page with a clickable "save" button implemented as a div. Manually clicking the button triggers a javascript event that saves any changes made on the page. However, when I run the script, the but ...

I keep encountering a parser error when making an AJAX call to retrieve JSON data. It seems to be caused by

here is a snippet of code I am working on $.ajax({ type: 'GET', url: "<%=request.getContextPath()%>/manageUsers.do", cache: false, data:{ "resultType": "json", "submit": $.i18n.prop('esadmin.manage.users ...

Save the result of a terminal command into an sqlite database

When I run a particular shell command in node js, the output is displayed on the console. Is there a method to store this output in a variable so that it can be POSTed to an Sqlite database? const shell = require('shelljs'); shell.exec('a ...

Server-side WebSocket doesn't appear to be successfully transmitting messages to the frontend

Using NodeJs with Fastify on the backend in a local environment: Server side: ////// Setting up the app const fastify = require('fastify')({ logger: true }); const path = require('path'); fastify.register(require('@fastify/static& ...

Guide to extracting a key from a specific index within JSON using Google Apps Script

Is there a way to extract values key11-key44? Just managed to retrieve values key1-key4: const data = JSON.parse(UrlFetchApp.fetch(url, options); const keys = Object.keys(data.paths); for (let a in keys) {return keys[a]} { "id": &q ...

Jest test encounters an error due to an unexpected token, looking for a semicolon

I've been working on a Node project that utilizes Typescript and Jest. Here's the current project structure I have: https://i.stack.imgur.com/TFgdQ.png Along with this tsconfig.json file "compilerOptions": { "target": "ES2017", "modu ...

The route in my Node.js Express application appears to be malfunctioning

I am facing an issue with my app.js and route file configuration. Here is my app.js file: const express = require('express'); const app = express(); const port = process.env.PORT || 8080; const userRoute = require('./routes/user.route' ...

What is the best way to use JavaScript to conceal a section of a form div?

After receiving some code from a certain platform and implementing it to hide part of my form div element, I noticed that the element hides and unhides quickly when running in a browser. This rapid hiding and showing behavior occurs when clicking on the bu ...

Tips for extracting header ID from the HTML/DOM using react and typescript

I developed a unique app that utilizes marked.js to convert markdown files into HTML and then showcases the converted content on a webpage. In the following code snippet, I go through text nodes to extract all raw text values that are displayed and store t ...

There was an unexpected token syntax error while trying to assign the database URL from the environment variable "REACT_APP

I am facing an issue with setting an environment variable in my mongo.js file. Here is the code snippet where I have set the ENV variable: const mongo = require('mongodb').MongoClient; const assert = require('assert'); const ObjectId = ...

Exploring the documentation of JQuery's $.Ajax Function

Can anyone help me locate the parameters in the JQuery Docs? jqXHR.done(function( data, textStatus, jqXHR ) {}); http://api.jquery.com/deferred.done/ I've been trying to determine what data represents but haven't had any luck. I've notic ...

Experiencing Chrome freezing issues due to a setInterval function in combination with React

Can anyone assist me with a countdown issue using React? I am trying to set the minutes and seconds by clicking on + and - buttons, then passing the seconds to a new variable called tottime. However, when the user clicks on Go!, the countdown should start ...

What is the most efficient method for executing multiple variable=function() and determining when all tasks have been finished?

I am facing the issue of having multiple variables that need to be calculated before being saved as a JSON file. These calculations are done using a function, but when run asynchronously, they end up undefined. After reading about promises, it seems like t ...

Customize the formatting of linked locale messages in Vue's internationalization (i18n) feature using parameters

Is there a way to link locale messages in vue-i18n with a parameter? { "next": "Next step {step+1}: @:steps[{step}]", "steps": [ "Welcome", // 0 "Briefing", // 1 "Finish" // 2 ...

What is the best way to convert an array of data into a dataset format in React Native?

Within my specific use case, I am seeking to reform the array structure prior to loading it into a line chart. In this context, the props received are as follows: const data = [26.727, 26.952, 12.132, 25.933, 12.151, 28.492, 12.134, 26.191] The objective ...