How to import files inside functions when using Vite (Vue 3, Nuxt 3)

202 Views Asked by At

I have a question.

Regarding migration from Vue 2 => Vue 3 and Nuxt 2 => Nuxt 3, and the new use of Vite, the function require() is no more supported.

I have to migrate this function which is requiring files according to the language, but I see that it is not possible o use the sentence 'import' inside a javascript function.

Which would be the solution that I could apply in this case?

    export function getTranslationsByKey(key) {
      const locales = LOCALES.map((locale) => {
        const file = require('./' + locale.iso + '/index.js')
    
        return {
          [locale[key]]: { ...file },
        }
  })
1

There are 1 best solutions below

0
Waleed Tariq On

You can use dynamic imports instead of require

Here's an example:

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;
}