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

ssc*_*ep3 6 javascript require webpack

我想在webpack中要求一个要求列表.一旦我用变量或常量替换require函数的字符串参数,它就不能再注入需求了.

这是一个完美的例子:

const angular = require('angular');
Run Code Online (Sandbox Code Playgroud)

但是一旦我将其更改为以下内容,它就不再起作用了:

const angularString = 'angular';
const angular = require(angularString);
Run Code Online (Sandbox Code Playgroud)

我的目标是拥有一个静态的依赖项列表并逐个注入它们,如下所示:

const angularDependencies = [
    'angular-socket-io',
    'angular-ui-router'
];

for(var i = 0; i < angularDependencies.length; i++) {
    require(angularDependencies[i]);
}
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误消息:

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 ^\.\/.*$
Run Code Online (Sandbox Code Playgroud)

Dav*_*haw 5

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

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

https://github.com/systemjs/systemjs


小智 4

Webpack 支持动态 require 但你需要告诉它如何使用context来查找文件。在需要模块之前,您可以尝试类似的操作:

var req = require.context(".", true, /^angular-.+$/)
req("angular-thing")
Run Code Online (Sandbox Code Playgroud)

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