有条件导入切换实现

时间:2016-03-10 14:53:36

标签: node.js typescript

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

return

但我对此有直觉(主要是因为加载模块的混合需要导入)。有没有其他方法如何在不导入两个模块的情况下实现基于配置文件的实现切换?

4 个答案:

答案 0 :(得分:5)

我认为你的做法没有错。事实上像

这样的行
import { config } from "../config";

当定位commonjs时会编译为以下javascript(ES6):

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

因此它们实际上是完全相同的,并且您没有混合使用不同的模块加载技术。

答案 1 :(得分:1)

如果要保持Something类的客户端代码清洁,可以将条件导入移动到单个文件中。您可以为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';

答案 2 :(得分:1)

你可以这样做:

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 ]);
}

答案 3 :(得分:0)

除了上面的正确答案外,如果您需要对单个文件夹中的许多文件进行此切换,则可以使用引用正确文件夹的符号链接(在Windows中不可用),因此代码保持干净

例如,这种方法非常适合在实际代码和存根之间切换