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

标签 javascript angularjs webpack

我的目标是创建一个文件

  1. 需要目录中所有不以 _test.js 结尾的 JS 文件
  2. 执行一个 module.exports 等于从这些 View 文件返回的模块名称数组。

我以为我已经做到了:

// 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 不支持正则表达式负向后查找,而且我对正则表达式的了解不够,无法在没有它的情况下做到这一点。

最佳答案

好的,我可以使用 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;

关于javascript - Webpack - Require.context - 如何要求目录中除 `_test.js` 之外的所有 .js 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41745947/

相关文章:

node.js - 在 Electron 和 Webpack 中使用 node require

javascript - Ajax 总是给出积极的值(value)。如何纠正呢?

javascript - anchor 标记重新加载页面而不是在 IE 中处理 onclick

javascript - 在不破坏 MVC 范式的情况下使用 ng-model (或其他解决方案)

angularjs - 解决 routeprovider 中的多个 promise

angularjs - 您的一些测试进行了整页重新加载 - 运行 Jasmine 测试时出错

javascript - 延迟脚本和放在页面主体末尾的脚本有什么区别?

javascript - 在 <option> 中存储 id(或其他数据)

css - 如何将 flag-icon-css 与 angular2/4 一起使用?

javascript - 如何存储配置文件并使用 React 读取它