我的目标是创建一个文件
- 需要目录中所有不以
_test.js
结尾的 JS 文件 - 执行一个
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/