[英]Webpack require array of requirements (require dynamic string)
我想在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 ^\.\/.*$
這不會起作用,因為WebPack是一個構建工具,可以分析您的源文件以進行鍛煉包含的內容。 它不會運行您的代碼來查看它的作用。 這意味着您的代碼只能在require語句中包含字符串。
如果您想以這種方式編寫代碼,那么請查看SystemJS而不是WebPack。
Webpack支持動態需求,但您需要告訴它如何使用上下文查找文件。 您可以在需要模塊之前嘗試類似的東西:
var req = require.context(".", true, /^angular-.+$/)
req("angular-thing")
如果這樣的東西不起作用,你需要在代碼中使用不同的方法,因為WebPack需要知道在編譯時包含在bundle中的模塊。
創建angularDependencies.js
:
module.exports = [
'angular-socket-io',
'angular-ui-router'
];
然后將其添加到webpack.config.js
條目部分 。 它應該如下所示:
require('./src/angularDependencies').concat(['./myApp.js'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.