Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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`)
    })
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading