I have an old test project originally built with Express 2.X. I am moving it to Express 4.x and trying to insert Babel 6.x to experiment with ES6 features server-side.
The update to Express 4.x went OK. The original app works fine. The problems arise when I start adding ES6 features.
In particular, I want to substitute all require
and module.export
instructions with ES6 import {...} from...
and export {...}
.
Problem: I seem unable to import routes from external files into the main app.js
file.
My app.js
loads routes like so:
import { indexRoute } from './routes/index_route';
app.use('/', indexRoute);
Inside index_route.js
I have:
"use strict";
import express from 'express';
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index_view', { title: 'Express' });
});
export { router }
This source code is OK for Babel, but node complains at startup:
Router.use() requires middleware function but got a undefined
I have two files like index_route.js
, each one for a group of routes, and AFAIS they both import + modify + export the same router object. In any case, the export+import done using ES6 keywords returns undefined
.
What am I doing wrong? Am I using the ES6 keywords on the wrong objects? Am I using obsolete instructions to configure the routes inside app.js
?
The problem is that you are exporting router
as named export router
, but trying to import it as indexRoute
.
You should either rename your export:
export { router as indexRoute }
or change your import:
import { router as indexRoute } from './routes/index_route';
Try this:
export default router;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With