My goal was to create a file that would
- Require all of the JS files in a directory that didn’t end in
_test.js
- Do a
module.exports
equal to an array of module names returned from those view files.
I thought I had it with this:
// 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 is working as intended
#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.
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.
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;