Typescript dynamically selecting which import to use
If I have a file called en_GB.ts
import { first_name } from '../lib/locales/en';
export const en_GB = {
first_name,
};
And then I have index.ts
which has something like
import { en_GB } from './locale/en_GB';
I know this will make the file available for consumption, but if I let the user set their locale and it is set to en_GB
to a variable of this.self.locale
.
Is there a way to use this.self.locale
to use the data from en_GB
import?
this is my full code for 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}`;
}
}
top level imports are only processed once when the file is loaded. So what if someone changes their locale somehow?
You could use a dynamic import but this works differently.
const localData = await import(`./locale/${localeName}`)
Note that returns a promise because loading that file is asynchronous. So this won't go in the imports at the top of the file.
However, depending on how you are bundling this code that approach may cause you problems. Because all possible paths are not knowable at compile time, the bundler may have hard time knowing what files to include in the bundle.
So it's probably better to have one import that has all locales in it, and you can simply select as a key from an object:
import locales from './locale';
const enGBorWhatever = locales[myLocaleName]