ES6 * Typescript:找不到命名空间

时间:2017-02-05 08:01:07

标签: node.js typescript ecmascript-6

Node7.4.0 / ES6 / Typescript 2.1.5 / WebStorm 2016.3

在线:     导出默认的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;

1 个答案:

答案 0 :(得分:5)

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

原因是您无法导出限定名称。 模块的导出绑定到称为模块命名空间对象的特殊对象。一个原因是,如果合格的导出是合法的,那么语义将会令人惊讶,因为更新变量router的实例成员heroRouter的值不会更新导出的绑定的值(此处命名为{{ 1}})。