Reputation: 58442
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?
Upvotes: 1
Views: 1326
Reputation: 26281
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);
});
Upvotes: 3
Reputation: 5270
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.
Upvotes: 0