有条件导入切换实现

Luk*_*rkl 7 node.js typescript

我有用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();
...
Run Code Online (Sandbox Code Playgroud)

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

Ami*_*mid 5

我认为你的做法没有错.实际上就像是

import { config } from "../config";
Run Code Online (Sandbox Code Playgroud)

当将目标commonjs编译为以下javascript(ES6)时:

const config = require('../config');
Run Code Online (Sandbox Code Playgroud)

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


Cal*_*den 5

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

/Something
    RealSomething.ts
    FakeSomething.ts
    index.ts
Run Code Online (Sandbox Code Playgroud)

在你的 index.ts 中,你可以有以下内容:

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

const Something = config.useFakeSomething ?
    require('./FakeSomething').FakeSomething :
    require('./RealSomething').RealSomething;

export default Something;
Run Code Online (Sandbox Code Playgroud)

在您的客户端代码中,您只需导入Something:

import Something from './Something/index';
Run Code Online (Sandbox Code Playgroud)


Met*_*bre 5

使用import()函数的现代答案:

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

let Something;
if (config.useFakeSomething) {
    Something = (await import("./FakeSomething")).FakeSomething;
} else {
    Something = (await import("./RealSomething")).RealSomething;
}
...
let s = new Something();
s.DoStuff();
...
Run Code Online (Sandbox Code Playgroud)

请记住,import() 是非阻塞的,因此如果后面的代码需要 import() 的结果,则需要添加等待。