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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37167602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:11:56  来源:igfitidea点击:

typescript node.js express routes separated files best practices

node.jsexpressmoduletypescriptcommonjs

提问by Andrei

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

在 Node 项目中使用 Express 和 Typescript 什么是 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

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

    //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....

lastly we would set-up our server.js

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

    //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')
        };

my main question really is, is index.ts (masterRouter file) and it's nested routes that are IIFe's

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

export = (function(){})();

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

should that be the correct/best way to write typescript modules for routers?

这应该是为路由器编写打字稿模块的正确/最佳方式吗?

or would it be better to use another pattern, perhaps one the utilizes the pattern

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

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

导出函数 fnName() {} -- 导出类 cName {} -- 导出默认值。

the reason for the IIFe is that when i import them into another file i won't need to initialize the module and there will only ever be 1 instance of each type of router.

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

回答by basarat

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 IIFEtrick to properly scope variables (and prevent global pollution / collision).

在 NodeJS 中,每个文件都是一个模块。声明变量不会污染全局命名空间。因此,您不需要使用古老的IIFE技巧来正确地限定变量的范围(并防止全局污染/碰撞)。

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

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

我的主要问题确实是 index.ts(masterRouter 文件),它是 IIFe 的嵌套路由,这export = (function(){})();应该是为路由器编写打字稿模块的正确/最佳方式


(source: memesvault.com)


(来源:memesvault.com