【问题标题】:Using imports conditionally without import()有条件地使用导入而不使用 import()
【发布时间】:2021-12-25 23:43:35
【问题描述】:

这听起来可能很奇怪,但我需要有条件地使用导入,而不使用 await import()

这是一个简单的例子,假设我有这个代码:

import { en } from './langs/en.json';
import { fr } from './langs/fr.json';  

我想有条件地使用enfr
比如:

const selectedLang = "en";
const lang = global[selectedLang]; 

有没有办法做到这一点?
我知道在浏览器下所有的全局变量都存储在window对象中。
但是这个库不是这样的。

【问题讨论】:

    标签: javascript import module


    【解决方案1】:

    您可以为此使用普通的旧 require

    const selectedLang = "en";
    const lang = require(`./langs/${selectedLang}.json`);
    

    【讨论】:

    • 这行得通!
    猜你喜欢
    • 2021-12-27
    • 2014-09-15
    • 2022-10-16
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多