How to globally register components in Vuejs located in subdirectories

I've been working through the documentation on the Vuejs website to understand how to globally register vue components.

In my setup, I've specified that the components folder's relative path is ./global and I've set it to look into subfolders (though by default it was set to false). Despite these settings, it still doesn't seem to search in subfolders.

To investigate further, I used console.log to check for the keys of the components but it only displayed components located in the global (root) folder.

https://v2.vuejs.org/v2/guide/components-registration.html

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

const requireComponent = require.context(
  // The relative path of the components folder
  './global',
  // Whether or not to look in subfolders
  true,
  // The regular expression used to match base component filenames
  /[A-Z]\w+\.(vue|js)$/
)

console.log(requireComponent.keys())

requireComponent.keys().forEach(fileName => {
  // Retrieve component configuration
  const componentConfig = requireComponent(fileName)

  // Obtain PascalCase name of the component
  const componentName = upperFirst(
    camelCase(
      // Remove the leading `./` and extension from the filename
      fileName.replace(/^\.\/(.*)\.\w+$/, '$1')
    )
  )

  // Register the component globally
  Vue.component(
    componentName,
    // Look for the component options on `.default`, if it exists
    // This will be present if the component was exported with `export default`
    // If not, fallback to the module's root.
    componentConfig.default || componentConfig
  )
})

Answer №1

Here is the code snippet I used to accomplish the desired outcome:

const requireComponent = require.context(
  // Path to the components folder
  './global',
  // Include subfolders
  true,
  // Regular expression to match component filenames
  /[A-Z]\w+\.(vue|js)$/
)

requireComponent.keys().forEach(fileName => {
  // Get component configuration
  const componentConfig = requireComponent(fileName)
  // Get PascalCase component name
  const componentName = Vue._.upperFirst(
    Vue._.camelCase(
      fileName
        .split('/')
        .pop()
        .replace(/\.\w+$/, '')
    )
  )

  // Register component globally
  Vue.component(
    componentName,
    // Check for component options on `.default`, use module's root if not present
    componentConfig.default || componentConfig
  )
})

Ensure that all files in the global folder are capitalized and have either a .vue or .js extension.

Also, ensure that your main.js (or equivalent bootstrap file) is located one directory above the global folder. For example:

/src main.js /global

With this setup, a file like ProgressBar.vue will be globally accessible in all components as simply ProgressBar:

<ProgressBar></ProgressBar>

Answer №2

@Anson C

const requireComponent = require.context(
  // The relative path of the components folder
  './global',
  // Whether or not to look in subfolders
  true,
  // The regular expression used to match base component filenames
  /[A-Z]\w+\.(vue|js)$/
)

The code provided here functions exactly as intended. It will retrieve all files in the subfolders as expected (for example, for ./Base/BaseInput.vue, it will return BaseInput). However, in order to import these files, you must also include the corresponding path.

// Get PascalCase name of component
  const componentName = upperFirst(
    camelCase(
      // Strip the leading `./` and extension from the filename
      fileName.replace(/^\.\/(.*)\.\w+$/, '$1')
    )
  )

Currently, this only imports ./BaseInput, which is an incorrect path. It should be ./Base/BaseInput.

Therefore:

// Get PascalCase name of component
  const componentName = Vue._.upperFirst(
    Vue._.camelCase(
      fileName
        .split('/')
        .pop()
        .replace(/\.\w+$/, '')
    )
  )

This code provides the perfect path to both the file and the folder it is located in.

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

The method .makePerspective() in THREE.Matrix4 has been updated with a new signature. Make sure to refer to the documentation for more information

Attempting to run a functional three.js code using release 119 of three.js (instead of r79) has resulted in an error being thrown by the previously functioning code: THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check ...

Warning: Node 125008 has reached the maximum number of listeners, indicating a potential memory leak in the EventEmitter

(node:125008) MaxListenersExceededWarning: There may be a memory leak with EventEmitter as 11 ready listeners have been added. Try using emitter.setMaxListeners() to raise the limit Can anyone provide guidance on how to increase the listener event count? ...

Tips for incorporating JavaScript into elements that have been modified using jQuery's .html() method

