owned this note changed 4 years ago
Linked with GitHub

用 typescript 寫一個 codegen 可以學到什麼? - Wayne Tsai

歡迎來到 MOPCON 2020 共筆

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

共筆入口:https://hackmd.io/@mopcon/2020
手機版請點選上方 按鈕展開議程列表。

  • 關於講者:
    • 名字:Wayne Tsai

本場簡報連結

Codegen工具

  1. Schematics Extension (講者第一個使用typescript寫的codegne工具)

links

  1. openapi-code-generator

相關工具:前端模板template

GTX-Compiler

code generator wrapper on vscode

開發緣由:Swagger repo 的更新趨緩

因為新工具的issue,本場未demo第二個工具,以第一個工具的demo為主。第二個工具demo講者會在鐵人賽後續的系列文補上,並在共筆貼上。

講者其他參考文章:自己用的工具自己做! 30天玩轉VS Code Extension之旅 :: 第 12 屆 iT 邦幫忙鐵人賽

TreeView 元件開發

VSCode 為物件導向,元件開發需要思考

TreeView 做為 data provider,會提供外部使用者存取事件,驅動文件自動更新

使用 Singleton 模式

使用class:

  1. 透過 static method創造物件
class A { static _instance: A | undefined; static getInstance() { if(A.instance) { A.instance = new A(); } return A.instance; } }
  1. 更簡單的方式:配合es6 module export一個new創建的物件達成。

不一定需使用class,也可export js物件完成一樣的效果。

當有多個元件時,管理上較為麻煩。

其他元件類別開發情境

需在類別創建時於constructor裡使用async await處理非同步行為,可以改用static method來創建類別或元件。

class A { static async createAsync() { const a = new A(); a.settings = await a.fetchSettings(); return a; } async fetchSettings() { return Promise.resolve(); } }
// 基本的類別創建方法: const a = new A(); // 使用async的static method創建物件: const a = await A.createAsync();

Log 輸出

  1. API 輸出,無狀態共享的問題。
  2. 使用物件封裝
  3. 更簡單的 singleton(全域、安全、方便)

-> 需要如有共享的全域狀態容易發生問題,慎選使用情境。

Registry Pattern 註冊表模式

常被用於實作Service Locator。

使用Map來管理物件的註冊,是更好管理多個全域物件的方式

透過Map的has()方法判斷是否已經註冊了要用的物件或物件服務,避免使用該物件的方法時拿不到物件出錯。

VSCode裡的Registry

github連結

VSCode 的 registry命名上比較難懂

export const Registry: IRegistry = new RegistryImpl();

export物件時將物件型態指定為interface的類型。使用介面隔離class之間的方法,class或物件、function之間彼此只了解對方介面的方法。

將 instance 類型分類

應用:群組化、模組化

使用 enum 分隔 constant variables

盡量使用小介面為主

使用 Interface:注入端(使用者端)

使用 constructor injection

好處:

  1. 容易了解A模組依賴了哪些其他模組的功能
  2. 好測試

預防null建議

  1. 帶入 property 時可使用問號語法避免參數缺少的問題
const obj = {
 propA: {};
}

const value = (obj as any).propA?.propB?.propC;

console.log(value || 'default');
  1. null coalescing
console.log(value || 'default');

console.log(value ?? 'default');

聽眾演講中反應

  • 後排有些聲音聽不到,需調大聲
  • 部分地方講速過快,調慢一點較好

問題區


有相關問題可以在這發問喔!

tags: MOPCON 2020
Select a repo