有条件的导入来切换实现

我有用TypeScript编写的node.js应用程序,我需要根据configuration文件在两个接口实现之间切换。 目前我有这个代码似乎在工作。

"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(); ... 

但是我对此有不好的直觉(主要是因为加载模块需要混合导入 )。 有没有其他的方式如何实现基于configuration文件切换而不导入两个模块?

我的方法看不出什么错。 其实就是这样的

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

当针对commonjs将被编译为以下JavaScript(ES6):

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

所以他们是完全相同的,你不混合不同的模块加载技术。

如果你想保持你的Something类的客户端代码干净,你可以将条件导入移动到一个文件中。 你可以为你的模块有如下的目录结构:

 /Something RealSomething.ts FakeSomething.ts index.ts 

而在你的index.ts,你可以有以下几点:

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

而在你的客户端代码中,你可以导入Something

 import Something from './Something/index'; 

你可以这样做:

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

接着

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