简体   繁体   English

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

[英]Webpack require array of requirements (require dynamic string)

I would like to require a list of requirements in webpack. 我想在webpack中要求一个要求列表。 As soon as I replace the string parameter of the require function with a variable or a constant, it cannot inject the requirement anymore. 一旦我用变量或常量替换require函数的字符串参数,它就不能再注入需求了。

Here is a perfectly working example: 这是一个完美的例子:

const angular = require('angular');

But as soon as I change this to the following, it doesnt work anymore: 但是一旦我将其更改为以下内容,它就不再起作用了:

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

My goal is to have a static list of dependencies and inject them one by one, like this: 我的目标是拥有一个静态的依赖项列表并逐个注入它们,如下所示:

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

for(var i = 0; i < angularDependencies.length; i++) {
    require(angularDependencies[i]);
}

This is the error message I got: 这是我收到的错误消息:

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 ^\.\/.*$

That won't work as WebPack is a build tool that analyses you source files to workout what to include. 这不会起作用,因为WebPack是一个构建工具,可以分析您的源文件以进行锻炼包含的内容。 It does not run your code to see what it does. 它不会运行您的代码来查看它的作用。 This means your code can only include strings inside require statements. 这意味着您的代码只能在require语句中包含字符串。

If you want to write your code this way then have a look at SystemJS instead of WebPack. 如果您想以这种方式编写代码,那么请查看SystemJS而不是WebPack。

https://github.com/systemjs/systemjs https://github.com/systemjs/systemjs

Webpack supports dynamic requires but you need to tell it how to find the files using contexts . Webpack支持动态需求,但您需要告诉它如何使用上下文查找文件。 You could try something like that before requiring your modules: 您可以在需要模块之前尝试类似的东西:

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

If something like that doesn't work, you will need to use a different approach in your code because WebPack needs to know what modules to include in your bundle on compile time. 如果这样的东西不起作用,你需要在代码中使用不同的方法,因为WebPack需要知道在编译时包含在bundle中的模块。

Create angularDependencies.js : 创建angularDependencies.js

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

Then add it to webpack.config.js entry section . 然后将其添加到webpack.config.js 条目部分 It should look like this: 它应该如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM