同构TypeScript /要求

时间:2019-05-08 12:04:30

标签: typescript

我有4个文件

Settings.ts

type sayType = () => string;

export interface SettingsModule {
    sayEnv: sayType;
}

settings.node.ts

import { SettingsModule } from '@/core/persistant/Settings';

export const mod: SettingsModule = {
    sayEnv: sayInternalEnv,
};

function sayInternalEnv(): string {
    return 'Node';
}

settings.browser.ts

import { SettingsModule } from '@/core/persistant/Settings';

export const mod: SettingsModule = {
    sayEnv: sayInternalEnv,
};

function sayInternalEnv(): string {
    return 'Browser';
}

settings.impl.ts

import { SettingsModule } from '@/core/persistant/Settings';

let settingsModule: SettingsModule;

if (window.indexedDB) {
    // tslint:disable-next-line:no-var-requires
    const m = require('./settings.browser') as { mod: SettingsModule };
    settingsModule = m.mod;
} else {
    // tslint:disable-next-line:no-var-requires
    const m = require('./settings.node') as { mod: SettingsModule };
    settingsModule = m.mod;
}

export const sayEnv = settingsModule.sayEnv;

整个过程就像一个咒语,但是我的问题是这样使用require真的安全吗?

我的意思是-对于如此小的文件,它可以正常工作,但是require总是同步的吗?我可以确定始终设置“ sayEnv”吗?

0 个答案:

没有答案