1

I have the following piece of code that works well:

require.ensure(['./core/sample-form.js'], require => {
    require('./core/sample-form.js');  
});

Now if I put that string into a variable:

const ajaxJs = './core/sample-form.js';
require.ensure([ajaxJs], require => {
    require(ajaxJs);  // eslint-disable-line import/no-dynamic-require
});

It throws the following error:

Uncaught (in promise) Error: Cannot find module "." at webpackMissingModule

Is there any way I can use a variable for that require?

c69
  • 19,951
  • 7
  • 52
  • 82
Pete
  • 57,112
  • 28
  • 117
  • 166

2 Answers2

3

Take a look at Webpack's Context Module.

Apparently, when you attempt to dynamicly require a module, Webpack will try to parse the input expression to a context.

Try the following code (haven't tested this):

const ajaxJs = './sample-form.js';
core = require.context('./core', true, /^\.\/.*\.js$/);
require.ensure([], () => {
    core(ajaxJs);
});
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
0

Webpack can't figure out which modules to bundle when the name is dynamic variable. You can't use variable name in require. You'll have to do something like :

require.ensure(['./core/sample-form.js'], require => {
    require('./core/sample-form.js');  // eslint-disable-line import/no-dynamic-require
});

This answer can help.

Ajay Gaur
  • 5,140
  • 6
  • 38
  • 60
  • Surely you should be able to use dynamic requires otherwise there wouldn't be a warning in eslint about it? I may be wrong, but it seems daft to only warn you about it rather than just throw an error if you can't do it? – Pete Nov 20 '17 at 11:52
  • Seems like the use of webpack's context module can do this. As @matias-cicero answered. – Ajay Gaur Nov 20 '17 at 12:02