typescript node.js express routes separated files best practices

荒凉一梦 提交于 2020-01-01 09:15:08

问题


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

example directory structure

|directory_name
  ---server.js
  |--node_modules
  |--routes
     ---index.ts
     |--admin
        ---admin.ts
     |--products
        ---products.ts
     |--authentication
        ---authentication.ts

so inside index.ts it would encapsulate and manage all the sub-routers

    //admin.ts (nested inside of index.ts)
    import * as express from "express";

    export = (() => {
        
        let router = express.Router();
              
        router.get('/admin', (req, res) => {
            res.json({success: true});
        });
        
        return router;
    })();

回答1:


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 🌹

my main question really is, is index.ts (masterRouter file) and it's nested routes that are IIFe's export = (function(){})(); should that be the correct/best way to write typescript modules for routers


(source: memesvault.com)



来源:https://stackoverflow.com/questions/37167602/typescript-node-js-express-routes-separated-files-best-practices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!