Conditional imports to switch implementations

I have a node.js application written in TypeScript and I need to switch between the two interface implementations based on the configuration file. I currently have this code that seems to work.

"use strict"; import { config } from "../config"; let Something; if (config.useFakeSomething) { Something = require("./FakeSomething").FakeSomething; } else { Something = require("./RealSomething").RealSomething; } ... let s = new Something(); s.DoStuff(); ... 

But I have a bad feeling about this (mainly due to mixing , import is also required to load the modules). Is there any other way how to achieve a switch of implementation based on a configuration file without importing both modules?

+6
source share
3 answers

I see nothing wrong with your approach. Actually strings like

 import { config } from "../config"; 

When commonjs targeting is compiled to the following javascript (ES6):

 const config = require('../config'); 

Thus, they are virtually identical, and you do not mix different methods of loading modules.

+3
source

If you want the client code for your Something class to be clean, you can move conditional imports to a single file. You may have the following directory structure for your Something module:

 /Something RealSomething.ts FakeSomething.ts index.ts 

And in your index.ts you can have the following:

 import { config } from '../config'; const Something = config.useFakeSomething ? require('./FakeSomething').FakeSomething : require('./RealSomething').RealSomething; export default Something; 

And in your client code, you can simply import Something :

 import Something from './Something/index'; 
0
source

You can do it as follows:

 let moduleLoader:any; if( pladform == 1 ) { moduleLoader = require('./module1'); } else { moduleLoader = require('./module2'); } 

and then

 if( pladform === 1 ) { platformBrowserDynamic().bootstrapModule(moduleLoader.module1, [ languageService ]); } else if ( pladform === 2 ) { platformBrowserDynamic().bootstrapModule(moduleLoader.module2, [ languageService ]); } 
0
source

All Articles