我有一个问题。
关于从 Vue 2 => Vue 3 和 Nuxt 2 => Nuxt 3 的迁移,以及 Vite 的新使用, 不再支持 require() 函数。
我必须根据语言迁移这个需要文件的函数,但我发现不可能在 JavaScript 函数中使用“导入”这句话。
在这种情况下我可以采用哪种解决方案?
export function getTranslationsByKey(key) {
const locales = LOCALES.map((locale) => {
const file = require('./' + locale.iso + '/index.js')
return {
[locale[key]]: { ...file },
}
})
您可以使用动态导入代替
require
这是一个例子:
export async function getTranslationsByKey(key) {
const locales = await Promise.all(
LOCALES.map(async (locale) => {
const file = await import(`./${locale.iso}/index.js`);
return {
[locale[key]]: { ...file },
};
})
);
return locales;
}