Node.js

前端工程師邁向後端之路 4 – 用 Node.js 架設 http server

接著就要來實作用 Node.js 來架設一個 http server 了!這一系列的文章都會用 TypeScript 來寫,TypeScript 是 JavaScript 的嚴格超集,最主要的差別就是可以為變數加上型別,讓大型專案更加好維護。

1. 安裝 TypeScript 及建立 Node.js 環境

雖然之前有寫過一篇:【 Node.js 】如何在 Node.js 中建立 TypeScript 的環境,但那篇並沒有導入 TypeScript 的「風格」,一般來說,在打造公司的產品的時候,也會同時確立 TypeScript 撰寫的風格 ( tab 應該是要幾個空格、要不要加上分號等等 ),讓產品雖然是多人開發,卻可以統一 code 的風格。

目前 TypeScript 的 style 主流為:airbnb、microsoft、google,本專案選擇用 airbnb 的 style guide,再做一些微調,airbnb 完整的 style guide 可以參考:Airbnb React/JSX Style Guide | Airbnb JavaScript Style Guide,裡面描述的雖然是 JavaScript 的規則,但 TypeScript 沿用了大部分的 style。

1.1 安裝 ESLint、TypeScript

ESLint 是用來檢查 coding style 的套件,在安裝 ESLint 並 init 後,就可以選擇想要哪種 style guide 並安裝相關套件:

# 使用 npm
$ npm install eslint typescript --save-dev
# 使用 yarn
$ yarn add eslint typescript --dev

安裝完後就可以 init ESLint 並作相關設定:

$ npx eslint --init
# or
$ yarn run eslint --init

# 1.
? How would you like to use ESLint? … 
  To check syntax only
  To check syntax and find problems
❯ To check syntax, find problems, and enforce code style

# 2.
? What type of modules does your project use? … 
❯ JavaScript modules (import/export)
  CommonJS (require/exports)
  None of these

# 3.
? Which framework does your project use? … 
  React
  Vue.js
❯ None of these

# 4. 選擇 Yes
? Does your project use TypeScript? › No / Yes

# 5. 這邊可以複選,但因為是在 server 的環境下,所以單勾 Node 就好
? Where does your code run? …  (Press <space> to select, <a> to toggle all, <i> to invert selection)
✔ Browser
✔ Node

# 6. 
? How would you like to define a style for your project? … 
❯ Use a popular style guide
  Answer questions about your style
  Inspect your JavaScript file(s)

# 7. 選擇 airbnb
? Which style guide do you want to follow? … 
❯ Airbnb: https://github.com/airbnb/javascript
  Standard: https://github.com/standard/standard
  Google: https://github.com/google/eslint-config-google
  XO: https://github.com/xojs/eslint-config-xo

# 8. 這邊按照個人喜好選擇設定檔的格式,個人偏好 json
? What format do you want your config file to be in? … 
  JavaScript
  YAML
❯ JSON

# 9. 這邊詢問是否安裝相關套件,選擇 Yes
@typescript-eslint/eslint-plugin@latest eslint-config-airbnb-base@latest eslint@^5.16.0 || ^6.8.0 || ^7.2.0 eslint-plugin-import@^2.22.1 @typescript-eslint/parser@latest
? Would you like to install them now with npm? › No / Yes

可以看到 ESLint 會自動新增一個 .eslintrc.json 的設定檔,裡面描述了 TypeScript 的一些格式設定。

接著我們可以安裝 vs-code 的套件:ESLint 來輔助開發,這樣寫 code 的過程中這個套件就會自動幫你檢查寫出來的 style 是否有符合設定檔,不用等到去執行 script 才知道專案種哪個地方不符合。

Node.js

如此一來一旦檔案中有任何不符合格式的地方,都會有紅色毛毛蟲出現,並且會提示不符合哪個規則:

Node.js

(以下 style 修正單純為了符合筆者平常的開發習慣,並非必要之修正)

1.2 新增 tsconfig.json

新增 tsconfig.json 在專案的根目錄:

{
  "compilerOptions": {
    "target": "es2020",
    "lib": ["es2020"],
    "module": "commonjs",
    "moduleResolution": "node",

    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "rootDir": ".",
    "outDir": "build",
    "sourceMap": true
  },
  "include": [
    "src/**/*.ts",
    "migrations/*.ts",
    "test/**/*.ts"
  ]
}

1.3 新增 .prettierrc

{
  "printWidth": 120,
  "singleQuote": true,
  "useTabs": false,
  "tabWidth": 2,
  "semi": true,
  "bracketSpacing": true,
  "trailingComma": "none"
 }
 

