1

The code environment is browser. bundle tool is webpack. I have a router.js file like:

import foo from './views/foo.vue'
import bar from './views/bar.vue'
import zoo from './views/zoo.vue'

//use foo, bar, zoo variables

I've many '.vue' files to import like this under views folder. Is there a programmatical way to auto import all [name].vue as local variable [name]? So when I add or remove a vue file in views, I don't need to manually edit router.js file. this one seems a little dirty.

for (let name of ['foo', 'bar', 'zoo']) {
    global[name] = require(`./views/${name}.vue`)
}
1
  • Not with import - because import is processed at compile time, not run time, there is no code you can write to affect it. But since require is just a regular function you can write code to control it like you posted. It is not dirty at all. Since require is a regular function it is perfectly OK to treat it as a regular function and call it inside a loop Commented Aug 29, 2020 at 8:48

2 Answers 2

2

Nope, that's it. You have a choice between dynamic import and automation, or explicit coding and type-checking / linting.

Unfortunately, it's one or the other. The only other way to do it is meta-programming, where you write code to write your code.

So you generate the import statements in a loop like that, and write the string into the source file, and use delimiting comment blocks in the source file to identify and update it.

Sign up to request clarification or add additional context in comments.

Comments

2

The following works for me with webpack and vue. I actually use it for vuex and namespaces. Hope it helps you as well.

// imports all .vue files from the views folder (first parameter is the path to your views)
const requireModule = require.context('./views', false, /\.vue$/);

// create empty modules object
const modules = {};

// travers through your imports
requireModule.keys().forEach(item => {

  // replace extension with nothing
  const moduleName = item.replace(/(\.\/|\.vue)/g, '');
  
  // add item to modules object
  modules[moduleName] = requireModule(item).default;
});

//export modules object
export default modules;

1 Comment

thanks. though not a direct answer, I apply your method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.