导出变量“router”已从外部模块使用或正在使用名称“Router”但无法命名

时间:2017-01-25 09:03:26

标签: node.js express typescript module

在使用Typescript 2直接导出路由器时,在多个文件中定义嵌套路由器的通用构造中,以及代码抛出后的@types/express@4.0.35定义

error TS4023: Exported variable 'router' has or is using name 'Router' from external module 
         "[...]/node_modules/@types/express-serve-static-core/index" but cannot be named.

取自basarat's answer

的示例
import * as express from "express";

// import sub-routers
import * as adminRouter from "./admin/admin";
import * as productRouter from "./products/products";

let router = express.Router();

// mount express paths, any addition middleware can be added as well.
// ex. router.use('/pathway', middleware_function, sub-router);

router.use('/products', productRouter);
router.use('/admin', adminRouter);

// Export the router
export = router;

1 个答案:

答案 0 :(得分:9)

解决方案是明确注释路由器变量(TypeScript/issues/5711#issuecomment-161194656)。

以下代码可以使用(请注意let router: express.Router = express.Router()

import * as express from "express";

import * as adminRouter from "./admin/admin";
import * as productRouter from "./products/products";

let router: express.Router = express.Router();

router.use('/products', productRouter);
router.use('/admin', adminRouter);

// Export the router
export = router;