Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

require.context: inline RegExp works, var RegExp does not

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

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

This is perfectly working. Now If I do this

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

This is not working at all and all files in ./ are matched (the './tests' parameter get ignored)

What am I missing? I want the third parameter of the require.context function to be a RegExp object so I can construct the 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 test 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 pass 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

like image 573
rolele Avatar asked Jul 14 '16 04:07

rolele


2 Answers

4 years later, facing the same issue. Check the warning message for require.context

https://webpack.js.org/guides/dependency-management/#requirecontext

like image 125
filoscoder Avatar answered Oct 22 '22 04:10

filoscoder


Sokra answered this on the webpack github saying that the regexp passed to require.context must be statically analyzable. That's why passing /thing/ works but not new RegExp(thing)

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

like image 3
Jon Avatar answered Oct 22 '22 05:10

Jon