Search code examples
node.jsdynamicimport

Import from a dynamic file name


I am trying to import from a file with a name passed from console:

let vis = process.argv[2];
import settings from `./${vis}.json`;

However, I am getting an error message:

import settings from ./${vis}.json;

                 ^^^^^

SyntaxError: Unexpected template string at Loader.moduleStrategy (node:internal/modules/esm/translators:147:18) at async link (node:internal/modules/esm/module_job:64:21)

I tried preparing the name in advance:

let vis = `./${process.argv[2]}.json`;
import settings from vis;

But got an error message:

import settings from custID;

                  ^^^^^^

SyntaxError: Unexpected identifier at Loader.moduleStrategy (node:internal/modules/esm/translators:147:18) at async link (node:internal/modules/esm/module_job:64:21)

It seems like only strings are accepted for the location. How can I import from a dynamic name?


Solution

  • You can not specify a module name that is constructed dynamically with the standard import syntax because of the static nature of the ESM module system - the dependency graph is actually built ahead of actual code execution, at which point the module names should be known.

    But you can do this with the dynamic import() syntax - which consists in a function that returns a promise that resolves to the module object.

    import(dynamicName)
      .then(function(module){
        // Use module here.
      })
    

    I am not sure that you would be able to straight-up import a .json file that way though - unless your build system or execution environment is set up to handle some appropriate kinds of code transform. This is because a .json file doesn't qualify as an ESM module.