Consider developing a custom plugin that automatically loads all components within your nuxt.js application

I have been attempting to load and define all my components globally in nuxt.js.

However, I encounter an error when trying to load the *.vue file: "Cannot find module ....".

Despite the fact that the file exists in the specified location...

Below is the loading plugin :

import Vue from 'vue'
import fs from 'fs'
import path from 'path'

const componentDirectory = `.${path.sep}src${path.sep}components`;
const componentTypes = ['atom','molecule','organism'];

function getComponentType(componentName) {

    let compGroup = ( componentName || '' ).toLowerCase().split('.');

    if (compGroup.length < 3 || compGroup[ compGroup.length - 1 ] !== 'vue' ) {
        return null;
    }

    return compGroup[ compGroup.length - 2 ];
}

function allowedComponentType(componentFileName) {
    return componentTypes.indexOf(getComponentType(componentFileName)) !== -1;
}

// Utilizing a synchronous method to list all files in a directory in Node.js recursively
var walkSync = function(dir, filelist) {
    var files = fs.readdirSync(dir);
    filelist = filelist || [];

    files.forEach(function (file) {        
        if (fs.statSync(dir + path.sep + file).isDirectory()) {
            filelist = walkSync(dir + path.sep + file, filelist);
        } else if (allowedComponentType(file) ) {
            filelist.push(dir + path.sep + file);
        }
    });

    return filelist;
};

walkSync(componentDirectory).forEach(componentFileName => {
    try {
        let componentPath = path.resolve(path.resolve(), componentFileName);

        console.log('Component name : ', componentPath)
        const component = require(componentPath).default;
        Vue.component(component.name, component);
    }
    catch (e) {
        console.log('Error : ' , e )
    }
});

P.S .: Once the issue is resolved, I will replace functions with a regular expression.

Answer №1

Create a JavaScript file with the following content in your components directory:

import Vue from 'vue'

const reqComp = require.context('@/components', true, /\.vue$/)

reqComp.keys().forEach(file => {
  const compConfig = reqComp(file)
  const compName = file
    .replace(/^\.\//, '')
    .replace(/\.\w+$/, '')
    .replace(/\//g, '-')
    .toLowerCase()
  Vue.component(compName, compConfig.default || compConfig)
})

Afterwards, import that file into your layout .vue file.

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

Encountered an error when attempting to access the property "addOption" on an undefined object

Every time I try to implement search functionality, I keep running into this error: "cannot read property 'addOption' of undefined in JavaScript selectize." I have confirmed that my result array does contain data. This is my JavaScript code: ...

How to retrieve static attributes while declaring an interface

class A { public static readonly TYPE = "A"; } interface forA { for: A.TYPE } I am facing an issue while trying to access A.TYPE from the forA interface in order to perform type guarding. The error I encounter is: TS2702: 'A' only refe ...

Blending an HTML jQuery toggle

Is there a way to make the current headline fade out while simultaneously fading in a new one when switching to the next div using a jQuery .html switch? Check out the codepen example: https://codepen.io/balke/pen/JpNNve $(window).scroll(function() { ...

Styling text in JavaScript and CSS with colored fonts and underlines

I am looking to customize the CSS for the font style. <div id="a" onmouseover="chbg('red','b')" onmouseout="chbg('white','b')">This will change b element</div> <div id="b">This is element b</div ...

Insert item at the end of the box and move all elements upwards

Hello! I'm experimenting with creating something using javascript's createElement method. My goal is to achieve an effect similar to this image: https://i.stack.imgur.com/itKUK.gif Currently, my code is functional, but the animation goes from to ...

saving numeric values and text to a document using node.js

In my node.js application, I am working with files to read and write numbers and strings. Currently, I am using fs.writeFileSync(myPath, value); where the value can be either a number or a string. When I try to read the file using fs.readFileSync(myPa ...

I can't seem to figure out which of these 4 statements is free of syntax errors

Can you identify which code block does not contain a syntax error? Out of the 4 options below, one of them is free from any syntax mistakes. alert("hello "+3+" times); alert("hello "+3 times); alert("hello +3+ times"); alert("hel ...

What causes the difference in behavior of nodejs function arguments when explicitly called?

As I refactor my nodejs application to improve code readability, I encountered an issue when calling a function directly. The following code works perfectly: router.route('/').get(({ query }, res, next) => { ItemsLogic.getItems(query) .the ...

Set the minimum height of a section in jQuery to be equal to the height of

My goal is to dynamically set the minimum height of each section to match the height of the window. Here is my current implementation... HTML <section id="hero"> </section> <section id="services"> </section> <section id="wo ...

Efficiently organizing items within a list on Ionic

Currently, I have an ion-list structured as follows: <ion-list *ngFor = "let chat of Chats"> <ion-item (click) = "openChat(chat.id)"> <ion-label> <h2> {{chat.username}} </h2> ...

Unable to call Ionic component function using ref in Vue3

I'm attempting to utilize the closeSlidingItems method of the IonList element in order to automatically close the sliding item after clicking a button that appears from behind once the item is slid to the right. My approach involved referencing IonLi ...

The curly braces in AngularJS are failing to display the values on the HTML page

After trying various articles and solutions to different questions, I am still unable to resolve my issue. I am working on a blank ionic project and it is running smoothly in my browser using ionic serve without any errors. However, instead of displaying ...

Merge two scripts together

I'm facing an issue with my frontend due to having two separate scripts in my Vue.js component class. How can I merge them into one cohesive script? If the problem stems from elsewhere, what could it be? <script> import GETUSER from "@/graphql/ ...

Tips for retrieving information from a highstock chart

Imagine I have a sample highstock chart on my website, similar to the one at this link. Is there a way to extract the data from the chart itself, even if the data used for creating the chart is not accessible to others? <img src="http://www.highchart ...

The Vue application is unable to expand to 100% height when using a media query

Hello everyone, I'm currently using my Vue router for multiple pages, and I'm facing an issue where setting the height of the main container to 100% within this media query is not working as expected: @media screen and (min-width: 700px) { #sig ...

The error message "Encountered an issue when trying to access properties of undefined (reading 'getState')" was

Currently working on developing an app that utilizes a Django backend and React frontend. The goal is to enable users to log in, receive refresh and access tokens from Django, store the token in local storage, and redirect authenticated users to a static p ...

Having trouble importing ES modules using the "node" command in my Nuxt project

Within my nuxt project, I have utilized serverMiddleware defined in nuxt.config.js like so: serverMiddleware: ['~/api'] All the files located in the api directory are equipped with import and export statements and they function flawlessly when ex ...

When a user clicks on a specific element's id, the image will rotate accordingly

When the elements in ul are clicked, the image rotates. The default position of the image is already rotated by a certain number of degrees, and on each click, it rotates to the desired value. This was achieved using the following code: $("#objRotates"). ...

Using AngularJS to pass objects dynamically through ng-include

Below is an example that is fully functional, except for one issue. When using node.title within the HTML code, everything works as expected. However, when trying to use {{node.title}} within the ng-include file, it does not function properly. Only the g ...

Using the EJS if-else statement to iterate through an array of items

I am working on rendering API data using Express (REST) and EJS (template engine) based on the value of the "status" field. If any item in the array has a status other than "CLOSED," it should be displayed, but if all items have the status set to "CLOSED," ...