Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject dependencies into ES2015 module

Is it possible to inject dependencies into ES2015 modules like in other programming languages like C# or Java? If I import a module I create a hard dependency to it and can not change it later at runtime. For example I have following JavaScript code:

import Animal from './dog';

class Person {
  feedAnimal() {
    new Animal().feed();
  }
}

I am importing the dog module. But what if I want to change it to a cat? At the moment I have to modify line 1 by hand but in some situations I want it configurable from the outside so that under some conditions there should be a cat and under some other conditions it should be a cat. All that things that can be done with classical dependency injection.

I know there are some DI frameworks out there like Scatter, Electrolyte, Wire and so on but unfortunately most of them require some special syntax and are not made for ES2015 modules.

like image 347
LongFlick Avatar asked Aug 14 '15 10:08

LongFlick


2 Answers

You cannot dynamically define dependencies. 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.

like image 113
sdgluck Avatar answered Nov 19 '22 10:11

sdgluck


You can use inject-loader to achieve this if you are bundling with Webpack.

Hopefully this helps someone who stumbles upon this old post.

like image 40
user8605837 Avatar answered Nov 19 '22 10:11

user8605837