Attempt to efficiently register components automatically on a global scale in Vue by utilizing the powerful combination of Laravel-Mix and Webpack

In my previous projects with Vue, which were based in a Laravel-Mix/Webpack runtime environment, I used to individually register components and views as needed. This was done by importing them and extending Vue:

import BaseButton from './components/BaseButton.vue'
import BaseIcon from './components/BaseIcon.vue'
import BaseInput from './components/BaseInput.vue'

window.base = Vue.extend {
  components: {
    BaseButton,
    BaseIcon,
    BaseInput
  }
}

I would then compile this into a JS file using webpack.mix.js:

const mix = require('laravel-mix');

mix.vue({
        version: 2
    })
        .js('src/js/base.js', 'dist/base_rendered.js')

and include the compiled file within an HTML file using a <script> tag:

<script src="base_rendered.js"></script>
<script>
   new base({
       el: '#base',

    });
</script>

This method worked well for smaller projects, but when I had to migrate a NuxtJS project to the same environment, with over 100 components needing registration, it became cumbersome. That's why I turned to Vue's documentation on automatic global registration of components for help. Here's their example code:

import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

// More code here...

While I understand how this code scans through component files and extracts PascalCase names, I'm struggling with integrating this approach with my current workflow involving webpack.mix.js and script references in HTML. Any guidance or assistance would be greatly appreciated as dealing with over 100 imports/export manually seems daunting to me.

(Additionally, my current setup uses kebab case for referencing components in HTML. Would this remain the same, or do I need to make adjustments? I also have sub-folders structured for different sections of components in my library.)

Answer №1

Oops! I tend to overthink things, but this time it was quite simple. To finalize the logic and export your components list, just create a new Vue instance after setting up the said list and defining the target element:

import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

const requireComponent = require.context(
    './components/',
    true,
    /[A-Z]\w+\.(vue|js)$/
)

requireComponent.keys().forEach(fileName => {
    const componentConfig = requireComponent(fileName)

    const componentName = upperFirst(
        camelCase(
            fileName
            .split('/')
            .pop()
            .replace(/\.\w+$/, '')
        )
    )

    Vue.component(
        componentName,componentConfig.default || componentConfig
    )
})

window.components = Vue.extend({})

With all my components now registered in the extended Vue instance, I can use the same method of calling them in my HTML files as I did before!

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

CSS modified after opening a modal dialog that has loaded external HTML content

Within my ASP.NET MVC project, I am utilizing a tab wizard. On one of the tabs, I trigger a modal dialog by loading HTML content from an external API. However, once I close the wizard and navigate to the next tab, the table style (specifically border color ...

Exploring the Possibilities of Automating Page Navigation with Vue-Router

What is the best way to automatically switch between two pages in a Vue.js application without any user interaction? I want to display the HelloWorld page first and then switch to the myPage page after a few seconds. I believe I need to use the vue-router ...

Having an issue with the 'scroll' event not being disabled in jQuery

Currently, we are encountering an issue with the implementation of a simple hiding menu when scrolling and showing it back once the user stops scrolling. The method .on('scroll') works as expected, but .off('scroll') is not functioning ...

The tag's onclick function that was dynamically created was not triggering in jQuery

I created a web application using jquery mobile and ran into an issue. I am trying to call a function by clicking on a dynamically generated anchor tag, but it's not working and showing an error that the function is not defined. Any assistance on this ...

What is the best method for eliminating script tags from a Magento web store's source code?

Below is the source code for the Magento site's homepage. I am looking to eliminate all JavaScript links from the code: ...

How can we trigger a mutation in Vue.js using the created or mounted hook?

I've encountered an issue in my Vue.js application with the store.js file where I'm setting up a Vuex store. Here's how it looks: import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export const store = new Vue ...

Delayed response of text effects in JQuery on page load

Within my rails app, I have the following code snippet: window.onload = -> $("#mycontainer").typewriter() $("#div1").fadeIn("slow") This code snippet interacts with the following block of content: <blockquote class="pull-left"> < ...

What is the best way to target a child element within a component's parent?

Within the structure of my project, I have a component with a template set up as follows: <template> <div class="referenceparent"> <input v-model="searchterm" type="text" @input="Search" ...

The robots.txt file in Nuxt.js allows for multiple disallow directives for each user agent

With the Nuxt module called nuxt-robots, how can I set up multiple disallow rules per user agent? Currently, my configuration looks like this: robots: () => { return { UserAgent: '*', Disallow: '/search/', Si ...

Having trouble getting the jQuery autocomplete feature to function properly?

On my page, there is a button labeled "Add a Skill." Clicking on this button should trigger the display of an input box where you can enter your skill, another input box for your skill level, and a horizontal slider to select the skill level. In my databa ...

What is the best way to retrieve the current complete URL in a Next.js/Typescript component?

I'm working on a component and I need to retrieve the current full URL. Here's a simplified version of what I have: /** * Share dropdown component */ export const ShareDropdown: React.FC<{ className: string }> = ({ className, }) => { ...

Avoid generating `.d.ts` definition files during the onstorybook build process in a Vite React library project

I am currently developing a component library using react and typescript. I have integrated Vite into my workflow, and every time I build Storybook, the dts plugin is triggered. This has two undesired effects: It generates numerous unnecessary folders an ...

The website is having trouble reading the local json file accurately

Currently, I have developed an HTML site that utilizes JavaScript/jQuery to read a .json file and PHP to write to it. In addition, there is a C++ backend which also reads and writes to the same .json file. My goal is to transmit the selected button informa ...

Designing a Custom Wordpress Extension and Integrating External Scripts

As I dive into the world of WordPress plugin development, I'm seeking guidance from the codex to enhance my skills. Currently, I have a basic plugin that loads a javascript file from a CDN and is supposed to display tooltips. However, I'm facing ...

AngularJS is not showing the dropdown options as expected

I am facing an issue where the dropdown list options are not displaying, even though I am able to fetch the data in the controller but not in HTML. Here is the code snippet: In HTML <select name="nameSelect" id="nameSelect" ng-model="model.name"> ...

Using the Jquery accordion function within google maps is limited to running only one time

After successfully creating a google maps page with markers generated from XML, I encountered an issue. The plan was to display event information in a div when a marker is clicked, along with attaching an accordion to the events data. Although the first cl ...

The copying of array values is not supported by Chromium

While utilizing Webworker to process an array of pixels from Canvas and then assign it back, I encountered a strange behavior. Firefox works flawlessly in this scenario, however, Chromium seems to insert an empty pixel array into the Canvas. Upon further ...

Leveraging the useRoute() function with Vue 3 Composition API and Typescript: [Vue alert]: The injection "Symbol(route location)" was not detected when employing Typescript

Just recently, I upgraded a Vue 2 application that heavily uses Vue Router and TypeScript to Vue 3. During the migration process, I switched a function from reading the route using this.$route in the Options API to using useRoute() in the Composition API. ...

Is there a way to trigger the vue-cli build command automatically when specific files are modified?

One way I can build my JavaScript file is by using the following command: vue build main.js --dist dist --prod --lib While this works, I am looking for a way to automate this process whenever I make changes to my JS or Vue files. I prefer not to rely on ...

Tips for receiving a reply from S3 getObject in Node.js?

Currently, in my Node.js project, I am working on retrieving data from S3. Successfully using getSignedURL, here is the code snippet: aws.getSignedUrl('getObject', params, function(err, url){ console.log(url); }); The parameters used are: ...