【问题标题】:Webpack require array of requirements (require dynamic string)Webpack 需要一系列需求(需要动态字符串)
【发布时间】:2016-10-04 08:48:00
【问题描述】:

我想要一份 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 ^\.\/.*$

【问题讨论】:

    标签: javascript webpack require


    【解决方案1】:

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

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

    https://github.com/systemjs/systemjs

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        【解决方案3】:

        创建angularDependencies.js:

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-08-26
          • 2018-05-03
          • 2017-01-20
          • 2020-06-05
          • 2020-11-19
          • 2016-09-27
          • 2017-12-01
          相关资源
          最近更新 更多