typescript node.js 表达路由分隔文件最佳实践

typescript node.js express routes separated files best practices

在 Node 项目中使用 Express 以及 Typescript 什么是 "best practices" for express.Router。

示例目录结构

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

所以在index.ts里面它会封装和管理所有的子路由器

<div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre><code>    //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;
    })();

    //index.ts (master file for express.Router)

    import * as express from "express";

    //import sub-routers
    import * as adminRouter from "./admin/admin";
    import * as productRouter from "./products/products";

    export = (() => {

      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);

      //return for revealing module pattern
      return router;
    })(); //<--- this is where I don't understand something....

最后我们将设置我们的 server.js

<div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre><code>    //the usual node setup
    //import * as *** http, body-parser, morgan, mongoose, express <-- psudocode

    import * as masterRouter from './routes/index'

    var app = express();
    //set-up all app.use()

    app.use('/api', masterRouter);

    http.createServer(app).listen(8080, () => {
          console.log('listening on port 8080')
        };

我的主要问题确实是 index.ts(masterRouter 文件),它是 IIFe 的嵌套路由

导出=(函数(){})();

这应该是 correct/best 为路由器编写 typescript 模块的方式吗?

或者使用另一种模式会更好,也许是利用模式

export function fnName() {} -- export class cName {} -- export default.

使用 IIFe 的原因是,当我将它们导入另一个文件时,我不需要初始化模块,并且每种类型的路由器只会有 1 个实例。

在 NodeJS 中每个文件都是一个模块。声明变量不会污染全局命名空间。所以你不需要使用好的旧 IIFE 技巧来正确地限定变量的范围(并防止全局污染/冲突)。

你会写:

  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;

关于模块的更多信息: https://basarat.gitbooks.io/typescript/content/docs/project/modules.html