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?
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);
});
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.