Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 546
Marco Faustinelli Avatar asked Jul 24 '16 10:07

Marco Faustinelli


2 Answers

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';
like image 83
Bogdan Savluk Avatar answered Sep 24 '22 16:09

Bogdan Savluk


Try this:

export default router;
like image 32
LevCode Avatar answered Sep 25 '22 16:09

LevCode