Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional import to switch implementations

I have node.js application written in TypeScript and I need to switch between two interface implementations based on the config file. Currently I have this code which seems to be working.

"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 bad gut feeling about that (mainly because of the mixing require and import for loading modules). Is there some other way how to achieve implementation switching based on config file without importing both modules?

like image 697
Lukas Pirkl Avatar asked Mar 10 '16 14:03

Lukas Pirkl


2 Answers

If you want to keep the client-code for your Something class clean, you can move the conditional importing to a single file. You can 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 just import Something:

import Something from './Something/index';
like image 133
Calvin Belden Avatar answered Oct 02 '22 22:10

Calvin Belden


I can see nothing wrong with your approach. In fact lines like

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

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

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

So they are effectively identical and you are not mixing different module loading techniques.

like image 31
Amid Avatar answered Oct 02 '22 23:10

Amid