Consider this example: $('#key').on('click', function(){ $('.task').html("<button id='key'>Button</button>"+Date()); }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.j ...

Tips for transferring a dataTable from C# code behind to jQuery

I am trying to pass a string as a table of data from C# code behind to jQuery using two functions: C# [System.Web.Services.WebMethod(EnableSession = true)] public static List<ListItem> GetImageArray(string AccNo) { string result = string.Empty; ...

What steps should I take to fix the WCF / AJAX problem I'm encountering? (Receiving a 400 Bad Request error

I am relatively new to AJAX and JavaScript, so I appreciate your patience. My goal is to use an AJAX call to send a new user object to a WCF C# method, which will then create the user in a SQL server database. Subsequently, the C# method will send back a v ...

Tips for exploring electron without launching additional windows

Is there a way to navigate between HTML pages within the same window without opening multiple windows in Electron? ...

What is the best way to incorporate Vuetify into a new application?

Recently, I developed a new app using Vue and I decided to integrate Vuetify as the framework. After executing the npm install vuetify --save command, Vuetify was added to the app successfully. However, when I tried to use it, the CSS button colors were no ...

Jquery plugin experiencing a malfunction

I am encountering an issue with my custom plugin as I am relatively new to this. My goal is to modify the properties of div elements on a webpage. Here is the JavaScript code I am using: (function($) { $.fn.changeDiv = function( options ) { var sett ...

Building a Many-to-Many Relationship in Node.js Using Sequelize.js

As I utilize the sequelize node.js module to structure schema in Postgres SQL, I have defined two schemas for Project and my users. Project Schema module.exports = function(sequelize, DataTypes) { var project = sequelize.define('project', { ...

What is the best approach to dynamically implement useReducer in code?

Take a look at the repository here: https://github.com/charles7771/ugly-code In the 'Options' component, I am facing an issue where I am hardcoding different names for each reducer case instead of dynamically generating them for a form. This app ...

How can I extract unique dates from my database in Laravel and display them without duplicates?

Currently, I am actively involved in a Laravel Jetstream Project that utilizes Inertia.js. This particular project is focused on displaying the GPS history of cars tracked using a tracker and then plotting them on a map to visualize the complete geo-histo ...

Is it necessary to include async/await in a method if there is already an await keyword where it is invoked?

Here are the two methods I have written in Typescript: async getCertURL(pol: string): Promise<string> { return await Api.getData(this.apiUrl + pol + this.certEndpoint, {timeout: 60000}).then( (response) => { return response.data.certUR ...

Tips for waiting for an event from a specific element in Playwright

Is there a way to await an event on a specific element using Playwright? Similar to page.waitForEvent, but focusing only on a particular element rather than the entire page. More information can be found in the documentation. ...

What is the timing for when the SignalR connection is terminated from the browser?

Currently, I am developing a chat application using SignalR 2.0, like many others in the same field. In my Win8.1 application, when the user closes the application, the hub receives the OnDisconnected event and removes the user from the list on the hub. A ...

Spin the AngularJS icon in a complete 360-degree clockwise rotation

Hey there! I'm new to Angular and I'm trying to create a button that will make an icon inside rotate 360 degrees when clicked. Right now, the entire button is rotating instead of just the element inside it. I want only the "blue square" to rotate ...

What are the best tools to develop a browser-based 2D top-down soccer simulation?

I'm looking to create a 2D top-down soccer simulation game for web browsers using modern technologies and without the need for additional plugins like Flash or Silverlight, making it compatible with mobile devices as well. The game will be AI-controll ...

What is the best way to conceal an element solely in live production environments?

Is there a way in my Angular code to specifically target the PROD environment? <div *ngIf="environment !== 'prod'" class="col-6"> <button class="btn btn-primary text-white add-photo" (cli ...

Implementing the map function in ReactJS to showcase data on the user interface

I seem to be facing an issue while attempting to utilize an array of data to display a <ul> element. Despite the console.log's working correctly in the code provided below, the list items fail to show up. <ul className="comments"&g ...

Modifying selections within a select box generated dynamically using JQuery

Looking for help on how to delegate to a static DOM element in my current situation. I need to create a dynamic select box .userDrop when .addNew is clicked, and then have the user select an option from #secDrop, triggering a change event that calls the da ...

Tips for populating a DOJO Select using JSON data that includes various parameters instead of just label and value

I am trying to populate a DOJO select element with JSON data where the item values for value are expressed by the code property. Here's an example of what I have: //require dojo Select var select = new Select({ name: "stateSelect", ...