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