【问题标题】:Webpack - Require.context -How to require all .js files except `_test.js` in a directory?Webpack - Require.context - 如何在目录中要求除 `_test.js` 之外的所有 .js 文件?
【发布时间】:2017-06-04 09:32:18
【问题描述】:

我的目标是创建一个文件

  1. 要求目录中的所有 JS 文件不以 _test.js 结尾
  2. 做一个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 不支持正则表达式负后视,而且我没有足够的正则表达式知识来做到这一点。

【问题讨论】:

  • 它为我提供了足够的信息来解决我的问题。谢谢!
  • 欢迎您。在这种情况下以重复的形式关闭您的问题
  • 在下面查看我的答案。你认为它足够不同,值得坚持吗?我觉得对于任何使用 webpack 和 index.views.js 约定的人来说,这是一个流行的用例,这很流行。

标签: javascript angularjs webpack


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2017-01-21
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    相关资源
    最近更新 更多