typescript node.js表示路径分离文件的最佳做法 [英] typescript node.js express routes separated files best practices

查看:474
本文介绍了typescript node.js表示路径分离文件的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



示例目录结构

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

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

  

  //admin.ts(嵌套在index.ts内)import * as express从快递; export =(()=> {let router = express.Router(); router.get('/ admin',(req,res)=> {res.json({success:true});}); return router;})();  


  //index.ts(master.Router的主文件)import * as express fromexpress; //导入子路由器导入*作为adminRouter从./admin/admin;进口*作为productRouter从./products/products; export =(()=> {let router = express.Router(); //挂载express路径,也可以添加任何添加中间件// ex。router.use('/ pathway',middleware_function,路由器); router.use('/ products',productRouter); router.use('/ admin',adminRouter); //返回显示模块模式return router;})(); //< ---这是我不明白的东西....  



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

  

  //通常的节点设置//导入*作为*** http,body-parser,morgan,mongoose,express<  -  psudocode import *作为masterRouter从'./routes/index'var app = express(); //设置所有app.use()app.use('/ api',masterRouter); http.createServer(app).listen(8080,()=> {console.log('listen on port 8080')};  

div>

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



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



应该是正确的/最好的方式来写路由器的文件模板?



或者最好使用另一个模式,也许一个使用模式


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


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

解决方案

答案



在NodeJS中,每个文件都是一个模块 em>不污染全局命名空间。所以你不需要使用好的旧的 IIFE 技巧来正确地对变量进行比较(并防止全球污染/碰撞)。



你会写:

  import * as express fromexpress ; 

//导入子路由器
import *作为adminRouter从./admin/admin;
import * as productRouter from./products/products;

let router = express.Router();

// mount express路径,任何添加中间件也可以添加。
// ex。 router.use('/ pathway',middleware_function,sub-router);

router.use('/ products',productRouter);
router.use('/ admin',adminRouter);

//导出路由器
export = router;



更多关于模块



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



我的反应

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

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

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

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.

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.

解决方案

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

这篇关于typescript node.js表示路径分离文件的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