Muzietto Muzietto - 4 months ago 52
Node.js Question

Importing/exporting the Express router using ES6 import + export keywords and Babel

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 via e.g.:

app.use('/', indexRoute);


where
indexRoute
is set at the top of the file with:

import { indexRoute } from './routes/index_route';


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
?

Answer

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';