Skip to content

Instantly share code, notes, and snippets.

@eirikb
Created May 24, 2017 19:24
Show Gist options
  • Star 37 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save eirikb/6f2e47d6806b8be6e67129b13ae05820 to your computer and use it in GitHub Desktop.
Save eirikb/6f2e47d6806b8be6e67129b13ae05820 to your computer and use it in GitHub Desktop.
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
Copy link

Nice, thanks!

@MartinMuzatko
Copy link

With this, I get the following error:

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

@maheshshah196
Copy link

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
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