9

I want to import all components that reside in a folder. Is there a way to do this without having to create an index.js file and individually importing and then exporting each component? Is there a bulk way?

Folder structure:

src/templates/ Foo.vue Bar.vue Baz.vue src/App.vue 

In App.vue I would like to import all components in templates folder:

import * as Templates from './templates' 

The above doesn't work unless I place an index.js file in ./templates folder:

// Do I have to import each component individually? // Can I just bulk import all these? import Default from './Default' import Home from './Home' import Agency from './Agency' import CaseStudies from './CaseStudies' import Contact from './Contact' export { Default, Home, Agency, CaseStudies, Contact } 
4
  • 1
    Maybe babel-wildcard could help npmjs.com/package/babel-plugin-wildcard ? Commented Apr 20, 2018 at 8:50
  • Maybe you could have phrased it as "Import wild card single file component Vue files does not work". People who downvoted it probably don't know that is a specific file type. I upvoted it, it's a valid question. Commented Apr 20, 2018 at 9:37
  • I think this works if you use Templates.Foo or Templates.Bar Commented Nov 6, 2019 at 8:12
  • This question is similar to: Is it possible to import *.vue files in a folder?. If you believe it’s different, please edit the question and clarify how it’s different. Commented Dec 2, 2024 at 5:33

3 Answers 3

5

You can do bulk import

import { Default, Home, Agency, CaseStudies, Contact } from "./templates/*"; 

with babel-plugin-wildcard

.babelrc

 "plugins": [ "transform-vue-jsx", "transform-runtime", ["wildcard", { "exts": ["js", "es6", "es", "jsx", "javascript", "vue"] }] ], 
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe you can use require.context,you can read vuejs official doc: https://v2.vuejs.org/v2/guide/components-registration.html

Comments

-3

You can use async import():

import fs = require('fs');

and then:

fs.readdir('./someDir', (err, files) => { files.forEach(file => { const module = import('./' + file).then(m => m.callSomeMethod(); ); // or const module = await import('file') }); }); 

2 Comments

This only works if you are using vue server side. In the browser you don't have access to the fs module
Yes this is for server side only (Node.js.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.