Require.context: inline RegExp works, var RegExp doesn't

I am trying to load my tests conditionally if SPEC Env is declared:

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

This works great. Now if i do that

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

This does not work at all, and all files in. / Match (the './tests' parameter is ignored)

What am I missing? I want the third parameter of the require.context function to be a RegExp object, so I can build RegExp using a variable.

EDIT 1

This does not work:

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

To check this, you can edit the tests.webpack.js file of this project: https://github.com/erikras/react-redux-universal-hot-example

You need to allow the SPEC variable to go through 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
    })

and run: npm run test

or: SPEC = t npm run test

+4
1

Sokra - github, , , require.context, . /thing/ , new RegExp(thing)

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

+1

All Articles