在没有 import() 的情况下有条件地使用导入
Using imports conditionally without import()
这听起来可能很奇怪,但我需要以有条件的方式使用导入而不使用 await import()
。
这是一个简单的例子,假设我有这段代码:
import { en } from './langs/en.json';
import { fr } from './langs/fr.json';
我想有条件地使用 en
或 fr
。
类似于:
const selectedLang = "en";
const lang = global[selectedLang];
有办法吗?
我知道在浏览器下所有全局变量都存储在 window
对象中。
但是这个库不是这样的。
您可以为此使用普通的旧 require
:
const selectedLang = "en";
const lang = require(`./langs/${selectedLang}.json`);
这听起来可能很奇怪,但我需要以有条件的方式使用导入而不使用 await import()
。
这是一个简单的例子,假设我有这段代码:
import { en } from './langs/en.json';
import { fr } from './langs/fr.json';
我想有条件地使用 en
或 fr
。
类似于:
const selectedLang = "en";
const lang = global[selectedLang];
有办法吗?
我知道在浏览器下所有全局变量都存储在 window
对象中。
但是这个库不是这样的。
您可以为此使用普通的旧 require
:
const selectedLang = "en";
const lang = require(`./langs/${selectedLang}.json`);