简体   繁体   中英

Reference an imported module with string variable

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?

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM