Skip to content
Advertisement

Dynamic import is not working the same as regular import

I have this file in ../../src/routes/index.js:

JavaScript

I am trying to import this file via node because I want to create my own simple routing API class.

Here is the code I’m trying to get working:

JavaScript

This works:

JavaScript

This does not work:

JavaScript

I need the 2nd example to work because I want to dynamically import a bunch of files from the routes directory. How do I get this to work using the import() syntax?

Advertisement

Answer

Dynamic import returns a Promise which you need to await (with await in an async function or by calling then) before running any code dependent on the imported module.

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement