typescript node.js express routes separated files best practices

后端 未结 1 1947
长情又很酷
长情又很酷 2021-01-02 03:58

using Express in a Node project along with Typescript what would be the \"best practices\" for express.Router.

example directory structure

|directory         


        
相关标签:
1条回答
  • 2021-01-02 04:59

    Answer

    In NodeJS each file is a module. Declaring variables does not pollute the global namespace. So you don't need to use the good old IIFE trick to properly scope variables (and prevent global pollution / collision).

    You would write:

      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;
    

    More on modules

    https://basarat.gitbooks.io/typescript/content/docs/project/modules.html

    My reaction

    0 讨论(0)
提交回复
热议问题