I have this file in ../../src/routes/index.js
:
JavaScript
x
10
10
1
import Router from '../../my_modules/nexus/Router.js'
2
3
Router.get('/', function (request, response) {
4
response.send('welcome home')
5
})
6
7
Router.get('/about', function (request, response) {
8
response.send('about me')
9
})
10
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
1
14
14
1
import express from 'express'
2
import Router from './Router.js'
3
4
const app = express()
5
6
import '../../src/routes/index.js'
7
// import('../../src/routes/index.js')
8
9
console.log(Router.routes)
10
11
app.listen(3000, function () {
12
console.log(`App listening on http://localhost:3000`)
13
})
14
This works:
JavaScript
1
3
1
import '../../src/routes/index.js'
2
// console.log(Router.routes) has the routes!
3
This does not work:
JavaScript
1
3
1
import('../../src/routes/index.js')
2
// console.log(Router.routes) is empty!
3
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
1
13
13
1
import express from 'express'
2
import Router from './Router.js'
3
4
const app = express()
5
6
import('../../src/routes/index.js').then(function () {
7
console.log(Router.routes)
8
9
app.listen(3000, function () {
10
console.log(`App listening on http://localhost:3000`)
11
})
12
});
13