是否可以像 C# 或 Java 等其他编程语言一样将依赖项注入(inject) ES2015 模块?如果我导入一个模块,我就会对它产生硬依赖,并且以后在运行时无法更改它。例如,我有以下 JavaScript 代码:
import Animal from './dog';
class Person {
feedAnimal() {
new Animal().feed();
}
}
我正在导入狗模块。但是如果我想把它变成一只猫呢?目前我必须手动修改第 1 行,但在某些情况下我希望它可以从外部进行配置,以便在某些情况下应该有一只猫,而在其他一些情况下它应该是一只猫。经典依赖注入(inject)可以完成的所有事情。
我知道有一些 DI 框架,比如 Scatter , Electrolyte , Wire等等,但不幸的是,它们中的大多数都需要一些特殊的语法,并且不是为ES2015 modules制作的.
最佳答案
您不能动态定义依赖项。 See this question and its accepted answer :
Question: ES6 variable import name in node.js?
Answer: Not with the import statement. import and export are defined in such a way that they are statically analyzable, so they cannot depend on runtime information.
关于javascript - 将依赖项注入(inject) ES2015 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32008340/