require.context:内联RegExp有效,var RegExp没有

rol*_*ele 7 javascript commonjs

如果声明SPEC Env,我试图有条件地加载我的测试:

var context = null
if (process.env.SPEC) {
  context = require.context('./tests', true, /.*?SearchInput.*/);
} 
context.keys().forEach(context);
Run Code Online (Sandbox Code Playgroud)

这非常有效.现在,如果我这样做

var context = null
if (process.env.SPEC) {
  var c = /.*?SearchInput.*/;
  context = require.context('./tests', true, c);
} 
context.keys().forEach(context);
Run Code Online (Sandbox Code Playgroud)

这根本不起作用,并且./中的所有文件都匹配('./tests'参数被忽略)

我错过了什么?我希望require.context函数的第三个参数是一个RegExp对象,所以我可以使用一个变量构造RegExp.

编辑1

这不起作用:

var context = null
if (process.env.SPEC) {
  var c = new RegExp(/.*?SearchInput.*/);
  context = require.context('./tests', true, c);
} 
context.keys().forEach(context);
Run Code Online (Sandbox Code Playgroud)

要测试这个,你可以编辑这个项目的tests.webpack.js文件:https: //github.com/erikras/react-redux-universal-hot-example

您需要允许SPEC变量通过webpack

  new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('test'),
        SPEC: JSON.stringify(process.env.SPEC || null)
      },
      __CLIENT__: true,
      __SERVER__: false,
      __DEVELOPMENT__: true,
      __DEVTOOLS__: false  // <-------- DISABLE redux-devtools HERE
    })
Run Code Online (Sandbox Code Playgroud)

并运行:npm run test

或:SPEC = t npm run test

Jon*_*Jon 3

Sokra 在 webpack github 上回答了这个问题,说传递给 require.context 的正则表达式必须是可静态分析的。这就是为什么传递/thing/有效但无效的原因new RegExp(thing)

https://github.com/webpack/webpack/issues/4772