ExpressJS - 最佳實踐



與 Django 和 Rails 具有定義好的做事方式、檔案結構等不同,Express 沒有遵循定義好的方式。這意味著您可以根據自己的喜好來構建應用程式。但是,隨著應用程式規模的增長,如果沒有一個定義良好的結構,維護它將非常困難。在本章中,我們將瞭解通常使用的目錄結構和關注點分離來構建我們的應用程式。

首先,我們將討論建立 Node 和 Express 應用程式的最佳實踐。

  • 始終使用npm init開始 Node 專案。

  • 始終使用--save--save-dev安裝依賴項。這將確保如果您遷移到不同的平臺,您只需執行npm install即可安裝所有依賴項。

  • 堅持使用小寫檔名和駝峰式變數。如果您檢視任何 npm 模組,它的名稱都是小寫並用連字元分隔。每當您需要這些模組時,請使用駝峰式命名法。

  • 不要將node_modules推送到您的儲存庫。相反,npm 在開發機器上安裝所有內容。

  • 使用config檔案儲存變數

  • 將路由分組並隔離到它們自己的檔案中。例如,在 REST API 頁面中看到的電影示例中的 CRUD 操作。

目錄結構

現在讓我們討論 Express 的目錄結構。

網站

Express 沒有社群定義的建立應用程式的結構。以下是網站主要使用的專案結構。

test-project/
   node_modules/
   config/
      db.js                //Database connection and configuration
      credentials.js       //Passwords/API keys for external services used by your app
      config.js            //Other environment variables
   models/                 //For mongoose schemas
      users.js
      things.js
   routes/                 //All routes for different entities in different files 
      users.js
      things.js
   views/
      index.pug
      404.pug
        ...
   public/                 //All static content being served
      images/
      css/
      javascript/
   app.js
   routes.js               //Require all routes in this and then require this file in 
   app.js 
   package.json

還有其他方法可以使用 Express 構建網站。您可以使用 MVC 設計模式構建網站。有關更多資訊,您可以訪問以下連結。

https://code.tutsplus.com/tutorials/build-a-complete-mvc-website-with-expressjs--net-34168

以及,

https://www.terlici.com/2014/08/25/best-practices-express-structure.html.

RESTful API

API 設計起來更簡單;它們不需要 public 或 views 目錄。使用以下結構來構建 API -

test-project/
   node_modules/
   config/
      db.js                //Database connection and configuration
      credentials.js       //Passwords/API keys for external services used by your app
   models/                 //For mongoose schemas
      users.js
      things.js
   routes/                 //All routes for different entities in different files 
      users.js
      things.js
   app.js
   routes.js               //Require all routes in this and then require this file in 
   app.js 
   package.json

您還可以使用yeoman 生成器來獲得類似的結構。

廣告

© . All rights reserved.