Webpack需要一系列要求(需要动态字符串)

时间:2016-06-04 09:40:42

标签: javascript webpack require

我想在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 个答案:

答案 0 :(得分:5)

这不会起作用,因为WebPack是一个构建工具,可以分析您的源文件以进行锻炼包含的内容。它不会运行您的代码来查看它的作用。这意味着您的代码只能在require语句中包含字符串。

如果您想以这种方式编写代码,那么请查看SystemJS而不是WebPack。

https://github.com/systemjs/systemjs

答案 1 :(得分:4)

Webpack支持动态需求,但您需要告诉它如何使用contexts查找文件。 在需要模块之前,您可以尝试类似的东西:

var req = require.context(".", true, /^angular-.+$/)
req("angular-thing")

如果类似的东西不起作用,你需要在代码中使用不同的方法,因为WebPack需要知道在编译时你的包中包含哪些模块。

答案 2 :(得分:2)

创建angularDependencies.js

module.exports = [
    'angular-socket-io',
    'angular-ui-router'
];

然后将其添加到webpack.config.js entry section。它应该是这样的:

require('./src/angularDependencies').concat(['./myApp.js'])
相关问题