1.4 修改 .eslintrc.json

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": ["airbnb-base"],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": 12,
    "sourceType": "module",
    "project": "./tsconfig.json"
  },
  "plugins": ["@typescript-eslint"],
  "rules": {
    "no-duplicate-imports": "off",
    "no-console": "off",
    "comma-dangle": "off",
    "consistent-return": "off",
    "import/extensions": [
      "error",
      "ignorePackages",
      {
        "js": "never",
        "jsx": "never",
        "ts": "never",
        "tsx": "never"
      }
   ],
   "import/prefer-default-export": "off",
   "no-unused-vars": "off"
  },
  "settings": {
    "import/resolver": {
      "node": {
        "extensions": [".js", ".jsx", ".ts", ".tsx"],
        "moduleDirectory": ["node_modules", "src/"]
      }
    }
  }
}

2. Install dependecies

2.1 安裝套件

接著要來安裝會用到的套件:

  • express: express 是針對 Node.js 所開發的 web 框架,讓我們可以省略許多語法快速開發一個 web app
  • nodemon: 每當 save 檔案時 nodemon 會自動重啟 server,讓你可以即時看到修改的 code 造成什麼樣的影響
  • ts-node: 一般來說將專案部署到 server 時會將 TypeScript 轉譯成 JavaScript 後,才能讓 JavaScript 引擎執行,但在開發的時候可能會需要直接執行 TypeScript ,這時候就需要 ts-node 了,ts-node 會先將 TypeScript 轉譯成 JavaScript 並放在快取當中,再讓 Node.js 來執行,因此可以將 ts-node 視為 TypeScript 引擎。
$ yarn add express
$ yarn add nodemon ts-node @types/express @types/node --dev

2.2 修改 package.json

新增幾個 script:

"scripts": {
    "start": "nodemon src/index.ts",
    "build": "tsc --project ./"
    ...
}

3. 建立 debug 的 config 檔

在開發的過程中如果遇到比較難解的 bug,會需要用到 vs-code 的 debug 模式來單步執行,因此我們需要先建立 debug 的 config 檔:

3.1 點擊進入點檔案

要先點擊 server 的進入點檔案,等等 vscode 才會直接按照這個檔案的路徑來自動產生 config 檔,以這個專案為例,要先點擊 src/index.ts

3.2 產生 launch.json

點擊左邊的 debug 模式後再點擊 create a launch.json ,選擇 node.js,vscode 就會自動產生 debug 模式的設定檔⏤launch.json:

Node.js
Node.js

基本上 launch.json 不需要改任何東西,我這邊只修改了 name,改成一個比較順眼的名字:

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "pwa-node",
      "request": "launch",
      "name": "Launch Current Server",
      "skipFiles": [
        "<node_internals>/**"
      ],
      "program": "${workspaceFolder}/src/index.ts",
      "preLaunchTask": "tsc: build - tsconfig.json",
      "outFiles": [
        "${workspaceFolder}/build/**/*.js"
      ]
    }
  ]
}

如此一來就可以進行 debug 模式了!

4. 建立 http-server

接著就可以來改寫 index.ts 來建立 http-server 了!

// src/index.ts
import express, { Request, Response } from 'express';

const app = express();
const port = 3000;

app.get('/', (req: Request, res: Response) => {
  res.send('The server is working!');
});

app.listen(port, () => {
  console.log(`server is listening on ${port} !!!`);
});

如果想要參考不用 express 的版本的話,可以參考我之前寫的文章的前半段:【 Node.js 】 用 TypeScript 和 Express 建立一個 http server

寫完 server 後就可以試著把 server 跑起來看看:

$ yarn start
# 或是
$ npm run start

如果 server 成功的 console 出 port 就代表成功了!

簡單架設一個 http server 後,接著要來談談為什麼需要 database migration:前端工程師邁向後端之路 5 – PostgreSQL migration:淺談 database migration ( 資料庫遷移 )?

5. 參考資料

google/gts: ☂️ TypeScript style guide, formatter, and linter.
A collection of useful .gitignore templates – GitHub
Rules – ESLint – Pluggable JavaScript linter
Disable typescript-eslint plugin rule (no-explicit-any) with inline comment
Options · Prettier
如何直接執行TypeScript 指令檔 – Poy Chang
程式碼檢查- TypeScript 新手指南

如果覺得我的文章有幫助的話,歡迎幫我的粉專按讚哦~謝謝你!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top