[英]Webpack require array of requirements (require dynamic string)
我想在webpack中要求一个要求列表。 一旦我用变量或常量替换require函数的字符串参数,它就不能再注入需求了。
这是一个完美的例子:
const angular = require('angular');
但是一旦我将其更改为以下内容,它就不再起作用了:
const angularString = 'angular';
const angular = require(angularString);
我的目标是拥有一个静态的依赖项列表并逐个注入它们,如下所示:
const angularDependencies = [
'angular-socket-io',
'angular-ui-router'
];
for(var i = 0; i < angularDependencies.length; i++) {
require(angularDependencies[i]);
}
这是我收到的错误消息:
WARNING in ./app/app.js
Critical dependencies:
14:1-14 the request of a dependency is an expression
@ ./app/app.js 14:1-14
WARNING in ./app ^\.\/.*$
Module not found: Error: a dependency to an entry point is not allowed
@ ./app ^\.\/.*$
WARNING in ./app ^\.\/.*$
Module not found: Error: a dependency to an entry point is not allowed
@ ./app ^\.\/.*$
这不会起作用,因为WebPack是一个构建工具,可以分析您的源文件以进行锻炼包含的内容。 它不会运行您的代码来查看它的作用。 这意味着您的代码只能在require语句中包含字符串。
如果您想以这种方式编写代码,那么请查看SystemJS而不是WebPack。
Webpack支持动态需求,但您需要告诉它如何使用上下文查找文件。 您可以在需要模块之前尝试类似的东西:
var req = require.context(".", true, /^angular-.+$/)
req("angular-thing")
如果这样的东西不起作用,你需要在代码中使用不同的方法,因为WebPack需要知道在编译时包含在bundle中的模块。
创建angularDependencies.js
:
module.exports = [
'angular-socket-io',
'angular-ui-router'
];
然后将其添加到webpack.config.js
条目部分 。 它应该如下所示:
require('./src/angularDependencies').concat(['./myApp.js'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.