簡體   English   中英

Webpack-Require.context-如何在目錄中要求除“ _test.js”以外的所有.js文件?

[英]Webpack - Require.context -How to require all .js files except `_test.js` in a directory?

我的目標是創建一個文件

  1. 要求目錄中未以_test.js結尾的所有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不支持正則表達式負向隱藏,並且我對正則表達式的了解還不夠。

好的,我能夠使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM