1

I have the following code snippet.

import {English as en} from 'languages/en.js'
import {Spanish as es} from 'languages/es.js'

console.log(this.lang) // es

I'm trying to call the corresponding imported module using the this.lang string. But not sure how I can call that module.

window[this.lang]

wouldn't work.

Any suggestions?

user1012181
  • 8,648
  • 10
  • 64
  • 106

1 Answers1

0

Create an object and look up lang in that:

  const result = { es, en }[this.lang];

Working with the global scope (aka window) can get you into real trouble, thats why it is considered an antipattern (and all those ES 6 features, let, const, import enforce that by making "global variables" not leak to the global scope, therefore you can't access them on window).

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151