使用Webpack快速路由HMR

时间:2017-05-14 00:32:10

标签: express typescript webpack webpack-hmr

我正在尝试使用快速应用程序让HMR在服务器端工作,我看到一些奇怪的行为。我的简单测试项目;

index.ts

let httpListener: Server = null;

let AppServer = require('./AppServer').default;
const port = Config.serverPort;

if (process.env.NODE_ENV === 'dev') {
    if ((module as any).hot) {
        (module as any).hot.addDisposeHandler((data: any) => {
            httpListener.close();
            AppServer = require('./AppServer').default;
        });
        console.log('index.ts', (module as any).hot.dependencies);
        (module as any).hot.accept((err: any) => {
            console.log('HMR Error', err);
        });
    }
}

httpListener = AppServer.app.listen(port, (error: Error) => {
    if (error) {
        console.error(error);
    } else {
        console.info(`Listening on port ${port}.`);
    }
});

AppServer.ts

class AppServer {
    public app: express.Application = express();

    constructor() {    
        this.app.use('/api', (new ApiRouter()).router);
    }
}

export default new AppServer();

和ApiRouter.ts

export class ApiRouter {
    public router: express.Router = express.Router();

    constructor() {
        this.router.use('/auth', (new AuthRouter()).router);

        this.router.get('/', (req, res) => {
            res.json({success: true});
        });
    }
}

Webpack捆绑正确,HMR报告正在更新的模块。如果我在index.ts中更改了一些代码,那么这些更改才会生效。但是,当我将{success: true}翻转为{success: false}时,我会看到HMR更新;

[HMR] Updated modules:
[HMR]  - ./src/server/AppServer.ts
[HMR]  - ./src/server/index.ts
[HMR]  - ./src/server/api/ApiRouter.ts

但是当我点击端点时,我会回来{success: true}。因此,尽管HMR似乎正在做正确的事情,但代码并未在运行时更改。我怀疑我错过了关于module.hot.accept如何在这里工作的基本信息,但我无法弄清楚我哪里出错了。

有没有人让这个工作正常?

0 个答案:

没有答案