简体   繁体   中英

How to programmatical import module to local scope of nodejs?

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`)
}

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM