Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
Why is await import(pathVariable) not working whilst await import('./file.json') works fine? pathVariable contains the same string

I am trying to load a json dynamically based on a string variable, however, when I try to use even the most basic variable that contains a string, I get an error, whereas when I use the string it works just fine

const configLoader = async () => {
    const pathVariable = './file.json';
    const fileName = 'file';

    const configFile = await import('./file.json'); // Works!
    const configFile = await import(pathVariable); // Doesn't work!
    const configFile = await import(`./${fileName}.json`); // Doesn't work!
}

The error

Invalid call at line 34: import(pathVariable)
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are using a tool, such as WebPack, which resolves imports at build-time.

It require that you pass string literals since the value of variables generally can't be known until run-time.

See WebPack's documentation:

Dynamic expressions in import()

It is not possible to use a fully dynamic import statement, such as import(foo). Because foo could potentially be any path to any file in your system or project.

The import() must contain at least some information about where the module is located. Bundling can be limited to a specific directory or set of files so that when you are using a dynamic expression - every module that could potentially be requested on an import() call is included. For example, import(./locale/${language}.json`) will cause every .json file in the ./locale directory to be bundled into the new chunk. At run time, when the variable language has been computed, any file like english.json or german.json will be available for consumption.

// imagine we had a method to get language from cookies or other storage
const language = detectVisitorLanguage();
import(`./locale/${language}.json`).then((module) => {
  // do something with the translations
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda