[英]Webpack - Require.context -How to require all .js files except `_test.js` in a directory?
我的目标是创建一个文件
_test.js
结尾的所有JS文件 module.exports
等于从那些视图文件返回的模块名称数组。 我以为是这样的:
// 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.