Webpack - Require.context - 如何在目录中要求除`_test.js`之外的所有.js文件?

时间:2017-01-19 15:41:26

标签: javascript angularjs webpack

我的目标是创建一个

的文件
  1. 要求目录中的所有JS文件都不以_test.js
  2. 结尾
  3. 使module.exports等于从这些视图文件返回的模块名称数组。
  4. 我以为我有这个:

    // 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的所有文件,因此测试文件最终会出现在我的构建代码中。

    我试图通过更新正则表达式来解决这个问题,但是JS并不支持正则表达式负面观察,而且我没有足够的正则表达式来做到这一点。

1 个答案:

答案 0 :(得分:3)

好的,我能够使用Slava.K的评论回答我的问题。这是下面的最终代码。我必须在正则表达式中包含(?!.*index),因为此代码包含自己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;
相关问题