导出Express路由器

导出Express路由器

本文介绍了使用ES6 import + export关键字和Babel导入/导出Express路由器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有一个最初使用Express 2.X构建的旧测试项目.我将其移至Express 4.x,并尝试插入Babel 6.x以在服务器端尝试ES6功能.

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.

对Express 4.x的更新正常.原始应用程序正常运行.当我开始添加ES6功能时,就会出现问题.

The update to Express 4.x went OK. The original app works fine. The problems arise when I start adding ES6 features.

特别是,我想用ES6 import {...} from...export {...}替换所有requiremodule.export指令.

In particular, I want to substitute all require and module.export instructions with ES6 import {...} from... and export {...}.

问题:我似乎无法将路由从外部文件导入到主app.js文件中.

Problem: I seem unable to import routes from external files into the main app.js file.

我的app.js像这样加载路线:

import { indexRoute } from './routes/index_route';
app.use('/', indexRoute);

index_route.js内部,我有:

"use strict";
import express from 'express';
var router = express.Router();

router.get('/', function(req, res, next) {
  res.render('index_view', { title: 'Express' });
});

export { router }

Babel可以使用此源代码,但是节点在启动时会抱怨:

This source code is OK for Babel, but node complains at startup:

Router.use() requires middleware function but got a undefined

我有两个文件,例如index_route.js,每个文件用于一组路由,并且AFAIS都导入,修改和导出同一路由器对象.无论如何,使用ES6关键字完成的export + import都会返回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.

我做错了什么?我在错误的对象上使用ES6关键字吗?我是否使用过时的指令来配置app.js中的路由?

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?

推荐答案

问题是您将router导出为名为export router,但尝试将其导入为indexRoute.

The problem is that you are exporting router as named export router, but trying to import it as indexRoute.

您应该重命名导出:

export { router as indexRoute }

或更改您的导入:

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

这篇关于使用ES6 import + export关键字和Babel导入/导出Express路由器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 11:56