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

What causes vue.js to be unable to function within HTML documents?

I was trying to integrate Vue.js into my Spring Boot application. Even though the build seemed successful, I am encountering issues with getting the Vue component to work properly. Here is a code snippet of my simple component, MenuBar.vue: <template> ...

Is it possible to utilize a CSV file to dictate which images should be utilized on my website as a guide?

I'm currently working on my website's gallery and have a collection of over 60 images. I'm exploring ways to streamline the process of displaying these images by having the website read their names from a CSV file instead of manually coding ...

How can I set the sphere's rotation in THREE.js to be absolute instead of cumulative?

I have encountered an issue with setting the rotation of a Three.js sphere to an absolute value. Whenever I use rotateY, the value I apply gets added or subtracted from the previous rotation instead of setting a new absolute rotation. In a similar scenari ...

Tips for retaining JWT token in local storage even after a page refresh

I am currently working on implementing a login/logout feature and utilizing the context API to manage functions such as storing tokens in local storage and removing them upon logging out. However, I have encountered an issue where the token stored in local ...

Iterating through a jQuery function to increment value

I have encountered an issue while trying to calculate the total value from an array of form fields. The problem lies in how the final value is being calculated on Keyup; it seems that only the last inputted value is being added instead of considering all t ...

What is the best way to add a character within a YouTube JSON link?

Fetching json data from a link, the youtube format in the link is http:\/\/www.youtube.com\/watch?v=UVKsd8z6scw. However, I need to add the letter "v" in between this link to display it in an iframe. So, the modified link should appear as ht ...

Employing the 'this' keyword for iterating over a jQuery selector

Having an issue with a jQuery code that logs the values of input fields on button click: Tried using forEach method on inputs but getting an error saying it's not a function. Why is this happening? $("#submit").click(e => { e.preventDefault(); ...

Oops! The Vue router has encountered a RangeError due to exceeding the maximum call stack

I'm currently working on implementing a login feature using Vue.js. Initially, I started with the following code: However, encountered an error message stating "Range Error: Maximum call stack size exceeded." ...

typescript: the modules with relational paths could not be located

As part of a migration process, I am currently converting code from JavaScript to TypeScript. In one of my files 'abc.ts', I need to import the 'xyz.css' file, which is located in the same directory. However, when I try to import it usi ...

The current version of 'buffer' is outdated. To resolve this issue, please upgrade to v4.9.2 or higher

Having some trouble integrating aws-amplify and aws-amplify-react modules into my application. After running: npm install --save aws-amplify aws-amplify-react I encountered multiple warning messages related to missing or deprecated dependencies. Althoug ...

Can you please elaborate on the concept of type coercion in JavaScript?

I've come across information stating that when comparing an object with a number, type-coercion occurs. ToPrimitive is called on the object which then invokes valueOf and, if necessary, toString. However, I'm struggling to understand how this pro ...

Is there a way for me to receive notifications about errors while piping to gulp browserify?

I am leveraging browserify to utilize npm modules in my front end code, and I use gulp for my build tasks. The setup is functioning smoothly: const browserify = require('gulp-browserify'); gulp.task('js', ['clean'], function ...

Template for Vue.js Component Registration

Below is a simple Vue component example: const MyComponent = Vue.component('my-component', { data () { // data here... }, methods: { // methods here... }, template: '<p>Hello, world !!!</p>' }); I ...

JavaScript in fullscreen mode for Internet Explorer

I'm trying to make sure that this code snippet... $('#gatewayDimmer').width($('html').width()); $('#gatewayDimmer').height($('html').height()); $('#gatewayDimmer').css('display','block& ...

Validating dropdown lists with Jquery

Custom Dropdownlist: <div class="col-md-2"> <div class="form-group"> <label for="field-3" class="control-label">Priority</label> <select id="lstpriority" class="custom-selectpicker" data-live-search="true" da ...

Testing the functionality of an Express Rest API with Mocha unit tests

I have just started diving into the world of unit testing. While I've been successful in running simple tests such as "adding two numbers and checking if the result is greater than 0", my goal now is to develop a REST API using Test-Driven Development ...

Whenever I try to import a directory that contains modules, Webpack encounters an error

I am currently in the process of developing a small npm library to streamline API interaction. Here is an overview of my folder structure... dist/ index.js src/ index.js endpoints/ endpoint1.js package.json webpack.config.js Inside my src/index ...

Adding a new element with Jquery when a dropdown option is selected

What is causing this issue to not function properly? <script> $(document).ready(function(){ $('#custom_field option').click(function(){ $('#custom_field_input').append('<tr><td></td> ...

A guide on converting array values to objects in AngularJS HTML

Here is my collection of objects: MyCart = { cartID: "cart101", listProducts : [ {pid:101, pname:"apple", price: 200, qty:3}, {pid:102, pname:"banana", price: 100, qty:12} ] } I have incorporated a form in ...

The attribute 'use' is not found within the data type 'typeof...', and the property 'extend' is not present within the data type 'typeof'

As I embark on building my very first Vue app using TypeScript, I find myself facing a frustrating issue: Property 'xxx' does not exist on type 'typeof. Despite my efforts to research similar problems, none of the suggested solutions have pr ...