Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
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}`;
  }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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]
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!