简体   繁体   English

如何以编程方式将模块导入nodejs的本地scope?

[英]How to programmatical import module to local scope of nodejs?

The code environment is browser.代码环境是浏览器。 bundle tool is webpack.捆绑工具是 webpack。 I have a router.js file like:我有一个 router.js 文件,例如:

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.我有很多'.vue'文件要像这样在views文件夹下导入。 Is there a programmatical way to auto import all [name].vue as local variable [name] ?是否有一种编程方式可以自动将所有[name].vue作为局部变量[name]导入? So when I add or remove a vue file in views , I don't need to manually edit router.js file.因此,当我在views中添加或删除 vue 文件时,我不需要手动编辑router.js文件。 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.以下适用于 webpack 和 vue。 I actually use it for vuex and namespaces.我实际上将它用于 vuex 和命名空间。 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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