Webpack-Require.context-如何在目录中要求除"_test.js"以外的所有.js文件? [英] Webpack - Require.context -How to require all .js files except `_test.js` in a directory?

查看:59
本文介绍了Webpack-Require.context-如何在目录中要求除"_test.js"以外的所有.js文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是创建一个文件

My goal was to create a file that would

  1. 要求目录中所有未以 _test.js
  2. 结尾的JS文件
  3. 执行一个 module.exports 等于从那些视图文件返回的模块名称的数组.
  1. Require all of the JS files in a directory that didn't end in _test.js
  2. Do a module.exports equal to an array of module names returned from those view files.

我以为我拥有了它:

// Automagically crawls through this directory, finds every js file inside any
// subdirectory, removes test files, and requires the resulting list of files,
// registering the exported module names as dependencies to the myApp.demoApp.views module.
var context = require.context('.', true, /\/.*\/.*\.js$/);
var moduleNames = _.chain(context.keys())
  .filter(function(key) {
      console.log(key, key.indexOf('_test.js') == -1);
    return key.indexOf('_test.js') == -1;
  })
  .map(function(key) {
      console.log("KEY", key);
    return context(key)
  })
  .value();
module.exports = angular.module('myApp.demoApp.views', moduleNames).name;

#2正常工作

#1不幸的是我很幼稚.过滤掉模块名称后,这仍然需要所有带有 _test 的文件,因此测试文件最终将存储在我的内置代码中.

#1 Unfortunately I was naive. While the module names are filtered out, this still requires all of the files with _test so the test files end up in my built code.

我试图通过更新正则表达式来解决此问题,但JS不支持正则表达式负向隐藏,并且我对正则表达式的理解不足以解决此问题.

I tried to fix this by updating the regex but JS doesn't support regex negative-look-behind and I'm not regex savvy enough to do it without that.

推荐答案

好的,我能够使用Slava.K注释中的答案来回答我的问题.这是下面的最终代码.我必须在正则表达式中包含(?!.* index),因为此代码本身包含了 index.views.js .

Ok, I was able to use the answer in Slava.K's comment to answer my question. Here's the final code below. I had to include (?!.*index) in the regex because this code was including itself index.views.js.

var context = require.context('.', true, /^(?!.*index).*\/(?!.*test).*\.js$/);

var moduleNames = _.chain(context.keys())
  .map(function(key) {
    return context(key)
  })
  .value();

module.exports = angular.module('myApp.demoApp.views', moduleNames).name;

这篇关于Webpack-Require.context-如何在目录中要求除"_test.js"以外的所有.js文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