Importing Vue components dynamically from a specific subdirectory

I'm having trouble importing all files with the .vue extension from a specific subfolder into another component. I am aware of the concept of Automatically Registering Base Components Globally, but it doesn't seem to be applicable in this case.

Imagine a default Vue component (not the main one) that looks something like this:

export default {
  components: {
    red: () => import('./panes/red'),
  },
  data() {
    return {
      current: false,
    };
  },

And suppose my file structure is as follows:

/src
- main.js
- main.vue
-- components/
-- panes/
--- /red.vue
--- /green.vue
--- /blue.vue
-- SubMain.vue

I want to dynamically generate the components object for the SubMain.vue folder.

So, in SubMain.vue, I've tried something like this:

import myComponents from './src/components/panes';

...

components: Object.keys(myComponents).reduce((obj, name) => {
  return Object.assign(obj, { [name]: () => import(myComponents[name]) })
}, {}),

However, ESLint keeps flagging errors related to Missing file extension and Unable to resolve path to module on the myComponents variable. I have verified the path multiple times and attempted different variations, but to no avail. My project is set up using Vue CLI 3.

Answer №1

If you are working with Webpack, one helpful method is to utilize the require.context function:

import _snakeCase from lodash/snakeCase

const modules = require.context('src/modules', true)

modules.keys().map(module => {
    // transform './ModuleName.js' into 'module_name'
    const moduleName = _snakeCase(
        module.replace(/^\.\//, '').replace(/\.js$/, '')
    )
    // globally register new module
    Vue.component(moduleName, modules(module))
})

Answer №2

It appears that importing multiple components in this manner may not be possible without an index file to organize the import/export process for you. For further information, please refer to Import multiple components in vue using ES6 syntax doesn't work

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

What is the best way to evaluate user input against a string retrieved from process.stdin.on()?

I'm having trouble comparing a string with user input from process.stdin.on as it always returns false. //Let's say the user inputs 'hello' every time. process.stdin.on('data', userInput => { let text = userInput.toStrin ...

How can I use jQuery to hide a div after submitting a form?

I am struggling to hide a specific div using an onclick function on my form submit button. However, despite my efforts, the div is not disappearing. Can anyone suggest a better approach for achieving this? My goal is to conceal a div element on my webpag ...

Vue component for children sends data to parent layout through props

Can I Dynamically Pass Content to a Slot in Vue Component? I am utilizing the Vue Webpack Template which includes Vue Router for Single Page Application functionality. The challenge I am encountering involves my master layout structure, as shown below: ...

Criteria for sending error messages (JSON, SQL)

Apologies for any language barriers, I will do my best to explain clearly. I created a function that generates a table from a JSON based on SQL query values within the JSON. Sometimes, when the SQL query is incorrect, I encounter issues accessing the JSO ...

Steps for signing up for a store module

I understand that Vuex allows us to use store.subscribe and provide a callback that is triggered each time there is a change in the store. Within my application, I have a store with multiple modules and I am interested in subscribing only to a specific mo ...

HTML tends to disregard the dimensions specified in the JavaScript file

I'm currently working on replicating an Etch-a-Sketch style drawing board where hovering over a single pixel with the mouse changes its color. However, I've hit a roadblock when it comes to drawing the board. The flexbox container doesn't se ...

What is the best way to insert text into a span element within a for loop using JavaScript?

I am currently working on form validation using an array and a loop. In each required field, I have created empty span elements. Here is the JavaScript code that I have set up: var name = document.querySelector('#Name').value, firstLastName = ...

Using express.js to transfer an uploaded image to Amazon S3

Currently, I am faced with an issue of passing an image uploaded from a react application through express to a managed s3 bucket. The s3 bucket is created and managed by the platform/host I am using, which also generates upload and access urls for me. So f ...

Is there a way to embed a JS media query inside the sticky navbar function for both the onscroll and onclick events?

I've been exploring media queries in JavaScript, and it seems like they work well when the window is resized. However, when nested within onscroll and onclick functions, things start to get a bit tricky. If you run the following code and resize the w ...

What is the best way to deliver static HTML files in Nest.js?

I am encountering an issue with loading JS files from a static /dist folder located outside of my Nest project. While the index.html file loads successfully, any JS file results in a 404 error. In another Node/Express.js project, I am able to serve these ...

Prevent Click Event in JQuery

I have a requirement to disable all click events on my webpage. However, even after using the appropriate code to prevent these events from firing, some of them are still getting called. Let me explain with an example. <div id='parent'> ...

PHP: How to create a custom function to convert JSON data to HTML-encoded text

I am faced with a challenge involving an array containing values from a database, some of which include HTML tags. My goal is to output this array in JSON format, so I am utilizing json_encode for that purpose. However, I am encountering an issue when tr ...

AngularJS is a highly intuitive platform that incorporates Google Maps for

I am relatively new to using Angular and decided to experiment with integrating Google Maps into my project. Here's what I need: I have a search bar for finding restaurants. The API returns the address, latitude, and longitude of the restaurant searc ...

Is there a way to adjust the size of the canvas element in HTML without compromising quality or resorting to zooming?

I'm currently working on a basic modeling application for the web. The main component of my app is a canvas element that I'm trying to size correctly. However, when I set the height and width using CSS, it scales the entire canvas and compromises ...

Passing parameters to JavaScript onload event from PHP

Looking for help with integrating date data from PHP into a JavaScript countdown function. I have extracted the date from a database using PHP, but struggling to pass it correctly to the JavaScript function. My attempt so far: <body onload="countIt(< ...

How can I dynamically redirect based on the selected radio button value in a React application?

I've been attempting to use the "navigate" method from "react-router-dom" to redirect users from the Login screen based on the radio button they click. I've tried using states, but I'm unsure if that's the best approach or if there&apos ...

Icons in CKEditor are not showing up on iPad devices

Experiencing Toolbar Icon Issues on CKEditor I am encountering an issue with the toolbar icons not appearing on the CKEditor when using it on an iPad with Safari. CKEditor Version: 4.3.2 Investigation The CKEditor functions properly on all other browse ...

Tips for choosing and controlling Google Maps markers using their unique identifiers (V3 JS API)

Currently, I have a Google Map that displays markers on the left side and a list with explanatory content items corresponding to each marker on the right side. When a marker is clicked, the list will automatically scroll to the relevant entry. This functio ...

Transform the snake code by incorporating a visual image as the face of the serpent

Can someone help me change the snake's face to an image instead of a color fill in this code? And how can I add arrows for mobile compatibility? (function() { // Insert JS code here })(); // Insert CSS code here This code snippet includes functi ...

invoking a jquery method through the onClick event handler

How can I make use of jQuery to perform different actions based on which checkbox is clicked? I am encountering an issue where the onClick event is not triggered for any of the checkboxes below. <HTML> <HEAD> <script type="text/javascr ...