[英]Webpack dynamic require throwing error
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
在webpackMissingModule
Is there any way I can use a variable for that require? 有什么方法可以使用变量来满足要求吗?
Take a look at Webpack's Context Module . 看一下Webpack的Context Module 。
Apparently, when you attempt to dynamicly require a module, Webpack will try to parse the input expression to a context
. 显然,当您尝试动态地需要模块时,Webpack将尝试将输入表达式解析为
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. 当名称是动态变量时,Webpack无法确定要捆绑的模块。 You can't use variable name in
require
. 您不能在
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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.