Embedding Dependencies in ES2015 Module

Is it possible to embed dependencies in ES2015 modules, for example, in other programming languages ​​such as C # or Java? If I import a module, I create a hard dependency for it and cannot change it later at runtime. For example, I have the following JavaScript code:

import Animal from './dog'; class Person { feedAnimal() { new Animal().feed(); } } 

I import a dog module. But what if I want to change it to a cat? At the moment, I need to change line 1 manually, but in some situations I want it to be configured externally, so under certain conditions there should be a cat, and in some other conditions it should be a cat. Everything you can do with classic dependency injection.

I know that there are some DI frameworks, for example Scatter , Electrolyte , Wire , etc., but, unfortunately, most of them require special syntax and are not made for ES2015 modules .

+7
javascript ecmascript-6 dependency-injection es6-module-loader
source share
3 answers

I switched to SystemJS . With SystemJS you can do dynamic import, for example System.import('foo').then(() => console.log('Loaded));

Another advantage is that the system will become the new module loading system for the standard ECMAScript module.

-one
source share

You cannot dynamically determine dependencies. Take a look at this question and its accepted answer :

Question: Import name of ES6 variable in node.js?

Answer: Not with the import statement. import and export are defined in such a way that they are statically analyzed, therefore they cannot depend on information about the runtime.

+2
source share

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

Hope this helps someone who stumbled upon this old post.

+2
source share

All Articles