1. 程式人生 > 其它 >TypeScript3+Express+Node.js

TypeScript3+Express+Node.js

  TypeScript 3 + Express + Node.js

  第一步、安裝需要的配置

  首先,我們將使用node包管理器(npm)來為我們的應用程式安裝依賴項。

  Npm與Node.js一起安裝。

  如果您還沒有安裝Node.js,可以通過homebrew程式完成。

  安裝Homebrew並更新它:

  $ /usr/bin/ruby -e "$(curl -fsSL raw.githubusercontent/Homebrew/install/master/install)"

  $ brew update

  $ brew doctor

  然後使用brew install命令安裝node

  brew install node

  第二步、建立專案

  接下來,讓我們使用npm init命令建立一個新專案。

  $ mkdir ts_node_blog

  $ cd ts_node_blog

  $ npm init

  在回答提示後,您將在專案資料夾中有一個新的package.json檔案。

  我們也新增一些自定義指令碼。

  首先,新增開發指令碼。

  這將使用nodemon模組來監視對快速Web應用程式的原始檔的任何更改。

  如果檔案更改,那麼我們將重新啟動伺服器。

  接下來,新增grunt指令碼。

  這只是呼叫grunt任務執行器。

  我們將在本教程後面安裝它。

  最後,新增啟動指令碼。

  這將使用node來執行bin/www檔案。

  如果您使用的是Linux或Mac,則package.json檔案應如下所示:

  {

  "name": "ts_node_blog",

  "version": "1.0.0",

  "description": "The blog of typescript + nodejs + express",

  "main": "app.js",

  "scripts": {

  "dev": "NODE_ENV=development nodemon ./bin/www",

  "grunt": "grunt",

  "start": "node ./bin/www",

  "test": "echo "Error: no test specified" && exit 1"

  },

  "keywords": [

  "typescript",

  "noejs",

  "blog"

  ],

  "author": "durban.zhang <durban.zhang@gmail>",

  "license": "MIT"

  }

  如果您使用的是Windows,則package.json檔案應如下所示:

  {

  "name": "ts_node_blog",

  "version": "1.0.0",

  "description": "The blog of typescript + nodejs + express",

  "main": "app.js",

  "scripts": {

  "dev": "SET NODE_ENV=development nodemon ./bin/www",

  "grunt": "grunt",

  "start": "node ./bin/www",

  "test": "echo "Error: no test specified" && exit 1"

  },

  "keywords": [

  "typescript",

  "noejs",

  "blog"

  ],

  "author": "durban.zhang <durban.zhang@gmail>",

  "license": "MIT"

  }

  請注意Windows使用者對dev指令碼的微小更改。

  第三步、安裝Express

  下一步是安裝Express依賴項。

  我在我的npm install命令中包含了--save標誌,以便將依賴項儲存在package.json檔案中。

  $ npm install express --save

  $ npm install @types/express --save-dev

  請注意,這還會在專案中生成新的node_modules資料夾。

  如果您使用Git,則應將此資料夾新增到.gitignore檔案中。

  第四步、啟動指令碼的配置

  接下來我們需要建立我們的啟動指令碼。

  如果您還記得,我們在package.json檔案的scripts配置中指定了一個start屬性。

  我將其值設定為:"node ./bin/www"。

  所以,讓我們在:bin/www建立一個空檔案

  $ mkdir bin

  $ cd bin

  $ touch www

  以下是www檔案的完整內容:

  #!/usr/bin/env node

  "use strict";

  const server=require("../dist/server");

  const debug=require("debug")("express:server");

  const http=require("http");

  const httpPort=normalizePort(process.env.Port || 8080);

  const app=server.Server.bootstrap().app;

  app.set("port", httpPort);

  const httpServer=http.createServer(app);

  httpServer.listen(httpPort);

  httpServer.on("error", onError);

  httpServer.on("listening", onListening);

  function normalizePort(val) {

  const port=parseInt(val, 10);

  if (isNaN(port)) {

  return val;

  }

  if (port >=0) {

  return port;

  }

  return false;

  }

  function onError(error) {

  if (error.syscall !=="listen") {

  throw error;

  }

  const bind=typeof httpPort==='string'

  ? "Pipe " + httpPort

  : "Port " + httpPort;

  switch(error.code) {

  case "EACCES":

  console.error(bind + " requires elevated privileges");

  process.exit(1);

  break;

  case "EADDRINUSE":

  console.error(bind + " alreay is use");

  process.exit(1);

  break;

  default:

  throw error;

  }

  }

  function onListening() {

  const addr=httpServer.address();

  const bind=typeof httpPort==='string'

  ? "Pipe " + httpPort

  : "Port " + httpPort;

  debug("Listening on " + bind);

  }

  這有點長。所以,讓我打破這一點並解釋每個部分。

  #!/usr/bin/env node

  "use strict";

  const server=require("../dist/server");

  const debug=require("debug")("express:server");

  const http=require("http");

  首先,我們有node shebang來執行這個指令碼。如果您使用的是Windows,只需將此檔案重新命名為js,node將根據副檔名執行此操作。

  然後我們通過“use strict”命令啟用嚴格模式。

  然後我需要一些依賴。首先,我將在:dist/server.js中有一個模組(檔案)。我們還沒有建立這個,所以不要擔心。然後我們需要express和http模組。

  const httpPort=normalizePort(process.env.Port || 8080);

  const app=server.Server.bootstrap().app;

  app.set("port", httpPort);

  const httpServer=http.createServer(app);

  首先,我確定將http伺服器繫結到的埠,並監聽。這將首先檢查PORT環境變數,然後預設為8080。

  我還使用了由Google Cloud Platform團隊提供的normalizePort()函式。我從他們的示例應用程式中借用了這些。

  接下來,我將使用bootstrap()老啟動我的應用程式。在建立Server類之後,這將更有意義。

  然後我為HTTP伺服器設定埠。

  最後我們建立了http伺服器,傳入我們的express app。

  httpServer.listen(httpPort);

  httpServer.on("error", onError);

  httpServer.on("listening", onListening);

  在這部分中,我將指定我們的http伺服器將偵聽的埠,然後我附加一些事件處理程式。

  我正在聽error和listening事件。

  在建立應用程式期間發生錯誤時將觸發錯誤事件。

  當http伺服器啟動並正在偵聽指定埠時,將觸發偵聽事件。

  第五步、安裝TypeScript 和 Grunt

  接下來,使用npm install命令安裝TypeScript:

  $ npm install typescript --save-dev

  我將使用Grunt任務執行器來編譯TypeScript原始碼

  使用npm安裝grunt:

  $ npm install grunt --save-dev

  現在我們安裝了grunt,讓我們安裝一些任務執行器:

  $ npm install grunt-contrib-copy --save-dev

  $ npm install grunt-ts --save-dev

  $ npm install grunt-contrib-watch --save-dev

  grunt-contrib-copy任務執行器將./public和./views目錄中的檔案複製到./dist目錄中

  我們將使用grunt-ts任務來編譯TypeScript原始碼。

  我們將使用grunt-contrib-watch來監視對TypeScript原始檔的任何更改。

  當一個檔案更新(或儲存)檔案後,我想重新編譯我的應用程式。

  結合我們之前在package.json檔案中建立的dev指令碼,我們將能夠輕鬆地對TypeScript源進行更改,然後立即在瀏覽器中檢視更改。

  第六步、建立gruntfile.js

  下一步是配置Grunt來編譯我們的TypeScript原始碼。

  首先,在應用程式根目錄中建立gruntfile.js檔案。

  $ touch gruntfile.js

  在您喜歡的編輯器中開啟gruntfile.js檔案。我使用Visual Studio Code。gruntfile.js檔案內容如下

  以下是gruntfile.js的說明:

  1. 使用exports物件,我們將匯出一個將由grunt任務執行器呼叫的函式。這是非常標準的。它有一個名為grunt的引數。

  2. 遵循最佳實踐我正在啟用嚴格模式。

  3. 然後我們呼叫grunt.initConfig()方法並傳入我們的配置物件。

  4. 在我們的配置物件中,我們指定每個任務

  5. 第一項任務是複製。此任務將複製./public和./views目錄中的檔案。

  6. 接下來的任務是ts。此任務將TypeScript原始碼編譯為可由Node.js執行的JavaScript。已編譯的JavaScript程式碼將輸出到./dist目錄。

  7. 第三項任務是觀察。此任務將監視對TypeScript原始檔(*.ts)以及檢視模板檔案(*.pug)的任何更改。

  如果一切正常,您應該能夠執行grunt命令

  $ npm run grunt

  你應該看到這樣的事情:

  > [email protected] grunt /Users/durban/nodejs/ts_node_blog

  > grunt

  Running "copy:build" (copy) task

  Running "ts:app" (ts) task

  No files to compile

  Done.

  第七步、安裝中介軟體

  在我們建立server.ts模組之前,我們需要安裝一些更多的依賴項。

  我在此示例Express應用程式中使用以下中介軟體:

  1. body-parser[github/expressjs/body-parser]

  2. cookie-parser[github/expressjs/cookie-parser]

  3. morgan[github/expressjs/morgan]

  4. errorhandler[github/expressjs/errorhandler]

  5. method-override[github/expressjs/method-override]

  您可以使用上面的連結閱讀有關這些內容的更多資訊。讓我們繼續,通過npm安裝這些:

  $ npm install body-parser --save

  $ npm install cookie-parser --save

  $ npm install morgan --save

  $ npm install errorhandler --save

  $ npm install method-override --save

  我們還需要為這些模組安裝TypeScript宣告檔案。

  在TypeScript 3之前,您必須使用名為Typings的開源專案。

  現在不再是這種情況,因為TypeScript 3極大地改進了對第三方模組宣告(或標頭檔案)的支援。

  讓我們使用npmjs上的@ types/repository安裝TypeScript宣告檔案:

  $ npm install @types/cookie-parser --save-dev

  $ npm install @types/morgan --save-dev

  $ npm install @types/errorhandler --save-dev

  $ npm install @types/method-override --save-dev

  第八步、建立Server類

  首先,為TypeScript程式碼建立一個src目錄,然後建立一個新的server.ts檔案。

  我們準備好在Node.js上使用Express啟動我們的新HTTP伺服器。

  在我們這樣做之前,我們需要建立我們的Server類。

  這個類將配置我們的express Web application,會涉及到REST API和routes的類。下面是定義我們的Server類的server.ts檔案的開頭:

  import * as bodyParser from "body-parser";

  import * as cookieParser from "cookie-parser";

  import * as express from "express";

  import * as logger from "morgan";

  import * as path from "path";

  import errorHandler=require("errorhandler");

  import merhodOverride=require("method-override");

  /**

  * The Server

  *

  * @class Server

  */

  export class Server {

  public app: express.Application;

  /**

  * Bootstrap the application

  *

  * @class Server

  * @method bootstrap

  * @static

  * @return Returns the newly created injector for this app. Returns the newly created injector for this app.

  */

  public static bootstrap(): Server {

  return new Server();

  }

  /**

  * Constructor

  *

  * @class Server

  * @method constructor

  */

  constructor() {

  // create express application

  this.app=express();

  // configure application

  this.config();

  // add routes

  this.routes();

  // add api

  this.api();

  }

  /**

  * Create REST Api routes

  *

  * @class Server

  * @method api

  */

  public api() {

  }

  /**

  * Configure application

  *

  * @class Server

  * @method config

  */

  public config() {

  }

  /**

  * Create router

  *

  * @class Server

  * @method router

  */

  public routes() {

  }

  }

  讓我們深入研究Server.ts模組(檔案)中的Server類。

  匯入

  import * as bodyParser from "body-parser";

  import * as cookieParser from "cookie-parser";

  import * as express from "express";

  import * as logger from "morgan";

  import * as path from "path";

  import errorHandler=require("errorhandler");

  import merhodOverride=require("method-override");

  1. 首先,我們匯入我們以前安裝的中介軟體和必要的模組。

  2. body-parser中介軟體將JSON有效負載資料解析為可在我們的express應用程式中使用的req.body物件。

  3. cookie-parser中介軟體類似於body-parser,因為它解析使用者的cookie資料並在req.cookies物件中使用它。

  4. 然後我們匯入express模組。這是express框架。

  5. 我正在使用morgan HTTP logger 中介軟體。這應該只在開發期間使用。

  6. 然後我匯入path模組。我將使用它來為config()方法中的public和views目錄設定路徑目錄。

  7. errorhandler 中介軟體將在開發期間處理錯誤。同樣,這不應該用於生產。相反,您需要記錄錯誤,然後向用戶顯示錯誤指示。

  8. 最後,我使用method-override中介軟體。您可能不需要這個,但在REST API配置中使用"PUT"和"DELETE"HTTP謂詞時需要這樣做。

  Server類

  /**

  * The Server

  *

  * @class Server

  */

  export class Server {

  public app: express.Application;

  /**

  * Bootstrap the application

  *

  * @class Server

  * @method bootstrap

  * @static

  * @return Returns the newly created injector for this app. Returns the newly created injector for this app.

  */

  public static bootstrap(): Server {

  return new Server();

  }

  }

  接下來,我們建立一個名為Server的新類。

  我們的類有一個名為app的公共變數。

  請注意,我們的應用程式是express.Application型別。

  在Server類中,我有一個名為bootstrap()的靜態方法。

  這在我們的www啟動指令碼中呼叫。

  它只是建立Server類的新例項並返回它。

  constructor函式

  /**

  * Constructor

  *

  * @class Server

  * @method constructor

  */

  constructor() {

  // create express application

  this.app=express();

  // configure application

  this.config();

  // add routes