Skip to content
Advertisement

Dynamic import is not working the same as regular import

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

import Router from '../../my_modules/nexus/Router.js'

Router.get('/', function (request, response) {
    response.send('welcome home')
})

Router.get('/about', function (request, response) {
    response.send('about me')
})

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:

import express from 'express'
import Router from './Router.js'

const app = express()

import '../../src/routes/index.js'
// import('../../src/routes/index.js')

console.log(Router.routes)

app.listen(3000, function () {
    console.log(`App listening on http://localhost:3000`)
})

This works:

import '../../src/routes/index.js'
// console.log(Router.routes) has the routes!

This does not work:

import('../../src/routes/index.js')
// console.log(Router.routes) is empty!

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.

import express from 'express'
import Router from './Router.js'

const app = express()

import('../../src/routes/index.js').then(function () {
    console.log(Router.routes)

    app.listen(3000, function () {
        console.log(`App listening on http://localhost:3000`)
    })
});
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement