javascript - 将依赖项注入(inject) ES2015 模块

标签 javascript dependency-injection ecmascript-6 es6-module-loader

是否可以像 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/

相关文章:

javascript - 如何使用 JavaScript 或 jQuery 在 html 页面中添加文档类型

c# - CaSTLe 依赖注入(inject) 生活方式

javascript - 如何将 Prop 映射到对象值 React Big Calendar

javascript - 使用 Google Maps API 显示标记

javascript - 事件发生后将分数存储在变量中

c# - 使用依赖注入(inject)的现实世界解决方案

spring - 关于spring框架中的多个容器

javascript - 等效于 ES6 生成器的 Function.prototype.apply

javascript - 如何在react-redux中正确更新我的initialState

javascript - jQuery UI 可排序 : determining in what order the items are