Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Load all Vue components from a given folder, no need for an "index.js"-file
const req = require.context('./components/', true, /\.(js|vue)$/i);
req.keys().map(key => {
const name = key.match(/\w+/)[0];
return Vue.component(name, req(key))
});
@sagalbot

This comment has been minimized.

Copy link

sagalbot commented Oct 21, 2017

Nice, thanks!

@MartinMuzatko

This comment has been minimized.

Copy link

MartinMuzatko commented Aug 9, 2018

With this, I get the following error:

[Vue warn]: Failed to mount component: template or render function not defined.
@maheshshah196

This comment has been minimized.

Copy link

maheshshah196 commented Dec 1, 2018

Whenever importing vue component using require statement instead of import use 'default' key, see below code

const req = require.context('./components/', true, /\.(js|vue)$/i); req.keys().map(key => { const name = key.match(/\w+/)[0]; return Vue.component(name, req(key).default) });

@xorik

This comment has been minimized.

Copy link

xorik commented Jun 19, 2019

For typescript:

// Load every component from _common
const req = require.context('./_common/', false, /\.(js|vue)$/i)
for (const key of req.keys()) {
  const name = key.match(/\w+/)![0]
  Vue.component(name, req(key).default)
}

Change false to true if you need subfolders

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.