jjzjj

javascript - Webpack require array of requirements(需要动态字符串)

coder 2024-07-29 原文

我想在 webpack 中要求一个需求列表。一旦我将 require 函数的字符串参数替换为变量或常量,它就无法再注入(inject)需求。

这是一个完美的例子:

const angular = require('angular');

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

const angularString = 'angular';
const angular = require(angularString);

我的目标是拥有一个静态的依赖项列表,并像这样一个一个地注入(inject)它们:

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。

https://github.com/systemjs/systemjs

关于javascript - Webpack require array of requirements(需要动态字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37628720/

有关javascript - Webpack require array of requirements(需要动态字符串)的更多相关文章

随机推荐