2017-02-05 59 views
2

Node7.4.0/ES6 /打字稿2.1.5/WebStorm 2016.3ES6 *打字稿:找不到命名空间

就行了: 出口默认heroRoutes.router;

我得到:TS2503找不到命名空间“heroRoutes”创造它和init() 这可能是错的后

感谢反馈

HeroRouter.ts

import {Router, Request, Response, NextFunction} from 'express'; 
const Heroes = require('../data'); 

export class HeroRouter { 
    router: Router; 

    /** 
    * Initialize the HeroRouter 
    */ 
    constructor() { 
     this.router = Router(); 
     this.init(); 
    } 

    /** 
    * GET all Heroes. 
    */ 
    public getAll(req: Request, res: Response, next: NextFunction) { 
     res.send(Heroes); 
    } 

    /** 
    * GET one hero by id 
    */ 
    public getOne(req: Request, res: Response, next: NextFunction) { 
     let query = parseInt(req.params.id); 
     let hero = Heroes.find(hero => hero.id === query); 
     if (hero) { 
      res.status(200) 
       .send({ 
        message: 'Success', 
        status: res.status, 
        hero 
       }); 
     } 
     else { 
      res.status(404) 
       .send({ 
        message: 'No hero found with the given id.', 
        status: res.status 
       }); 
     } 
    } 

    /** 
    * Take each handler, and attach to one of the Express.Router's 
    * endpoints. 
    */ 
    init() { 
     this.router.get('/', this.getAll); 
     this.router.get('/:id', this.getOne); 
    } 

} 

// Create the HeroRouter, and export its configured Express.Router 
let heroRoutes = new HeroRouter(); 
heroRoutes.init(); 

export default heroRoutes.router; 

回答

3
const heroRouter = new HeroRouter(); 
const router = heroRouter.router; 
export default router; 

这样做的原因是,你不能导出一个合格的名称。 模块的导出被绑定到一个称为模块名称空间对象的特殊对象。其中一个原因是,如果合格的输出是合法的,则语义将会令人惊讶,因为更新变量heroRouter的实例成员router的值不会更新导出的绑定(此处名为default)的值。

+1

谢谢阿an,这就是要点!我也不应该忘记在两个常量声明之间插入heroRouter.init()... 这里有什么意思?是否在出口默认参数... 任何链接到一些文件?... – erwin

+0

确实有一些上下文丢失,我更新了我的答案 –

+0

至于'init'方法,我会摆脱它,并把构造函数中的所有逻辑。允许在无效状态下创建对象是一种不好的做法。它会导致bug,就像我的例子中的问题。 –