Webpack要求一个要求的数组(要求动态字符串)

6
我希望在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 ^\.\/.*$
3个回答

4
那样做是行不通的,因为 WebPack 是一种构建工具,它会分析你的源文件以确定要包含什么内容。它不会运行你的代码来查看它的作用。这意味着你的代码只能在 require 语句中包含字符串。
如果你想以这种方式编写代码,请考虑使用 SystemJS 而不是 WebPack。 https://github.com/systemjs/systemjs

4
Webpack支持动态导入但是需要告诉它如何使用contexts查找文件。在要求模块之前,您可以尝试类似以下的操作:
var req = require.context(".", true, /^angular-.+$/)
req("angular-thing")

如果类似那样的方法不能正常工作,您需要在代码中采取不同的方法,因为 WebPack 需要在编译时知道要包含哪些模块。

2
创建 angularDependencies.js:
module.exports = [
    'angular-socket-io',
    'angular-ui-router'
];

然后将其添加到webpack.config.js入口部分。它应该是这样的:

require('./src/angularDependencies').concat(['./myApp.js'])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接