【问题标题】:Conditional import to switch implementations切换实现的条件导入
【发布时间】:2016-06-25 11:56:26
【问题描述】:

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

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

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

【问题讨论】:

    标签: node.js typescript


    【解决方案1】:

    我看不出你的方法有什么问题。事实上像

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

    定位commonjs时会编译成下面的javascript(ES6):

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

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

    【讨论】:

      【解决方案2】:

      如果您想保持 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';
      

      【讨论】:

      • 但这将始终加载两个模块,不是吗?我无法在开发环境中加载 RealSomething 模块,因为它正在初始化不存在的特殊硬件。
      • 是的,你是对的。我会更新我的答案。我认为在 TypeScript 模块中使用 require 来支持这种动态行为没有任何问题。如果您切换到不同的模块加载器,就会出现问题,但这应该很少见。
      • 计算机科学基本定理再次提供了解决方案。喜欢它!
      【解决方案3】:

      你可以这样做:

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-15
          • 1970-01-01
          • 2017-11-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-07-07
          • 1970-01-01
          相关资源
          最近更新 更多