【问题标题】:Typescript dynamically selecting which import to useTypescript 动态选择要使用的导入
【发布时间】:2022-01-13 20:44:06
【问题描述】:

如果我有一个名为en_GB.ts的文件

import { first_name } from '../lib/locales/en';

export const en_GB = {
  first_name,
};

然后我有 index.ts 类似

import { en_GB } from './locale/en_GB';

我知道这将使文件可供使用,但如果我让用户设置他们的语言环境并将其设置为 en_GBthis.self.locale 的变量。

有没有办法使用this.self.locale 来使用来自en_GB 导入的数据?

这是index.ts的完整代码

import { Name } from './lib/name';
import { en_GB } from './locale/en_GB';

interface SelfTypes {
  locale?: any;
  locales?: any;
  localeFallback?: any;
  name?: any;
}

export class Deets {
  greeting: string;
  public self: SelfTypes = {};
  name: any;

  constructor(options: any, name: string) {
    this.greeting = name;

    this.self = {
      locale: options.locale || {},
      locales: options.locales || 'en',
      localeFallback: options.localeFallback || 'en',
    };

    console.log('this.self');
    console.log([this.self.locale]);
    console.log('this.self');

    this.name = new Name(this.self);
  }

  greet() {
    return `Hello, ${this.greeting}`;
  }
}

【问题讨论】:

    标签: javascript typescript ecmascript-6


    【解决方案1】:

    顶级导入仅在文件加载时处理一次。那么,如果有人以某种方式更改了他们的语言环境怎么办?


    您可以使用dynamic import,但这会有所不同。

    const localData = await import(`./locale/${localeName}`)
    

    请注意,它返回一个承诺,因为加载该文件是异步的。所以这不会进入文件顶部的导入中。


    但是,根据您捆绑此代码的方式,该方法可能会给您带来问题。由于在编译时所有可能的路径都不可知,因此捆绑器可能很难知道捆绑包中包含哪些文件。

    所以最好有一个包含所有语言环境的导入,并且您可以简单地从对象中选择作为键:

    import locales from './locale';
    
    const enGBorWhatever = locales[myLocaleName]
    

    【讨论】:

      猜你喜欢
      • 2022-01-26
      • 2018-05-15
      • 2018-11-19
      • 1970-01-01
      • 2019-12-18
      • 2019-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多