<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by LiRen Lin on Medium]]></title>
        <description><![CDATA[Stories by LiRen Lin on Medium]]></description>
        <link>https://medium.com/@toy9986619?source=rss-3f389ee4264c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4blsgihPT_CuirDKeENjzg.jpeg</url>
            <title>Stories by LiRen Lin on Medium</title>
            <link>https://medium.com/@toy9986619?source=rss-3f389ee4264c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:37:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@toy9986619/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[在 JavaScript 開發環境下改善開發體驗 — 3. 提供 API 文件]]></title>
            <link>https://toy9986619.medium.com/%E5%9C%A8-javascript-%E9%96%8B%E7%99%BC%E7%92%B0%E5%A2%83%E4%B8%8B%E6%94%B9%E5%96%84%E9%96%8B%E7%99%BC%E9%AB%94%E9%A9%97-%E6%8F%90%E4%BE%9B-api-%E6%96%87%E4%BB%B6-146bfb567423?source=rss-3f389ee4264c------2</link>
            <guid isPermaLink="false">https://medium.com/p/146bfb567423</guid>
            <dc:creator><![CDATA[LiRen Lin]]></dc:creator>
            <pubDate>Tue, 13 May 2025 09:29:22 GMT</pubDate>
            <atom:updated>2025-05-29T09:52:23.348Z</atom:updated>
            <content:encoded><![CDATA[<h3>在 JavaScript 開發環境下改善開發體驗 — 3. 提供 API 文件</h3><p>TL;DR，透過 TypeDoc 這個第三方套件，我們可以對撰寫好 JSDoc 格式註解的原始碼，產生對應的 HTML 文件，提供給第三方開發人員做 API 文件閱讀。</p><p>這篇文章會延續前兩篇的<a href="https://toy9986619.medium.com/652b0707a752">內容</a>與<a href="https://github.com/toy9986619/js-intellisense-support-example">專案</a>，引導開發人員在 JavaScript 專案下，提供 API 文件給第三方開發人員閱讀。</p><p>我們會用到的工具有：</p><ul><li><a href="https://typedoc.org/index.html">TypeDoc</a>，建立 API 文件。</li></ul><h3>建立 API 文件</h3><p>首先，我們要先建立 TypeDoc 的設定，重點設定如下：</p><pre>// typedoc.json<br><br>{<br>    // 設定哪些文件要讓 typedoc 處理<br>    &quot;entryPoints&quot;: [<br>        &quot;./src/**/*.js&quot;,<br>        &quot;./src/**/types/**.ts&quot;,<br>        &quot;./package.json&quot;<br>    ],<br>    // 設定產生結果的路徑<br>    &quot;out&quot;: &quot;./docs&quot;,<br>    // 設定 typedoc 要使用的 typescript config 檔案<br>    &quot;tsconfig&quot;: &quot;./tsconfig.json&quot;,<br>    // 產生結果將包含 package.json 的版本號<br>    &quot;includeVersion&quot;: true<br>}</pre><p>接著執行 TypeDoc 產生文件：</p><pre>npx typedoc</pre><p>完成後，我們會獲得 docs 這一個資料夾，以及相關檔案。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*QG_HfWXedZAJSEgYcAPJPw.png" /><figcaption>TypeDoc 產生的檔案</figcaption></figure><p>我們用瀏覽器對 docs/index.html 這一個檔案做開啟，便可以看到產生的 API 文件。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K8ftZ8v5l0g39SLUUUycbw.png" /><figcaption>瀏覽器開啟 API 文件</figcaption></figure><p>先來看看 onAuthStateChanged API 的產生文件內容：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*Hnk9s2Lv_uhQKqXp0hFCCg.png" /><figcaption>onAuthStateChanged 的文件產生結果</figcaption></figure><p>我們可以看到 API 參數的型別都有辨識出來，點擊型別也會跳去型別文件的細節。然而這還不算是一份友善的文件，因為我們還沒有對這個 API 做它的功能描述、參數做描述，或是給這個 API 的 sample code。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*QGOr9aUObJylorGUIKv5tw.png" /><figcaption>一份友善的文件，會有 API 的描述，以及參數、回傳值的描述。(以 react 文件為例)</figcaption></figure><p>因此，我們要回頭從原始碼檔案上，做更詳細的加註，讓文件可以有更多的描述內容在上面。</p><p>我們可以用 JSDoc 的格式，繼續對 onAuthStateChanged API 做更多的說明。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*AemMnAWQcdBiQn83tgRPmg.png" /><figcaption>新的 API 的描述</figcaption></figure><p>以上圖為例，我們新增了這個 API 的說明，markdown 格式說明了這個 function 的 sample code，以及對參數做了額外的補充。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*gr39MXVdGiw5Ky8WJjIVxA.png" /><figcaption>對參數做額外補充</figcaption></figure><p>我們額外擴充的 AuthStateChangedListener 的型別宣告，則是直接在參數內加註參數說明。</p><p>新增完 API 說明後，重新用 TypeDoc 產生新的文件：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*RrjH15aiM6BPfv4VTqQMJQ.png" /><figcaption>文件包含了新增的描述</figcaption></figure><p>可以從上圖看到，新的結果包含了 function 的說明、範例程式碼(以及支援 markdown 輸出)、參數的說明。這個輸出結果開始符合我們的目標：友善的文件。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*AOyE2Oe244Of0H7ceT96Tg.png" /></figure><p>在 AuthStateChangedListener 的擴增型別中，對 uid 參數所註記的描述，也有被正確的產生出來。</p><p>至此，我們可以對會公開的 API、型別，用 JSDoc 格式進行描述，讓 TypeDoc 產生對應的文件，即可將文件交付給第三方開發人員，或是放上網路空間(例如直接使用 Github Pages 的服務)，即可讓第三方開發人員瀏覽。</p><h3>額外詢問</h3><p>在前一篇文章中，透過 tsc 轉譯 d.ts 檔案的時候，我還有一些疑惑：我在 js 上面的所有加註描述，都會在 d.ts 上移除。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*eYzt9Q9nwsV8FJJZFHlCxg.png" /><figcaption>所有描述都被移除了</figcaption></figure><p>我翻了滿多討論，都是說 tsc 最後產生的結果，應該要是產品版本的結果，因此所有註解都會移除，不保留在 d.ts 檔案上，也不提供設定做調整。</p><p>我也好奇，大型團隊釋出的套件，能夠直接在 IDE 上面看到描述，點入引用也能發現是在 d.ts 檔案上的註解。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*oTlrbjAWoPk7IJ22Nf4NSA.png" /><figcaption>Firebase SDK 底下對於 getApp 的說明</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*bVDYGzk89QjMQlGLOYcsnw.png" /><figcaption>Firebase App 底下的 d.ts 檔案</figcaption></figure><p>我很好奇他們的 d.ts 檔案是如何產生的，不曉得他們是否能夠用自動化方式產生出描述這麼多的 d.ts，還是只能依靠手動方式建立檔案與維護。</p><p>若有讀者知道他們的做法的話，還請留言補充，非常感謝。</p><h3>2025/05/29 更新</h3><p>我翻到了一篇 TypeScript 的 <a href="https://github.com/microsoft/TypeScript/issues/34860">issue report</a>，看起來是 arrow function 在轉換成 d.ts 時有些狀況。</p><p>目前有幾個方法可以讓 arrow function 的註解留在轉換後的 d.ts 上：</p><h4>轉成 regular function 宣告</h4><pre>/**<br> * your function comment<br> */<br>export function getApp() {<br>  // ...<br>}</pre><p>直接修改宣告方式，一定有效 😅。</p><h4>多備註 @type 在註解上</h4><pre>/**<br> * your function comment<br> * @type {() =&gt; app}<br> */<br>export const getApp = () =&gt; {<br>  // ...<br>}</pre><p>多寫一個 ‘@type’ 在註解上，讓 typescript 調整輸出，這個方法能正確讓註解出現在 d.ts 上。另外要記得 type 的內容要寫對。</p><p>以上兩個方法供參考，大家看自己適用哪個場景囉。</p><p>這篇文章完成了如何在 JavaScript 開發環境下，透過 TypeDoc 建立 API 文件，提供給第三方開發人員進行閱覽。這個系列文暫時告一段落了，我們從加強內部開發團隊的 IntelliSense 開始調整，到第三方開發團隊的 IntelliSense 加強、提供文件，我們提升了許多開發體驗。希望這三篇文章，能夠帶給你們在團隊上的正向調整。</p><p>閱讀完文章後有什麼想法，也歡迎告訴我！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=146bfb567423" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[在 JavaScript 開發環境下改善開發體驗 — 2. 提供 Type Definition File]]></title>
            <link>https://toy9986619.medium.com/%E5%9C%A8-javascript-%E9%96%8B%E7%99%BC%E7%92%B0%E5%A2%83%E4%B8%8B%E6%94%B9%E5%96%84%E9%96%8B%E7%99%BC%E9%AB%94%E9%A9%97-%E6%8F%90%E4%BE%9B-type-defination-file-652b0707a752?source=rss-3f389ee4264c------2</link>
            <guid isPermaLink="false">https://medium.com/p/652b0707a752</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[LiRen Lin]]></dc:creator>
            <pubDate>Tue, 13 May 2025 09:29:05 GMT</pubDate>
            <atom:updated>2025-05-13T12:42:09.847Z</atom:updated>
            <content:encoded><![CDATA[<h3>在 JavaScript 開發環境下改善開發體驗 — 2. 提供 Type Definition File</h3><p>TL;DR，透過 TypeScript 的 tsc 指令，能夠建立出 JavaScript 對應的 d.ts file，讓開發人員能夠在釋出套件時，一起釋出對應的 Type Definition。</p><p>這篇文章會延續上一篇的<a href="https://toy9986619.medium.com/c155cae7c22a">內容</a>與<a href="https://github.com/toy9986619/js-intellisense-support-example">專案</a>，引導開發人員在 JavaScript 專案下，建立釋出套件時可以使用的 Type Definition File。我們的目標是，讓引用套件的第三方開發人員，也能在 IDE 上正確啟用套件的 IntelliSense。</p><p>我們會用到的工具有：</p><ul><li><a href="https://rollupjs.org/introduction/">Rollup</a>，把原始碼透過 Rollup 轉換成 ES 格式與 CommonJS 格式釋出。</li><li>tsc，TypeScript 的官方編譯器，讓他閱讀 JS 檔案產生對應的 d.ts 檔。</li><li><a href="https://github.com/wclr/yalc">yalc</a>，我使用的是 yarn package manager，yalc 可以協助我在本地環境下，測試發布套件後的結果。</li></ul><h3>產生 ES 與 CommonJS 結果</h3><p>現代的 JS 在釋出套件格式上，開始分為 ESModule 與 CommonJS 兩大派陣營。ESModule 的格式比較貼近前端用的方式(import/export)，CommonJS 格式比較貼近 Node.js 所使用的方式(require/export)。如果你的套件未來想提供給前端與 Node.js 環境都能使用，可以對這兩個格式各建構一份 JS Code 的結果，再搭配 package.json 的 “<a href="https://nodejs.org/api/packages.html#conditional-exports">exports</a>” 欄位讓打包工具能找到對應的引入。</p><p>我在專案中撰寫的 rollup config 如下:</p><pre>import { globSync } from &#39;glob&#39;;<br>import path from &#39;node:path&#39;;<br>import { fileURLToPath } from &#39;node:url&#39;;<br><br>const outputDir = &#39;dist&#39;;<br><br>const esBuild = {<br>  input: Object.fromEntries(globSync(&#39;src/**/*.js&#39;).map((file) =&gt; [<br>    path.relative(<br>      &#39;src&#39;,<br>      file.slice(0, file.length - path.extname(file).length)<br>    ),<br>    fileURLToPath(new URL(file, import.meta.url))<br>  ])),<br>  output: {<br>    format: &#39;es&#39;,<br>    dir: `${outputDir}/es`,<br>    sourcemap: true,<br>  },<br>  external: [&quot;eventemitter3&quot;],<br>};<br><br>const commonJsBuild = {<br>  input: Object.fromEntries(globSync(&#39;src/**/*.js&#39;).map((file) =&gt; [<br>    path.relative(<br>      &#39;src&#39;,<br>      file.slice(0, file.length - path.extname(file).length)<br>    ),<br>    fileURLToPath(new URL(file, import.meta.url))<br>  ])),<br>  output: {<br>    format: &#39;cjs&#39;,<br>    dir: `${outputDir}/cjs`,<br>    sourcemap: true,<br>  },<br>  external: [&quot;eventemitter3&quot;],<br>};<br><br>export default [<br>  esBuild,<br>  commonJsBuild,<br>];</pre><p>基本上是使用 <a href="https://rollupjs.org/configuration-options/#input">Rollup 的範例</a>中作些微的修改，將 src 底下的所有 JS 檔案做格式調整後輸出至 dist 資料夾下。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*iS3pPIEjPF2N5gApF4FQmA.png" /><figcaption>輸出的 dist 資料夾樣貌</figcaption></figure><p>接著，我們要調整 package.json 的內容，告知使用 import 與 require 的時候，要從哪裡找尋檔案。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*EO8XsTzGgnU8XUMFqXZvXQ.png" /><figcaption>調整 package.json 的 exports 欄位</figcaption></figure><p>我採用了 <a href="https://nodejs.org/api/packages.html#nested-conditions">Nested conditions</a> 的方式，讓這一個套件在釋出的時候，能有對應的 namespace 去找尋 module API。以範例為例，我如果要用到 app module 公開的 API，我要做的 import 就會長得像：</p><pre>import { getApp } from &#39;js-intellisense-support-example/app&#39;;</pre><h3>建立 Type Definition File</h3><p>接著，我們要對 Source Code 建立出對應的 Type Definition File，提供給引用套件的人員。</p><p>我們需要撰寫 TypeScript 的 config，重點的 config 如下：</p><pre>// tsconfig.json<br><br>{<br>    &quot;compilerOptions&quot;: {<br>        &quot;baseUrl&quot;: &quot;./&quot;,<br>        // 允許使用 JavaScript 檔案<br>        &quot;allowJs&quot;: true,<br>        // 建立 d.ts 檔案<br>        &quot;declaration&quot;: true,<br>        // 建立 d.ts 檔案於何處<br>        &quot;declarationDir&quot;: &quot;dist/types&quot;,<br>        // 只建立 d.ts 檔案，不建立 js 檔案 (在 TypeScript 的一般流程下，ts 檔案需要轉譯成 js 檔案)<br>        &quot;emitDeclarationOnly&quot;: true,<br>        // 告知編譯器引用第三方套件的 types 路徑<br>        &quot;typeRoots&quot;: [<br>            &quot;node_modules/@types&quot;<br>        ],<br>    },<br>    // 只編譯 src 底下的檔案<br>    &quot;include&quot;: [<br>        &quot;src/**/*&quot;<br>    ]<br>}</pre><p>建立完之後，透過 npx 執行 tsc，即可拿到 d.ts 檔案。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*lWNY-k5HTjbv8dKqhn6FKQ.png" /><figcaption>建立 d.ts 的結果</figcaption></figure><p>還記得上一篇文章，我們針對 Auth module 的 onAuthStateChanged API 做了 callback function 的擴充宣告嗎？來看看它在 d.ts 檔案下的結果是什麼：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*-TVepPYI9PpwCvy5g_WCvg.png" /><figcaption>type 有正確引用</figcaption></figure><p>從檔案結果可以看到，我們在原始碼上做的型別加註，tsc 在生產 d.ts 的過程中都有正確的引用。</p><p>建立 Type Definition File 到此完成了，接著要調整 package.json 的 exports 欄位，告知引用套件時要從哪裡找到 Type Definition：</p><pre>{<br>  // ... 其他的 config<br>  &quot;exports&quot;: {<br>    &quot;./app&quot;: {<br>      &quot;types&quot;: &quot;./dist/types/modules/app/index.d.ts&quot;,  // &lt;--新增這個 types 欄位<br>      &quot;import&quot;: &quot;./dist/es/modules/app/index.js&quot;,<br>      &quot;require&quot;: &quot;./dist/cjs/modules/app/index.js&quot;<br>    },<br>    &quot;./auth&quot;: {<br>      &quot;types&quot;: &quot;./dist/types/modules/auth/index.d.ts&quot;,  // &lt;--新增這個 types 欄位<br>      &quot;import&quot;: &quot;./dist/es/modules/auth/index.js&quot;,<br>      &quot;require&quot;: &quot;./dist/cjs/modules/auth/index.js&quot;<br>    }<br>  },<br>}</pre><p>到這邊，釋出套件的準備工作都完成了。</p><h3>測試釋出套件的結果</h3><p>我們透過 yalc 來做釋出套件的結果測試，先在專案根目錄底下執行 push：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*RJsh1WmYNo8yCWE21kQisQ.png" /></figure><p>完成後，我們直接在同一專案下引用套件：</p><pre>yalc add js-intellisense-support-example@1.0.0</pre><p>完成後，開一份 js 的空白檔案，做 import 的測試：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*6MTxm4RW7rwPVbr7kIct6Q.png" /><figcaption>import 測試</figcaption></figure><p>我們可以看到 IDE 成功辨識套件存在，提供 AutoComplete。那我們再測試看看 Auth Module 的 onAuthStateChanged API 的型別。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*B7mIX49CzQtoZwzBq0fq9w.png" /><figcaption>IDE 成功辨識 callback 的 type</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*wMUgkf0anbgnaEGYWuSTRw.png" /><figcaption>IDE 可以提供 callback 的參數會有哪些內容</figcaption></figure><p>IDE 都能正確提供型別的提示與 AutoComplete，至此我們就完成給第三方開發人員的 IntelliSense 加強了。</p><h3>可能發生的狀況</h3><p>因為這一個 SDK 的設計有多個進入點，我們在 package.json 寫了 <a href="https://nodejs.org/api/packages.html#nested-conditions">Nested conditions</a> 的 exports，如果 IDE 沒有識別出套件，且確定有執行 yalc add 引用套件時，可能會需要多寫一些 config：</p><pre>// jsconfig.json<br><br>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;module&quot;: &quot;NodeNext&quot;,<br>    &quot;moduleResolution&quot;: &quot;nodenext&quot;,<br>  }<br>}</pre><p>我的經驗是，加上這兩個欄位設定後，IDE 應該可以正確識別出套件了。</p><h3>同場加映 — d.ts 融合成一份</h3><p>如果你的套件釋出的結果比較特別，你需要把所有的 d.ts 融合成一份 index.d.ts 的話，可以參考看看 <a href="https://github.com/Swatinem/rollup-plugin-dts/tree/master">rollup-plugin-dts</a> 這一個 rollup plugin。通常會適用於套件只有單一進入點且透過打包工具切 chunk 的情境，或是套件的使用方式是建立一份 Instance，所有操作都是透過 Instance 呼叫，而不是透過 import API 進來使用的情境。</p><h3>同場加映 — Path Rewrite</h3><p>多數專案會為了 import 方便而寫了 Path Map，例如用 “@” 表示從 “src/” 路徑開始。</p><pre>// tsconfig<br><br>{<br>  &quot;compilerOptions&quot;: {<br>     // others config<br>     &quot;paths&quot;: {<br>        &quot;@/*&quot;: [&quot;src/*&quot;]<br>     },<br>  },<br>}</pre><p>這時候，我們直接用 tsc 編譯出的 d.ts，並不會直接轉譯出正確的路徑。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*cCX4Z4pySAXyH2owSIHbZw.png" /></figure><p>要解決這個問題，我們可以使用 <a href="https://github.com/Swatinem/rollup-plugin-dts/tree/master">rollup-plugin-dts</a> 這一個 rollup-plugin (沒錯，跟上一個段落提到的 plugin 相同)，在搭配 “<a href="https://www.npmjs.com/package/@rollup/plugin-alias">@rollup/plugin-alias</a>”，讓 rollup 對 d.ts 檔案做轉譯處理。</p><p>首先先調整 rollup.config.mjs 的設定：</p><pre>import { globSync } from &#39;glob&#39;;<br>import path from &#39;node:path&#39;;<br>import { fileURLToPath } from &#39;node:url&#39;;<br>import alias from &#39;@rollup/plugin-alias&#39;;<br>import dts from &#39;rollup-plugin-dts&#39;;<br><br>const esBuild = {<br>  // ... 省略<br>};<br><br>const commonJsBuild = {<br>  // ... 省略<br>};<br><br>const __filename = fileURLToPath(import.meta.url);<br>const __dirname = path.dirname(__filename);<br>const pathResolve = (p) =&gt; path.resolve(__dirname, p);<br><br>const dtsConfig = {<br>  input: Object.fromEntries(<br>    globSync(&#39;dist/types/**/*.d.ts&#39;).map((file) =&gt; [<br>      path.relative(<br>        &#39;dist/types&#39;,<br>        file.slice(0, file.length - &#39;.d.ts&#39;.length)<br>      ),<br>      fileURLToPath(new URL(file, import.meta.url))<br>    ]),<br>  ),<br>  output: {<br>    dir: `${outputDir}/types`,<br>  },<br>  plugins: [<br>    // 處理 path rewrite<br>    alias({<br>      entries: [<br>        { find: &#39;@&#39;, replacement: pathResolve(&#39;./dist/types&#39;) },<br>      ],<br>    }),<br>    // 引用 dts plugin<br>    dts(),<br>  ],<br>};<br><br>export default [<br>  esBuild,<br>  commonJsBuild,<br>  dtsConfig,<br>];</pre><p>如此一來，在執行 rollup 打包的時候，便會把 tsc 產生的 d.ts 檔案做路徑轉換調整。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*1kIdzsfPHnQzDbt5YTyQ9g.png" /><figcaption>路徑轉換完成，可以正確辨識型別</figcaption></figure><p>Build Code 的過程就會變成：</p><ol><li>執行 tsc 拿到 d.ts 檔案。</li><li>執行 rollup 拿到轉譯後的 JS code 與 d.ts 檔案。</li></ol><p>為了避免干擾，會更建議將 tsc 產生 d.ts 檔案的位置做調整，讓 rollup config 轉譯後的 d.ts 檔案放入最終要釋出的資料夾即可。</p><p>這篇文章完成了如何在 JavaScript 開發環境下，透過 TypeScript 建立 d.ts 功能，加強第三方開發人員引用套件時的 IntelliSense。<a href="https://medium.com/@toy9986619/146bfb567423">下一篇文章</a>會引導建立套件的 API Document，讓開發團隊、第三方開發人員能有一份可以閱讀的文件。</p><p>閱讀完文章後有什麼想法，也歡迎告訴我！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=652b0707a752" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[在 JavaScript 開發環境下改善開發體驗 — 1. 加強內部開發的 IntelliSense]]></title>
            <link>https://toy9986619.medium.com/%E5%9C%A8-javascript-%E7%92%B0%E5%A2%83%E4%B8%8B%E6%94%B9%E5%96%84%E9%96%8B%E7%99%BC%E9%AB%94%E9%A9%97-%E5%8A%A0%E5%BC%B7%E5%85%A7%E9%83%A8%E9%96%8B%E7%99%BC%E7%9A%84-intellisense-c155cae7c22a?source=rss-3f389ee4264c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c155cae7c22a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[intellisense]]></category>
            <dc:creator><![CDATA[LiRen Lin]]></dc:creator>
            <pubDate>Tue, 13 May 2025 09:28:36 GMT</pubDate>
            <atom:updated>2025-05-13T12:54:18.055Z</atom:updated>
            <content:encoded><![CDATA[<h3>在 JavaScript 開發環境下改善開發體驗 — 1. 加強內部開發的 IntelliSense</h3><p>TL;DR, 透過 TypeScript 官方的 JSDoc 參考功能，能在 JS 開發環境裡，完成 Intellisense，提供更好的開發體驗。</p><p>在 JavaScript 專案中工作時，我們常常享受它的靈活性與快速開發的優勢，完成需求與製作出許多工具與套件。隨著專案的變化，我們可能會有更多團隊成員加入維護，甚至是我們將套件公開給其他開發人員。此時我們可能要加強 JavaScript 專案的開發體驗：</p><ul><li>讓 IDE 能夠正確提供 IntelliSense，例如 AutoComplete 功能及型別提示。</li><li>提供 API 文件。</li></ul><p>一個 JavaScript 專案要直接轉換為 TypeScript 專案，會有許多負擔，可能需要重新撰寫現有的 Code、開發團隊需要學習 TypeScript 知識與適應開發方式等等。我們可以透過一些簡單的方式，讓專案能維持在 JavaScript 方式開發，又能提供上述所提到的開發體驗。</p><p>這個主題的文章，我預計會寫三篇：</p><ul><li>第一篇：加強 IDE IntelliSence。</li><li>第二篇：提供套件的 Type Definition File，並正確啟用 IDE IntelliSence。</li><li>第三篇：製作 API Doc。</li></ul><p>本文會利用一個<a href="https://github.com/toy9986619/js-intellisense-support-example">簡單的 Code Project</a>，引導加強 IDE IntelliSence。</p><p><a href="https://github.com/toy9986619/js-intellisense-support-example">範例的程式專案</a>參考了 <a href="https://firebase.google.com/docs/reference/js/app.md#app_package">Google Firebase Javascript SDK</a> 的設計，製作了一個小型的 SDK project。我的 IDE 使用 VS Code。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*6Q0Z7edAbJvAG4-eGJnwTg.png" /></figure><p>在這段程式碼中，希望使用者在使用這一個 SDK，要先透過 initApp 這個 API 製作出 SDK 的實體。之後要使用 App 時，要透過 getApp API 獲取。</p><p>這個 SDK 設計提供使用者能建立多個 SDK 實體，只需要在 initApp 時提供 SDK 的名字做區分，並在 getApp 提供相同的名字即可取得該 SDK 實體。</p><p>此時在開發體驗上會面臨到一個問題：getApp 無法正確判別回傳的型別，AutoComplete 功能無法使用。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*dIWG0TgUvj0UgsljtuP43g.png" /><figcaption>initApp 可以正確識別回傳型別</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*uMWOHCR-45jhXzo36zzQvg.png" /><figcaption>getApp 無法識別回傳型別</figcaption></figure><h3>加強型別識別</h3><p>我們可以透過 <a href="https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#param-and-returns">TypeScript 的 JSDoc 參考功能</a>來協助 IDE 識別型別。它採用了 JSDoc 的格式並做了擴充。在這個情境下，我們要對 Map 或是 getApp 的函式進行加註都可以。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*Tw3TOC4ji3vqOsy6ZzwKZA.png" /><figcaption>對 getApp function 做加註</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*OHGaF7OQc04qI8oHtW2v9w.png" /><figcaption>對 _app 這個變數做加註</figcaption></figure><h3>跨檔案加強型別識別</h3><p>我們換到 Auth Module 來看一下，當開發人員要啟用 SDK 的 Auth 服務時，需要呼叫 Auth Module 底下的 getAuth。getAuth 會使用傳入的 SDK 實體去查詢是否已建立過 Auth Service，沒有的話會做 Auth Service 建立與掛載進 SDK 實體中。</p><p>這時，我們的 IDE 在這個 scope 下，無法認識 app 實際上是 SDK 的實體，因此 AutoComplete 失效。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*aC0X7PNwyn_8UbXitSwlFg.png" /><figcaption>IDE 不認識 app 的型別</figcaption></figure><p>這邊我們一樣可以對 getAuth 的 app 參數進行 TSDoc 的加註，但是 App 的參考在其他檔案，而我們這份檔案並沒有直接引用到 App，該怎麼辦呢？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*UwF4owGnl_vv-kjSufoNNw.png" /><figcaption>如何加註 getAuth function?</figcaption></figure><p>我們可以使用 TypeScript Annotations 的 <a href="https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types">import types</a> 功能，讓他跨檔案去獲得型別。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*GTVwfyCF7OQisf8hbzlTWA.png" /><figcaption>IDE 成功獲得型別</figcaption></figure><p>注入進 Class 的變數也能透過相同方式進行加註，讓內部變數獲得型別辨識。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*SYfPMOjiF3ZCoKg-bCwhuQ.png" /></figure><h3>擴充型別定義</h3><p>在 Auth Service 中，設計能夠讓使用者透過 onAuthStateChanged API 監聽 Auth 狀態的變化：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*FVP9G4hnKoEe2tNYUjjTTw.png" /><figcaption>Google Firebase SDK 的範例程式碼</figcaption></figure><p>在此我利用 EventEmitter 製作了類似的功能實作，提供了監聽器 API：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*s3ZkMFX1LQnoI1MCBammVw.png" /></figure><p>目前使用這個 API，會不知道 callback function 裡有哪些參數能使用。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*rO5lvpOAvc0IvWfEsh41DQ.png" /><figcaption>Auto Complete 無法識別</figcaption></figure><p>我們可以建立 ts 檔案進行型別定義的擴充，再透過 TypeScript Document 的 <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-5.html#the-jsdoc-import-tag">import types</a> 做整份檔案的引用。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*6qrRwDNzwSvhsewtSGV0Gg.png" /><figcaption>建立 ts 並撰寫 type 做定義擴充</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*ggf77V2dHCG7fuYW0DERbg.png" /><figcaption>透過 import types 引用整份檔案</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*G7czOEAzpGnHuPdpWJNhqw.png" /><figcaption>Auto Complete 功能正確使用</figcaption></figure><p>如此一來，能夠讓使用者在建立監聽器時，得知 callback function 會回傳哪些參數並提供 Auto Complete。</p><p>至此，對於加強 IntelliSense 的部分，已經告一段落了。</p><p>這篇文章完成了如何在 JavaScript 開發環境下，透過 TypeScript 的加註功能加強 IntelliSense。<a href="https://medium.com/@toy9986619/652b0707a752">下一篇文章</a>會引導建立套件可以用的 Types Definition File，讓引用套件的人員也能正確啟用 IntelliSense。</p><p>閱讀完文章後有什麼想法，也歡迎告訴我！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c155cae7c22a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MacOS 的 Electron App 打包記錄]]></title>
            <link>https://toy9986619.medium.com/macos-%E7%9A%84-electron-app-%E6%89%93%E5%8C%85%E8%A8%98%E9%8C%84-ad8461333709?source=rss-3f389ee4264c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad8461333709</guid>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[electron]]></category>
            <dc:creator><![CDATA[LiRen Lin]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 12:28:21 GMT</pubDate>
            <atom:updated>2025-03-12T12:28:21.978Z</atom:updated>
            <content:encoded><![CDATA[<p>前陣子公司的產品有嘗試過製作 Electron App 來做跨平台的 Desktop App，當時我有處理相關的流程，遇到了一些問題與找到解決方法，因此記錄一下。</p><p>我們最後有成功製作出 MacOS 用的 Electron App，intel (x64) 與 M 系列 (arm64) 晶片都能夠運作。</p><p>這篇文章會大致描述以下的內容：</p><ul><li>打包工具</li><li>Code Sign (簽章)</li><li>Notarize (公證)</li></ul><h3>打包工具</h3><p>我們採用 <a href="https://www.electron.build/">Electron-Builder </a>這套工具，Build Code 過程不麻煩，缺點是官方文件有些內容寫的不是很清楚，要摸索一陣子。</p><p><strong>打包設定</strong></p><p>可以先玩玩看 <a href="https://www.electron.build/#quick-setup-guide">Quick Setup Guide</a> 了解一下基本功能。我們採用的 config 方案是 js file 格式，為了處理檔案路徑。</p><p>幾個我們寫過的重點設定有:</p><ul><li><a href="https://www.electron.build/configuration#files">files</a>: 我們為了縮小 electron app 的體積，只將 build 好、最小化的 JS code 與 electron app 所需要的一些額外的 JS code 打包進 App，因此有寫過這個設定。根據我們之前的測試，安裝完的 App 從 1G 左右的大小，下降至約 300 MB，滿有感的。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*gJWXTHcokVqfLyGw168j8A.png" /><figcaption>只打包了特定的檔案</figcaption></figure><ul><li><a href="https://www.electron.build/mac#target">mac.target</a>: 我們設定打包成 DMG 檔案。另外有設定 arch，因為要 build x64 給 intel CPU 跟 arm64 給 M 系列 CPU 的版本。x64 版本的給 M 系列 CPU 是可以使用的，只是需要透過 <a href="https://support.apple.com/zh-tw/102527">rosetta</a> 進行轉譯運作的版本，能製作 arm64 版本的會更好。<br>另外要說一下，我曾經遇過 arm64 build 的版本，如果不做 Code Sign，發佈出去的 App 別人安裝後打不開，會顯示檔案損毀，x64 版本的沒有這個問題，進行開發測試的時候要注意一下。這點會在後面的 Code Sign 章節再描述一下。</li><li><a href="https://www.electron.build/electron-builder.interface.macconfiguration#entitlements">mac.entitlements</a>: 我們的 App 需要麥克風與相機的權限，需要透過 plist 檔案設定。基底是用<a href="https://github.com/electron-userland/electron-builder/blob/master/packages/app-builder-lib/templates/entitlements.mac.plist">這份檔案</a>下去調整。</li><li><a href="https://www.electron.build/electron-builder.interface.macconfiguration#publish">publish</a>: 如果有用到 Auto Update 功能的話，需要進行相關設定。</li></ul><p><strong>Auto Update (自動更新)</strong></p><p>有測試過他的 Auto Update 功能，他會需要找個網路空間存放新的程式，我們有測試過 Amazon S3 的空間，運作是成功的。最後是因為只做內部測試用，因此沒有部屬 Auto Update 用的檔案，每次更新發佈新的 DMG 檔案讓大家下載安裝。</p><p>Amazon S3 的空間，在 build config 中的 <a href="https://www.electron.build/electron-builder.interface.macconfiguration#publish">publish</a> 設定採用 generic 即可。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*7-9954jeiPmMc9MCLkNrGg.png" /></figure><h3>Code Sign (簽章)</h3><p>Code Sign 主要影響的是 Auto Update 功能能否使用，與執行 App 時的安全性驗證。安全性驗證又關聯到後面會描述的 Notarize (公證)。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*TpTXamGrE9aZgjlek3rwfg.png" /><figcaption>Auto Update 章節有描述 macOS app 需要做 Code Sign</figcaption></figure><p>關於 MacOS 的 Code Sign 準備，Electron-Builder 官方文件<a href="https://www.electron.build/code-signing-mac">在此</a>。基本上是憑證檔案弄好了之後，Electron-Builder 進行打包工作的時候就會一起執行處理。</p><p>我們是製作成沒有上架在 App Store 的版本，因此我們準備了 “Developer ID Application” 憑證。這個憑證需要用 Apple Developer 開發者帳號才能建立。如果是組織型的帳號，需要找到頂層管理員的人員用他的帳號建立，建立後再傳送憑證檔案給開發人員放置進 Key Chain ，或是直接使用 p12 檔案指定給 build 流程中的 “CSC_LINK” 與 “CSC_KEY_PASSWORD” 環境變數進行 Code Sign。</p><p>另外在前述的打包設定時有提到過，沒有做完 Code Sign 的流程，我們有遇到製作 arm64 的 DMG 檔案，只要透過上傳到網路空間在下載到裝置上，安裝完要打開程式時會遇到檔案損毀。建議要做 arm64 版本的人員，Code Sign 流程要做完。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*0HzH5rJe1zGl3EKDnBtrGw.png" /><figcaption>arm64 版本的 App，沒有做 Code Sign 會無法打開</figcaption></figure><h3><strong>Notarize (公證)</strong></h3><p>主要參考<a href="https://kilianvalkhof.com/2019/electron/notarizing-your-electron-application/">這份文件</a>，另外 notarize 的 js module 已經搬家到<a href="https://www.npmjs.com/package/@electron/notarize">這裡</a>了。</p><p>Notarize 流程主要在做的事情是讓 Apple 審核這個 App 是通過認證的。沒有做過 Notarize 的 App，在上傳到網路空間供人下載之後，打開應用程式會被安全性驗證擋下。可以在系統設定的”隱私權與安全性”中將被阻擋的安裝強制進行，但正式發佈時讓使用者進行這個操作並不恰當。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*HpTaZQLx0p6LVdS5GwUvnA.png" /><figcaption>執行程式的時候會被安全驗證擋下</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*3gu8Pawt_wTjaeR1jM7e2w.png" /><figcaption>可以強制開啟，但正式釋出給使用者時並不恰當</figcaption></figure><p>我們的經驗是打包完 Electron App，做完 Code Sign 之後，手動跑 Node.js Script 做 notarize。這邊的流程是需要建立 Apple ID 的 app-specific password 並填入 notarize config 中的 “appleIdPassword”。”appBundleId” 則是跟 build electron app 時填寫的 “appId” 相同即可。</p><p>app-specific password 的建立可以參考<a href="https://support.apple.com/en-us/102654">這份 Apple 文件</a>。</p><p>打包出來的 x64 跟 arm64 版本 Electron App 檔案，都要做過 notarize。</p><p>驗證 Notarize 是否完成的方式，是把 DMG 檔案放到網路空間後再下載下來，安裝後打開 App 不會跳 Apple 無法檢查而擋下開啟即可。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*xXfgz0U81A2Xr7qACm0Iww.png" /><figcaption>Notarize 完成，第一次開啟 App 會是這個提醒</figcaption></figure><p>如果 config 都正確，但遇到 Notarize API 執行失敗，可以看看是不是 Apple 的 ”Developer ID Notary Service” 遇到問題了。可以在<a href="https://developer.apple.com/system-status/">這裡</a>找到 Apple 的 Service Status。</p><h3><strong>其他奇怪的問題</strong></h3><p>如果你有安裝 Anaconda，在做 Electron-Builder 的打包之前，請先做一次 “conda deactivate” 的指令，讓 anaconda 的環境取消。原因是 code sign 的流程中，有指令似乎跟 anaconda 環境下的指令相撞了，因此 code sign 會失敗。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*m8BwdDqxOgfGp_QQI-ueOA.png" /><figcaption>Code Sign 流程失敗</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*5MkN_5cd1O6Rgip7zUEaxA.png" /><figcaption>codesign 指令指到了 anaconda 環境下的 codesign，不符合使用</figcaption></figure><p>以上是簡單的分享，如果有剛好解決到你面臨的問題的話，那就太棒了！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad8461333709" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React 元件效能優化 —  三個會發生效能問題的實作寫法]]></title>
            <link>https://toy9986619.medium.com/react-%E5%85%83%E4%BB%B6%E6%95%88%E8%83%BD%E5%84%AA%E5%8C%96-%E4%B8%89%E5%80%8B%E6%9C%83%E7%99%BC%E7%94%9F%E6%95%88%E8%83%BD%E5%95%8F%E9%A1%8C%E7%9A%84%E5%AF%A6%E4%BD%9C%E5%AF%AB%E6%B3%95-805895f3275c?source=rss-3f389ee4264c------2</link>
            <guid isPermaLink="false">https://medium.com/p/805895f3275c</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[LiRen Lin]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 03:25:08 GMT</pubDate>
            <atom:updated>2024-11-14T03:25:08.219Z</atom:updated>
            <content:encoded><![CDATA[<h3>React 元件效能優化 — 三個會發生效能問題的實作寫法</h3><p>TL;DR，若有使用到以下實作寫法時，可以做一些調整來迴避效能問題。</p><ol><li>Parent Component Rendered，能利用 memo API 做調整。</li><li>Default Value，調整成能固定住初始值的寫法，避免後續渲染更新時產生新的資料，造成子元件更新。</li><li>useSelector，要避免在 useSelector API 的 function scope 內進行資料轉換。</li></ol><p>這次要來分享的是，我在實務上做效能調整的時候，遇過的<strong>三個</strong>容易發生與被忽略，可能會造成效能問題的寫法。同時我也會提供，當遇到這三個狀況時，能怎麼做調整。在開發產品的過程中，如果能注意一下這三個細節，也許能迴避以後要大動作調整專案 codebase 來提昇效能的情況。</p><h3>Parent Component Rendered</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*7AAKZe0ruuuDugmNBu9krg.png" /><figcaption>Parent Component Rendered 示意圖</figcaption></figure><p>第一個要說明的是 Parent Component Rendered。會有這個渲染原因，代表渲染此元件的「<strong>父層元件</strong>」，發生了更新後連帶也重新繪製了這個元件，即使<strong>完全沒有</strong>任何 props, states, contexts 變更。因為渲染機制的過程中，有參與渲染的元件都會產生 Virtual DOM 並與之前的狀態做比對。雖然最後比對的結果可能是不需要更新真實的 DOM，然而比對 Virtual DOM 也是需要時間運算的。如果能夠讓元件不發生渲染比對，也能夠提升程式的效能。</p><p>在這個情況下，讓元件不發生渲染比對的方式是「<a href="https://react.dev/reference/react/memo">memo</a>」API，若是舊制 Class Component 可以使用「<a href="https://react.dev/reference/react/PureComponent">PureComponent</a>」，效果是一樣的。memo API 的做法是，在渲染階段中，若比對出元件的 props 沒有發生變化，則此元件將不會發生新的渲染，React App 將繼續使用舊的 Instance。在一般情況下，API 預設是採用對 props 做淺層比對的方式來加速比較資料的運算。若有特殊情況想做調整的時候，memo API 有提供客製處理 enquality function 的部分，可以參閱官方文件獲得更多的細節。</p><pre>import { memo } from &#39;react&#39;;<br><br>const UserItem = (props) =&gt; {<br>  // ... component implement<br>};<br><br>export default memo(UserItem);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*11UH1GBmb7dE2v14dvXJCg.png" /><figcaption>調整後的 profiler 顯示</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/1*IN__XxKjQUPzKwrgnVEn0A.png" /><figcaption>UserItem 完全沒有參與到渲染過程</figcaption></figure><p>從上面的 profiler 示意圖可以發現，調整後的父層元件「UserList」與它的子節點，整個渲染時間從 8ms 下降到 5ms 左右。若對應的子節點越多，下降差異會更明顯。</p><p>那是不是所有元件都直接套用 memo API 就可以了呢？答案是「否」。原因是 memo API 本身也需要做一個簡易的比對。如果元件本身就時常發生更新，而不是因為遇到「Parent Component Rendered」的渲染原因，反而會造成多餘的運算時間。</p><p>因此，這個 memo API 的調整很適合那些用在元件樹中的 <a href="https://ithelp.ithome.com.tw/articles/10218331">Leaf Node</a>，主要負責顯示畫面內容的元件。至於中間的節點能不能套用，就要看各專案的狀況了。慢慢的從 Leaf Node 往上調整起，會有較少的 Side Effect 發生。</p><p>如果你已經習慣使用「useCallback」、「useMemo」等 API 來固定一些變數的 value 或 memory address，記得檢查一下子節點的元件是否有套用到 memo API 來減緩重新渲染的狀況哦！</p><h3>Default Value</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*d-9jiLf--_6OSn2Q4eicwA.png" /><figcaption>Props 變更</figcaption></figure><p>接下來這個情境要來聊聊 Default Value 的部分了，但它不是指元件的 Default Value，而是資料取用上的 Default Value。</p><p>假設一個情境，你可能透過後端服務的 API 獲得一包資料，而程式要從這一包「巢狀深層物件」資料裡，找到想要顯示在畫面上的資料。因此，你可能有類似這樣的實作：</p><pre>/*<br> * 假設要存取一個深層物件<br> *<br> * 例如：<br> * const responseResult = {<br> *   foo: {<br> *    bar: {<br> *     users: {}<br> *   }<br> * };<br> */<br><br>const Parent = () =&gt; {<br>  // ... component implement<br><br>  const users = responseResult?.foo?.bar?.users || {};<br><br>  return (<br>    &lt;UserList users={users} /&gt;<br>  );  <br>}<br><br>const UserList = (props) =&gt; {<br>  const { users } = props;<br><br>  // ... component implement<br><br>  return (<br>    &lt;div&gt;<br>      {/* component view implement */}<br>    &lt;/div&gt;<br>  )<br>};</pre><p>為了要處理「Backend Response 沒有放預設值」、「畫面渲染時就要先給一個初始值」、「Request 可能發生錯誤」等等原因，因此選擇了深度存取這個物件後，如果找到為 <a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy">falsy</a> 的值，都給予一個空物件作為保險的初始值，同時進行「對非物件的變數存取物件屬性」、「固定 users 為物件」的防錯處理。</p><p>然而這樣的 Default Value 處理方式，卻可能在這個元件發生下一次的渲染時，因為在 runtime 下建立了「<strong>新的空物件</strong>」，讓子元件跟著被觸發渲染。</p><p>遇到這個情況時，從 Profiler 上只能看到「props 變更」的提醒，必須要從子元件的實作一路往上翻，才可能發現是這個實作內容導致的更新。而這個情況，通常發生在「物件」與「陣列」，因為這兩個型別在變數保存時，是保存實體的 Memory Address。</p><p>在這個情況下，你的解決方式可以有以下兩種：</p><ol><li>不在取得資料時設置 Default Value ，依靠元件自身定義的 Default Value。</li><li>設置 Default Value，但是要固定住這個 Default Value 的 Memory Address。</li></ol><h4><strong>不在取得資料時設置 Default Value ，依靠元件自身定義的 Default Value</strong></h4><p>如果 Backend 開發嚴謹，沒有值的時候要嘛不給 key，要嘛已經定義好空值的型態(依照這個範例，應該定義成 Object)，那可以使用這個解決方案。</p><pre>const Parent = () =&gt; {<br>  // ... component implement<br><br>  const users = responseResult?.foo?.bar?.users;<br><br>  return (<br>    &lt;UserList users={users} /&gt;<br>  );<br><br>}<br><br>const UserList = (props = { users: {} }) =&gt; {<br>  const { users = {} } = props;<br><br>  // ... component implement<br><br>  return (<br>    &lt;div&gt;<br>      {/* component view implement */}<br>    &lt;/div&gt;<br>  )<br>};</pre><p>如此一來，只要 props 沒有 users 的 value (值為 undefined 狀態)，便可以利用 JavaScript 的 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">default value</a> 方式處理，迴避 props 會發生變動的情境。</p><h4><strong>設置 Default Value，但是要固定住這個 Default Value 的 Memory Address</strong></h4><p>如果你發現 Backend 回應的空值不是理想的型態，又或是想要弄好防呆防錯，那可以選擇這個方案。</p><pre>// 在不會被渲染執行影響的地方宣告<br>const EMPTY_OBJECT = {};<br><br>const Parent = () =&gt; {<br>  // ... component implement<br><br>  const users = responseResult?.foo?.bar?.users || EMPTY_OBJECT;<br><br>  // 或是可以利用 useMemo 關注資料是否發生變化而重新計算<br>  const users = useMemo(() =&gt; {<br>    return responseResult?.foo?.bar?.users || {};<br>  }, [responseResult?.foo?.bar?.users])<br><br><br>  return (<br>    &lt;UserList users={users} /&gt;<br>  );<br><br>}<br><br>const UserList = (props = { users: {} }) =&gt; {<br>  const { users = {} } = props;<br><br>  // ... component implement<br><br>  return (<br>    &lt;div&gt;<br>      {/* component view implement */}<br>    &lt;/div&gt;<br>  )<br>};</pre><p>固定實體的方式，可以簡單的採用提前宣告，而不在 function 內宣告執行的方式；或是使用 React 的 useMemo API，在資料發生變動時才重新執行計算的方式。</p><p>另外要小心直接修改實體的一些執行，在 React 的開發中會盡量避免直接修改與渲染相關的資料，以免造成不預期的 Side Effect 發生。</p><pre>// 避免這類操作在與渲染有關的資料上<br>const object = {};<br>object.foo = &#39;bar&#39;<br><br>const array = [];<br>array.push(&#39;foo&#39;);</pre><h3>UseSelector</h3><p>這個情境會用 redux 的 <a href="https://react-redux.js.org/api/hooks#useselector">useSelector</a> 作為舉例，我認為它應該會發生在使用外部 State Management 套件時都有機會遇到。</p><p>假設放置了資料在 Global State Management 上，在取用資料的時候，因為想增加後續開發的便利，可能對資料做了一層轉換實作：</p><pre>import { useSelector } from &#39;react-redux&#39;;<br><br>const Parent = () =&gt; {<br>  const users = useSelector((state) =&gt; {<br>    // 假設 return Object 型態的資料<br>    return dataTransform(state.backendData);<br>  });<br><br>  // ... component implement<br><br>  return (<br>    &lt;UserList users={users} /&gt;<br>  );<br>}<br><br>const UserList = (props) =&gt; {<br>  const { users = {} } = props;<br><br>  // ... component implement<br>}</pre><p>一樣的，當 Parent 元件更新的時候，因為元件透過新的渲染過程執行，建立出新的 users 物件，將新的資料帶給子元件，讓子元件也發生更新渲染。</p><p>跟前面 Default Value 描述的很像，從 profiler 上錄製的時候，一樣會看到 props 變更觸發更新的提示。</p><p>在這個情境下，應該把轉換的處理移出 useSelector 的部分：</p><pre>const backendData = useSelector((state) =&gt; {<br>  return state.backendData;<br>});<br><br>// 可以使用 useMemo<br>const users = useMemo(() =&gt; {<br>  return dataTransform(state.backendData);<br>}, [users]);</pre><p>或是使用像是 <a href="https://github.com/reduxjs/reselect">reselect</a> (<a href="https://redux-toolkit.js.org/api/createSelector">createSelector</a>) 的工具：</p><pre>const { createSelector } from &#39;@reduxjs/toolkit&#39;;<br><br>const dataTransformSelector = createSelector(<br>  (state) =&gt; state.backendData,<br>  (backendData) =&gt; dataTransform(backendData),<br>);<br><br>const Parent = () =&gt; {<br>  // ... component implement<br><br>  const users = useSelector(state =&gt; dataTransformSelector(state));<br>}</pre><p>是也可以利用 <a href="https://react-redux.js.org/api/hooks#equality-comparisons-and-updates">useSelector</a> 的 EqualityFn 參數：</p><pre>import { shallowEqual, useSelector } from &#39;react-redux&#39;;<br><br><br>const Parent = () =&gt; {<br>  // ... component implement<br><br>  // 可以應付簡單情境，但是不推薦<br>  // 沒寫好時還是會產生新的渲染<br>  const users = useSelector((state) =&gt; {<br>    return dataTransform(state.backendData);<br>  }, shallowEqual);<br>}</pre><p>但是推薦的做法會將轉換處理的執行拉出 useSelector 外。實際上，redux 的<a href="https://redux.js.org/usage/deriving-data-selectors#optimizing-selectors-with-memoization">官方文件</a>也有拉出一個文章篇幅，講述在 useSelector 的 function scope 內做資料轉換的問題。</p><p>以上是三個我曾經在實務上處理過幾次的案例。回頭看看會覺得，真的是很容易就寫出來的實作。調整它們的手法也不難，可是當產生出效能問題的時候，要找出問題的源頭，是一件不容易的事情。</p><p>閱讀完後有什麼想法、或是有其他的工具、調整做法嗎？歡迎留言分享！</p><p>References:</p><ul><li><a href="https://react.dev/reference/react/memo">React Memo API</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">JavaScript Destructuring Assignment</a></li><li><a href="https://redux.js.org/usage/deriving-data-selectors#optimizing-selectors-with-memoization">Redux — Optimizing Selectors with Memoization</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=805895f3275c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React 元件效能調整 — 資料集更新的影響]]></title>
            <link>https://toy9986619.medium.com/react-%E5%85%83%E4%BB%B6%E6%95%88%E8%83%BD%E8%AA%BF%E6%95%B4-%E8%B3%87%E6%96%99%E9%9B%86%E6%9B%B4%E6%96%B0%E7%9A%84%E5%BD%B1%E9%9F%BF-acde2fdbfd71?source=rss-3f389ee4264c------2</link>
            <guid isPermaLink="false">https://medium.com/p/acde2fdbfd71</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[LiRen Lin]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 10:00:04 GMT</pubDate>
            <atom:updated>2024-11-08T06:30:04.931Z</atom:updated>
            <content:encoded><![CDATA[<h3>React 元件效能調整 — 資料集更新的影響</h3><p>TL;DR，在開發 React Application 的過程中，若是有眾多元件常常引用到同一個資料集時，可以對這類的資料集更新與 React Application 之間做一層隔離，來避免資料集更新時造成多餘的元件渲染更新。</p><p>會讓 React 元件重新渲染，通常有以下幾種情況：</p><ul><li>元件內部的 State 的內容更新。</li><li>元件的 Props 的內容更新。</li><li>元件引用的 Context 的內容更新。</li><li>父層重新渲染，因此跟著重新渲染。</li></ul><p>前三種渲染狀況，都跟元件關注的資料更新後觸發 React 更新渲染有關。常見的效能調整的手法，是盡可能限縮內容更新而觸發的渲染動作，例如固定 props value 跟 context value 等等。元件重新渲染的整個流程中，有一個 Virtual DOM 比對階段，在比對的過程中會需要消耗比較多的運算效能。因此，提升 React App 的效能，通常會以「減少元件更新」的方式下手處理。</p><p>如果有一個在高階層級的資料集，而且 App 內部有很多地方會引用到它，當資料集更新時會發生什麼事情呢？舉個例子，例如 User 資料集，很多元件會需要用 User ID 去跟資料集交換拿到 User 的資料。這個資料集發生更新時，所有引用的元件都需要重新渲染，顯示新的 User 資料。</p><p>這篇文章想要分享的是，如何控制一個資料集發生更新時，要處理的渲染效能問題。</p><h3>基本情境</h3><p>我製作了一份 <a href="https://github.com/toy9986619/chatroom-performance-example/tree/main">chatroom 的簡單程式</a>來舉例。這個 React App 實作了以下的功能：</p><ul><li>簡單的 chatroom，能切換 room、看 room 裡面的訊息，與發送訊息到選定的 room 內。</li><li>Message 元件會有發送人的名字及頭像，頭像會顯示發送人目前的上線狀態。</li><li>右側有簡單的操作面板，可以對 User 做更名與更改狀態，用來模擬觸發 User 資料更新。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LH-V1YJYrARdVgoVA-MkYQ.png" /><figcaption>chatroom 範例圖</figcaption></figure><p>在這個範例程式中，在 React Component Tree 裡有一個高階層的元件” UserDataProvider”，用來保存 User 的資料，以及利用 Context 功能來提供 User 資料給需要引用的元件。</p><p>Message 元件則會透過 “UserDataContext” 來獲得 User 的資料集，並利用 User ID 獲得發送人的資料，來顯示名字與上線狀態。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*1AROOnFZ-dyd4DDjKFWXZw.png" /><figcaption>App 結構簡易描述</figcaption></figure><p>User 的資料在正式的情況下，會透過 API Request 向後端服務獲得。在這個簡單範例中，我們用一份假的資料進行處理。Context 提供資料的部分，在正式情況下也有可能是使用 Global State Manager 的套件(例如 <a href="https://redux-toolkit.js.org/">Redux</a>)進行處理。當 User 變更它的資料，於後端服務保存之後，通常後端服務會推播相關事件，讓前端 App 能實時更新最新的 User 資料。</p><h3><strong>當 User 資料更新時，會發生什麼事情？</strong></h3><p>透過右側的控制面板，如果更改 User 的上線狀態，再利用之前文章提到的 React Profiler 工具，我們可以看到這個結果：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*htSfMBWKV6hxT0kAM-ei9g.gif" /><figcaption>App 更新範圍顯示</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*Y5idfmpnMLtRSu0_Y6cFIA.png" /><figcaption>Profiler 錄製的元件更新</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*KTFbnI0AWBxX7GmiDR8Byg.png" /><figcaption>Chrome Performance 錄製的執行結果</figcaption></figure><p>從這個操作狀況可以發現，我們只更動 User 1 的上線狀態，更新 User 1 的資料，卻也影響到顯示為 User 2 傳送的訊息一起渲染。透過 Profiler 查看原因能得知是 context 變化而跟著更新。</p><p>這個更新原因是因為，為了更新 User 1 的資料，我們在操作頂層的 userMap 更新 User 1 的資料時，也必須讓 userMap 獲得新的 object memory address 來觸發 React 的更新機制。因為這個機制，讓引用到沒有更新的 User 2 資料的 Message 元件也必須進行更新，但這些更新是我們不預期要發生的。</p><p>在這個狀況下，我們要限縮元件引用到的資料範圍，讓更新範圍縮小，減少不必要的元件更新。</p><h3>調整元件更新範圍</h3><p>我在同一份 repo 底下建立了新的<a href="https://github.com/toy9986619/chatroom-performance-example/tree/feature/performanceImprove">分支</a>，來放置調整後的範例程式。</p><p>為了讓引用到的資料範圍縮小，我將 User 資料管理的部分，「獨立」在 React Application 之外。再使用 <a href="https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent">Custom Event</a> 的處理，當 User 資料變化時，發出特定的 Event 做通知。</p><p>在 React Appliaction 這邊，我撰寫了一份 Custom Hooks 提供介面操作。React 元件透過 Hooks 提供的介面獲得 User 資料的時候，會同時監聽這一個 User ID 的 Event。被通知資料有變化的時候，用一個 State 變更來做元件的強制更新，讓下一次的元件渲染可以拿到新的 User 資料。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*4dwV_j5SXkK5iIfykunsVA.png" /><figcaption>調整後的 App 結構簡易描述</figcaption></figure><p>這個結構調整後，用 React Profiler 錄製的更新渲染如下:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*75a8sYmpFjWFC02zWbn8gg.gif" /><figcaption>結構調整後的渲染更新範圍顯示</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*Cnd15TKT0NzPTQ-4O_oEyg.png" /><figcaption>Profiler 錄製的元件更新</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*USMw335WGkppaZ1d1H4cDg.png" /><figcaption>Chrome Performance 錄製的執行結果</figcaption></figure><p>從 React Profiler 錄製的結果可以看到，引用 User 2 的 Message 元件不再進行更新了，Render Duration 也從 14.7 ms 下降至 5.9 ms，減少了約 60 % 的執行時間。用 Chrome Performance 錄製執行過程，Scripting 指標(執行 JavaScript 的時間)也從 205 ms 下降至 173 ms，減少了約 15 % 的執行時間。</p><p>利用這樣子的方式調整，元件關注到的資料範圍變小，即可縮小更新範圍，讓元件被更新觸發的範圍降低。如果需要的話，還能擴充事件，再針對資料下特定的屬性變更時才通知關注者進行處理。</p><h3>有沒有其他做法？</h3><p>上述調整的方式並不是唯一的調整可能性，它是好移植且能彈性運用在各種情境下的方式。</p><p>對於簡易需求與範例程式中的 Message 元件，它算是很好針對調整的對象。原因是需要 User 資料的部分只有顯示傳送者，來源只有 message 資料下的 userId，因此是可以讓 Message 元件不要直接接觸 UserDataContext 就好。我們可以在 Message 元件外面多做一層 Container，讓它先準備好需要轉換的 User 資料，再轉交給 Message 元件做處理。只要 Message 元件的 <a href="https://react.dev/reference/react/memo">memo</a> 處理得當，在 Context Value 更新的時候，也只會有 Container 層進行處理，減少會直接影響 DOM 層的元件發生渲染。</p><p>如果需求變得更複雜，例如要滿足訊息內容中發生「mention」而顯示被 mention 的 user 資料，或是在不同場景下要取用的資料來源會不同時，這層 Container 可能會不容易撰寫。</p><h3>這個調整值得嗎?</h3><p>以範例程式來說，並沒有真的模擬出會造成負擔的渲染結果，因為程式太簡單了，調整前後的 Render Duration 只差了 8 ms 左右，依照現在電腦強大的運算能力下，這個差異很難感受得到。</p><p>但是在真實複雜的專案下，一個元件更新可能需要的 Render Duration 會較多。當 App 掛載很多引用同一資料集的元件時，更新時所造成的負擔會比較大。如果資料集更新的很頻繁，也會加重渲染的負擔。如果在實際的開發上有遇到類似的情境，導致 App 運作有卡卡的現象，可以嘗試看看這種方案來降低更新資料時產生的渲染負擔，我也曾運用過這個方式來調整產品的效能。</p><p>另外，在學習 React 的過程中，也常常會學習到 API Fetch 回來的結果，放在大的 Global State (例如 Redux)之下。這個情境也能提供一個思考方向，是不是有些內容不直接放在 Global State 下，額外獨立出來再跟 React App 做整合會比較好。</p><p>以上是我在資料集更新的效能調整分享，如果你有面臨到類似的狀況，可以嘗試看看這樣的調整方式。</p><p>閱讀完後有什麼想法、或是有其他的工具、調整做法嗎？歡迎留言分享！</p><p>Reference:</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent">Custom Event</a></li><li><a href="https://react.dev/reference/react/memo">React memo</a></li><li><a href="https://github.com/toy9986619/chatroom-performance-example/tree/main">Github Repo — Example Code</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acde2fdbfd71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React 元件效能調整 — 效能調整如何起步]]></title>
            <link>https://toy9986619.medium.com/react-%E5%85%83%E4%BB%B6%E6%95%88%E8%83%BD%E8%AA%BF%E6%95%B4-%E6%95%88%E8%83%BD%E8%AA%BF%E6%95%B4%E5%A6%82%E4%BD%95%E8%B5%B7%E6%AD%A5-b1aff90ebb0e?source=rss-3f389ee4264c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1aff90ebb0e</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[LiRen Lin]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 07:48:31 GMT</pubDate>
            <atom:updated>2024-10-23T07:48:31.060Z</atom:updated>
            <content:encoded><![CDATA[<h3>React 元件效能調整 — 效能調整如何起步</h3><p>開發 Web Application 的過程中，通常會以滿足需求項目為首要目標。當 Application 的功能越來越多，各個元件複雜的交互作用之下，Application 的效能問題可能會開始浮現：程式跑很慢、畫面卡頓，造成使用者操作不順利。</p><p>在使用 React 的情況下，我們如何在面對效能問題時，進行相關的效能調整呢？我想利用幾篇文章的分享，紀錄下我在這部分學習到的內容。預計後續想再撰寫幾篇文章來提到如何觀察性能問題，並提供幾個實際的例子進行解釋。</p><p>這篇文章會帶到以下的內容：</p><ul><li>什麼時候學習、處理效能調整</li><li>定位會造成效能問題的動作</li><li>運用工具找尋會造成效能問題的元件</li></ul><h3>什麼時候學習、處理效能調整</h3><p>效能問題要先有程式正在運作中才會發現，在學習與開發的初期階段中，效能調整的重要性並不會太明顯。</p><p>在我的個人經驗中，早期階段並不容易也不適合處理效能調整。第一個原因是「很難對效能問題有明顯的感受」，例如無法想像畫面會如何卡住、無法想像後續開始進行調整時，會需要多大的付出；第二個原因是「投入的資源不容易量化出價值」，沒有調整前後的效能資料對比的狀態下，很難認定會改善多少。有可能發生投入了很長的時間做調整，但只換到一點點的提升，整理評估下是不划算的。也可能發生原本想像會產生的事情，在實際操作場景下並不會真的造成出問題；第三個原因是「有些效能調整會帶來程式碼閱讀性方面的下降」，對維護方面會需要其他輔助（例如註解）來進行補強。</p><p>我認為，當有人回報相關的 issue 時，或是真實進行操作而發現明顯的效能問題時，會是很好的學習與進行調整的時間。</p><h3>定位會造成效能問題的動作</h3><p>幾個常見得知發生效能問題的時間點是：</p><ol><li>開發過程中，由開發人員自行發現。</li><li>提交測試後，由測試人員進行驗證與壓力測試時發現。</li></ol><p>透過操作回報，開發人員復現出效能問題後，從復現過程中找尋會造成效能問題的動作。例如：在 chatroom input bar 快速輸入文字、在監控的功能面板下進行動作時畫面會卡住，反應很慢等等。</p><h3>運用工具找尋會造成效能問題的元件</h3><p>在 React 的框架下，大多導致效能問題的原因，是過多的 React 元件更新與渲染。我們 React 官方提供的工具，來嘗試找尋看看是不是這樣子的原因。</p><p>React 官方提供了 「<a href="https://react.dev/learn/react-developer-tools">React DevTools</a>」進行開發過程的除錯，其中有一個面板是「Profiler」。在 Profiler 面板下，可以錄製會導致效能問題的操作過程，並從 Profiler 錄下的資料中，找到每個元件的渲染時間與渲染原因。</p><p>若找到是元件渲染過久，且觀察到不必要的渲染更新，例如不預期會有的 props, state 的更新的狀況時，我們可以從減少渲染更新的方向著手處理。</p><p>關於 Profiler 的操作，可以參考以下的文章：</p><ul><li><a href="https://zh-hant.legacy.reactjs.org/blog/2018/09/10/introducing-the-react-profiler.html">Introducing the React Profiler</a></li></ul><p>Profiler 的設定，我會加開「Profiler」&gt;「Record why each component rendered while profiling」的選項，可以得知元件是因為什麼原因而重新渲染。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*3udZqocPMP9Rs6Dc96Yapw.png" /></figure><p>另一個可以用來找尋執行時間的工具是「Chrome DevTools」，在「Performance」分頁下可以進行錄製操作並分析 JavaScript 的執行狀態。</p><p>藉由這個工具，可以量化 JavaScript function 的執行時間，用來找尋是否有哪些 JS function 執行起來是厚重的，進而調整 function 的實作，減少執行 function 的次數、調整時間複雜度等等。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*KouMPYlpZWWPmCAt4op2qQ.png" /><figcaption>Chrome DevTools — Performance Sample</figcaption></figure><p>關於這個工具，可以參考以下文章：</p><ul><li><a href="https://developer.chrome.com/docs/devtools/performance/reference?hl=zh-tw">效能功能參考資料</a></li></ul><p>在這篇文章之後，我想分享一些實際遇到的案例、分析原因與如何進行調整，希望我能夠順利的把這些文章分享出來！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1aff90ebb0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React 元件設計經驗談 - 高階元件(HoC)還需要存在嗎?]]></title>
            <link>https://toy9986619.medium.com/react-%E5%85%83%E4%BB%B6%E8%A8%AD%E8%A8%88%E7%B6%93%E9%A9%97%E8%AB%87-%E9%AB%98%E9%9A%8E%E5%85%83%E4%BB%B6-hoc-%E9%82%84%E9%9C%80%E8%A6%81%E5%AD%98%E5%9C%A8%E5%97%8E-7b894feca747?source=rss-3f389ee4264c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b894feca747</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[LiRen Lin]]></dc:creator>
            <pubDate>Tue, 04 Jun 2024 13:49:32 GMT</pubDate>
            <atom:updated>2024-06-26T03:38:59.331Z</atom:updated>
            <content:encoded><![CDATA[<p>回顧這幾年的工作過程裡，用了 HoC Pattern 處理了一些情境。突然想到從 Hooks 誕生之後，HoC 的使用率就降低了很多。因此想記錄一下 HoC Pattern 在 2024 年的 React 生態中，還有沒有需要存在？以及它適合處理那些問題。</p><h3><strong>HoC 簡介</strong></h3><p>高階元件(High Order Component, HoC) 是 React 還在 Class Component 時期，作為邏輯重複使用的重要工具之一。</p><p>一個 HoC 的語法長得像這個樣子：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*orBxpDN6zso8rPKVjLuG3g.png" /><figcaption>HoC 簡單介紹</figcaption></figure><p>透過多一層的 Wrapper Component，將一些可以重複使用的邏輯、資料處理好之後，再將內容注入到目標的元件上。用 Function 的方式處理，可以輕鬆的重複使用在各個元件上，並且依據需求套用、移除這些內容注入。</p><p>需要更詳細的說明的話，歡迎前往到<a href="https://legacy.reactjs.org/docs/higher-order-components.html">舊版的官網</a>查詢。</p><p>但是現在在<a href="https://react.dev/">新版的 React 官網</a>已經找不到 HoC 的章節了，<a href="https://legacy.reactjs.org/docs/higher-order-components.html">舊版的官網</a>也將 HoC Pattern 標記成不推薦使用。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0PUcNJzkMEQMiF0yhk338Q.png" /><figcaption>新的官網搜尋不到 HoC 的相關內容了</figcaption></figure><p>現在的 React 生態系下，需要邏輯重複使用的部分，大多都能用 Custom Hook 做邏輯的關注進行分割與重複使用。那 HoC pattern 在甚麼情況下需要拿出來使用呢？</p><h3>HoC 適用的場景</h3><h4>維護舊的 Class Component</h4><p>並非所有專案都已經將所有 Component 搬遷至 Function Component 並搭配 Hooks 的寫法，因此在 Class Component 的設計下，還是需要 HoC Pattern作為邏輯重複使用的重要工具，這也是最常出現的場景。</p><p>即使新的邏輯採用 Hooks 方式撰寫了，因為 Class Component 無法直接使用 Hooks，需要 HoC Pattern 撰寫一個 Function Component 的 Wrapper 元件來引用 Hooks，並視情況注入至子層的 Class Component。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*TRADBGGtOetM5wZ89tI2vQ.png" /><figcaption>引用 Custom Hooks 並注入在 Class Component 上</figcaption></figure><h4>強制性的父子層關係</h4><p>HoC pattern 的本質，就是在繪製目標的 Component 前，多繪製了一個 Component 並把目標 Component 作為自己的 Children 處理。這個<strong>強制性父子層關係</strong>的特性，在特定的情境下有可以發揮的空間。</p><p>我在實務上利用此特性而拿來使用的情境，有一部分是在既有的元件上需要做一些注重父子層關係的調整。</p><p>有什麼情境是注重父子層關係的調整呢？舉例來說，假設我需要在現有的元件上添加 Context，確保從這個元件到它的子元件群，都能夠通過 Context 獲得狀態和方法。在這個例子中，其他元件可能已經為該 Context 提供了相關的值，並設計了相關的 Hooks 供調用。然而，若我需要從當前元件就開始使用該 Context 的內容，則必須確保 Context Provider 的渲染層級高於當前元件，這樣 Context 才能在所有子元件中生效，甚至 Context 都是分離獨立的狀態。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*25-1VPl7EYs_SG0qW6hD-g.png" /><figcaption>臨時需要幫設計好的元件加上 Context</figcaption></figure><p>另一個例子是當某些特定邏輯的執行順序會影響渲染結果時，這也是需要注重父子層關係的情況。舉例來說，如果需要在渲染一個現有的 Component 之前執行檢查邏輯，並且檢查不通過時不進行渲染。我們可以在 Component 中使用一個檢查 Flag 的 state，當 Flag 為 False 時執行 Early Return，來阻止後續的渲染動作。然而，這種方法依然會執行 Component 中的其他副作用（Side Effect），即使這些副作用在檢查不通過時是不必要的。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*o2FpWL2FS3QxJBXhNtIBpw.png" /><figcaption>Early Return Case</figcaption></figure><p>在這些場景下，若不透過 HoC Pattern 處理時，我們可以選擇寫一個新的 Parent Component，將我們想要的邏輯寫在內，然後渲染 Children，並將此 Component 渲染在目標元件的父層上。然而，若這個現有的目標元件已經在整個 App 內多次被調用，我們需要修改多處既有的元件內容，這樣做既費時又容易導致語義丟失。另一種方式是寫一個新的 Component 並在其中渲染舊的 Component，可以盡可能保留舊元件的語義，但這種方法同樣需要在應用的多個地方替換舊的 Component，這會帶來一定的成本。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*jYIiErG3uTkP_UPHKTNdTA.png" /><figcaption>因應調整而修改多處既有內容</figcaption></figure><p>使用 HoC Pattern 可以更簡單地處理這類問題。例如，在 Context 的情境中，可以將 Context Provider 包裝在 HoC 中，再將 HoC 應用到指定的 Component 上，這樣就能確保 Context Provider 一定在父層。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*qpjRsCr5sVbxHj5wr4fbXA.png" /><figcaption>Context Provider Sample Code</figcaption></figure><p>在需要 Early Return 的情況下，可以將檢查邏輯和 Early Return 的邏輯放入 HoC 中，這樣既能輕鬆實現效果，又不影響現有 Component 的實現。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*BrI75pXnojMycBPSH-WkAQ.png" /><figcaption>Early Return Sample Code</figcaption></figure><h3>捨棄 HoC Pattern 的原因</h3><p>HoC Pattern 被逐漸捨棄掉的原因，我個人的理解有以下幾個原因：</p><p><strong>「重複利用邏輯」的運用主因被 Custom Hooks 取代</strong></p><p>現在的 React Component 風格往 Function Component 靠攏，Class Component 逐漸被淘汰掉，Custom Hooks 的寫法更符合關注邏輯與切割的形式，也較為簡易使用。</p><p><strong>層疊 Component</strong></p><p>HoC Pattern 會讓目標的 Component 在父層強制渲染一個 Wrapper Component，從元件樹看結構有多層 Component，呈現類似「Component Hell」的狀況。多層的 Component 在 debug 與調整效能優化的時候，可能不容易找出問題點在哪。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*TLieaa-RRyFabw7NwoeEfA.png" /><figcaption>元件的樹狀圖很可怕</figcaption></figure><p><strong>模糊的 Component Props 與管理困擾</strong></p><p>透過 HoC 注入的 Component Props，其實不易直接從目標元件與直接調用渲染它的父元件，在交叉比對時看出來，會需要一些配套措施。例如從定義 Component PropTypes 時，註解說明從哪一個 HoC 注入這一個 Props。另外，若有多層 HoC 的調用，如果某一層 HoC 臨時需要引用新的 Props 時，也可能在設計上容易發生 Props 傳遞的地獄，不容易知道該 Props Data 究竟是哪一層 HoC 需要使用的。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*wk_4ikEe3DXNh14VN26F6w.png" /><figcaption>HoC 一多，管理起來很困擾</figcaption></figure><p><strong>HoC 不容易在 Runtime 下進行調整</strong></p><p>HoC 的 function 引用在建立 Component 時就會決定了。如果在 Runtime 下有需要傳遞變數進行流程上的調整，可能得使用 props 傳遞進 HoC 層處理，在許多場合下這個操作會過於僵化，不太適合現在的開發方式。改用 Hooks 可以較方便的從 Runtime 下傳遞變數調整流程。</p><p><strong>Props 命名衝突</strong></p><p>Props 的命名在傳遞時就確定了，引用 HoC 時傳遞的 props 與 component 的 props 可能有命名衝突，導致資料不如預期。</p><h3>總結</h3><p>現在 React 生態系應該是<strong>不推薦</strong> HoC 這個寫法了，在 google 搜尋 HoC Pattern 的討論，可以發現一個 <a href="https://www.reddit.com/r/reactjs/comments/17ee7gs/hochigherorder_components_are_not_commonly_used/">Reddit 討論串</a>，底下的回覆也是說大部分的使用場景都可以讓 Hooks 取代並做的更好，甚至說 HoC 是魔鬼 😆。</p><p>除了維護 Class Component 可能是目前不容易取代的需求外，其他的使用方式會是在調整既有的 Component 下，考量執行需求、測試、上線的成本時所做出的決定。如果是重新設計、建立一個 Component，能迴避 HoC 的寫法對長期的維護成本會比較好。</p><p>認識、複習一下老方法，或許有一天能在真實情境上派上用場。</p><h3>Reference</h3><ul><li><a href="https://legacy.reactjs.org/docs/higher-order-components.html">https://legacy.reactjs.org/docs/higher-order-components.html</a></li><li><a href="https://www.reddit.com/r/reactjs/comments/17ee7gs/hochigherorder_components_are_not_commonly_used/">Reddit 討論串 — HOC(Higher-order components) are not commonly used in modern React code</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b894feca747" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Component Design Experience — Leveraging Promises for Process Control (Translate with…]]></title>
            <link>https://toy9986619.medium.com/react-component-design-experience-leveraging-promises-for-process-control-translate-with-77c4683b6543?source=rss-3f389ee4264c------2</link>
            <guid isPermaLink="false">https://medium.com/p/77c4683b6543</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[LiRen Lin]]></dc:creator>
            <pubDate>Sat, 17 Jun 2023 09:02:19 GMT</pubDate>
            <atom:updated>2023-08-21T03:18:03.712Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Component Design Experience — Leveraging Promises for Process Control (Translate with ChatGPT)</h3><p>My origin topic is <a href="https://toy9986619.medium.com/7bde713bd2b5">here</a>. This is translated with ChatGPT.</p><p>Today, I would like to share a process control design approach that I have been using in practice and find quite effective. Therefore, I would like to document my design ideas for readers to reference and also hope to receive some feedback.</p><p>This sample code will be implemented using MUI components.</p><p>Let’s assume a requirement scenario as follows: Create a functionality to display and edit an article. There will be an area to display the article content, and when the edit button is pressed, it switches to edit mode. Users can enter content in a text editing area, and upon pressing the save button, the content is submitted, while pressing the cancel button cancels the editing.</p><p>Here, I will simulate the scenario using a simple approach:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpromise-fan-li-1-t1ou6f%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark%26view%3Dpreview&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpromise-fan-li-1-t1ou6f%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark%26view%3Dpreview&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Ft1ou6f%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8d2d855ee453ebeca53b0c8d1e82f5e/href">https://medium.com/media/c8d2d855ee453ebeca53b0c8d1e82f5e/href</a></iframe><p>Then, suddenly, a detailed requirement emerged: When the cancel button is pressed, a confirmation dialog must be displayed to prevent accidentally switching back while the user is in the middle of entering content.</p><p>It sounds reasonable, so we proceeded to integrate a Dialog:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpromise-fan-li-2-dialog-qnmoyj%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpromise-fan-li-2-dialog-qnmoyj%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fqnmoyj%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/9953133fc7f4f35b15b7a7a4d608a80c/href">https://medium.com/media/9953133fc7f4f35b15b7a7a4d608a80c/href</a></iframe><p>Alright! Everything seems to be working fine! But in order to add a confirmation dialog, we made the following changes:</p><ul><li>Added a dialog component and implemented three methods related to dialog operations.</li><li>Replaced the onClick event of the cancel button with a method to open the dialog.</li><li>Defined the onClick behavior of the confirmation button in the dialog to close the dialog and switch back to display mode.</li></ul><p>As a result, in order to track the entire process of canceling the editing, one must have a comprehensive understanding of the interaction and implementation of all the components. When developers first look at the code, they will only see that the cancel button opens the dialog, and they need to track the relevant implementation of the dialog to know that it switches back to display mode upon confirming in the dialog. It seems that it would take some time to understand the entire flow, and the related methods need to be re-bound to their corresponding components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*K0cIn4ip5M4gkmDQWs9izg.png" /><figcaption>Before and after implementation comparison</figcaption></figure><p>In this example, there is only one dialog, so the implementation burden is relatively small. However, if there are additional confirmation dialog steps to be inserted in between, the methods bound between components would need to be moved again, making it increasingly difficult to track the semantic flow of events throughout the process. Alternatively, if this entire set of requirement flows needs to be replicated in other requirements or components, it would also impose a burden on developers during the transplantation process.</p><p>I also asked ChatGPT how it would handle the implementation approach for confirmation flows, and it provided a similar answer to the implementation mentioned above.</p><p>To address the growing disconnect between the process flow and the written code, I started thinking about using Promises. Promises are commonly used to handle asynchronous tasks. They allow the environment to proceed with other tasks while awaiting a response from an asynchronous task. Once the asynchronous task is completed and notifies the system, it can then continue with the subsequent execution of that task. In the case of this requirement, the task of “confirming if the user really wants to cancel the edit” seems to be a perfect fit for an asynchronous task.</p><p>Therefore, I want to design a solution where the cancel edit button can maintain its binding to the handleCancelEdit method while wrapping the confirmation process within the handleCancelEdit process itself.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpromise-fan-li-3-promise-efy1do%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark%26view%3Deditor&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpromise-fan-li-3-promise-efy1do%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark%26view%3Deditor&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fefy1do%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/49575062f38408511c4cb4e86ea84fd0/href">https://medium.com/media/49575062f38408511c4cb4e86ea84fd0/href</a></iframe><p>In this implementation, I created a Promise controller (PromiseController) to control the Promises that will be used later. I kept the cancel edit button bound to the handleCancelEdit method but added the checkUserConfirm method within its flow. checkUserConfirm opens the dialog component and requests a Promise from the PromiseController while waiting for a response. The button implementation in the dialog component handles not only whether the dialog should continue to be displayed but also resolves the Promise. I made the confirmation button resolve with true using the PromiseController, while the cancel button resolves with false. This way, when the Promise is resolved and provides a response, the handleCancelEdit flow can check the obtained Promise result and decide whether to continue execution or perform an early return to end the process.</p><p>The benefit of this implementation is that developers can more easily understand what will happen within the handleCancelEdit flow. There is minimal modification to the event bindings between components, ensuring correct semantics and easier process tracking. The implementation of user confirmation is encapsulated within the checkUserConfirm method, enhancing semantic expression through naming. This approach significantly reduces the burden for individuals maintaining the requirements but not focusing on the confirmation process implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9FFBEjqIJJV_7WNl3zUq4w.png" /><figcaption>Comparison Before and After Implementation Using Promises</figcaption></figure><p>If we want to transplant and reuse this user confirmation requirement, this approach can also be quickly encapsulated and transplanted. We can utilize custom hooks to wrap the dialog component and provide the component instance along with the relevant methods. When implementing a component that requires a confirmation step, we can import and use this custom hook, render the component instance (dialog component) provided by the hook, and conveniently call the checkUserConfirm method within the confirmation process.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpromise-fan-li-4-hooks-tdc3du%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark%26view%3Deditor&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpromise-fan-li-4-hooks-tdc3du%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark%26view%3Deditor&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Ftdc3du%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/c86cb03a407440af2ffda8a6204c3891/href">https://medium.com/media/c86cb03a407440af2ffda8a6204c3891/href</a></iframe><p>To summarize the benefits of designing using this approach:</p><ol><li>Easy to track requirement flow: The flow of the requirements is easily traceable, and the code semantics remain closely aligned with the intended logic.</li><li>Minimal adjustments between components: When adding new flows, there is no need to make significant changes to the event bindings between components.</li><li>Easy to encapsulate and reuse: The process can be encapsulated and reused effectively, making it convenient to implement similar confirmation flows.</li></ol><p>The above is a design approach I have personally used in practice. I believe this design addresses some of the challenges I faced and allows for easy adjustments when new requirements arise. If you encounter scenarios that require process checks and confirmations, or situations where you need to wait for a response for an extended period without knowing when it will arrive, I recommend giving this design approach a try!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77c4683b6543" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React 元件設計經驗談 — 善用 Promise 作流程控制]]></title>
            <link>https://toy9986619.medium.com/react-%E5%85%83%E4%BB%B6%E8%A8%AD%E8%A8%88%E7%B6%93%E9%A9%97%E8%AB%87-%E5%96%84%E7%94%A8-promise-%E4%BD%9C%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6-7bde713bd2b5?source=rss-3f389ee4264c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bde713bd2b5</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[LiRen Lin]]></dc:creator>
            <pubDate>Mon, 01 May 2023 12:34:20 GMT</pubDate>
            <atom:updated>2023-05-01T16:42:49.605Z</atom:updated>
            <content:encoded><![CDATA[<h3>React 元件設計經驗談 — 善用 Promise 作流程控制</h3><p>今天想分享的流程控制設計方式，是我在實務上使用了一陣子，覺得滿不錯的做法。因此想記錄我的設計想法，提供給讀者參考，也希望能夠獲得一些回饋。</p><p>這次的 sample code 會搭配 MUI 元件做實作。</p><p>假設有一個需求場景描述如下：製作一個顯示與編輯文章的功能。會有一個區域顯示文章內容，按下編輯按鈕切換至編輯模式。使用者可以在一個文字編輯區域內輸入內容，按下保存鍵後將內容送出，按下取消鍵取消編輯。</p><p>在此我用簡單的方式模擬一下：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpromise-fan-li-1-t1ou6f%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark%26view%3Dpreview&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpromise-fan-li-1-t1ou6f%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark%26view%3Dpreview&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Ft1ou6f%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8d2d855ee453ebeca53b0c8d1e82f5e/href">https://medium.com/media/c8d2d855ee453ebeca53b0c8d1e82f5e/href</a></iframe><p>這時候突然有個需求細節出來了：按下取消鍵的時候，必須要跳一個確認對話框，避免使用者輸入到一半後誤觸被切換回去。</p><p>聽起來很合理，於是我們開始串了一個 Dialog：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpromise-fan-li-2-dialog-qnmoyj%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpromise-fan-li-2-dialog-qnmoyj%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fqnmoyj%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/9953133fc7f4f35b15b7a7a4d608a80c/href">https://medium.com/media/9953133fc7f4f35b15b7a7a4d608a80c/href</a></iframe><p>OK！ 一切看起來運作正常！</p><p>但為了加一個確認對話框，我們有了以下的改動:</p><ol><li>新增對話框元件，並寫了三個跟對話框操作有關的 method</li><li>把原先取消鍵的 onClick 置換成開啟對話框的 method</li><li>讓對話框的確認鍵的 onClick 行為，執行到關閉對話框與轉回顯示模式</li></ol><p>如此一來要追蹤整個取消編輯的流程，就要完整的了解所有元件的交互作用與實作。開發人員第一時間看程式碼只會看到取消鍵會打開對話框，還要追蹤對話框的相關實作，才會知道在對話框按下確認後會執行轉回顯示模式。這樣要了解整個流程似乎會花費不少時間，相關的 Method 也要重新綁定在對應的元件上。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*K0cIn4ip5M4gkmDQWs9izg.png" /><figcaption>實作前後對比</figcaption></figure><p>這一個例子只有一個對話框，在實作上的負擔是比較小。如果有些需求在中間又要安插其他對話框的確認環節，元件之間綁定的 method 會要再次地移來移去，覺得語意上要追蹤整個流程發生的事情越來越難了；又或是這整組需求流程要重複移植在其他需求或元件上，在移植時也會對開發人員造成負擔。</p><p>我也問了 ChatGPT 對於這種要做確認流程的實作方式會如何處理，它給了跟上述實作類似的答案。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*xkvSXcmLIsBenV3foq2-ww.png" /><figcaption>chatGPT 給予的回應，中間的 sample code 已省略</figcaption></figure><p>為了解決流程與撰寫的程式碼語意越來越脫離，我把腦筋動到了 Promise 上。常見用在 Promise 的時候是要處理一個非同步的工作。讓環境在非同步工作尚未給予回應前先去處理其他工作，等到這份非同步工作完成並通知時，再回頭處理這一個非同步工作的後續執行。對這個需求而言，這一個「確認使用者是真的要做取消編輯」的事情不就剛好是一個<strong>非同步工作</strong>嗎？</p><p>因此我想設計出，讓取消編輯按鍵能維持 handleCancelEdit method 的綁定，把確認的流程包裝在 handleCancelEdit 的過程裡。</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpromise-fan-li-3-promise-efy1do%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark%26view%3Deditor&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpromise-fan-li-3-promise-efy1do%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark%26view%3Deditor&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fefy1do%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/49575062f38408511c4cb4e86ea84fd0/href">https://medium.com/media/49575062f38408511c4cb4e86ea84fd0/href</a></iframe><p>在這一個實作中，我做了一個用來控制 Promise 的控制器 (PromiseController)，以便用於待會的 Promise 操作。我讓取消編輯按鍵維持綁定 handleCancelEdit method，只是在它的流程中增加了 checkUserConfirm 的 method 執行。checkUserConfirm 會開啟對話框元件，並向 PromiseController 要求一個 promise 並等候回應。對話框的按鍵實作除了要處理對話框的是否繼續顯示之外，還要做 resolve promise 的動作。我讓確認鍵的行為用 PromiseController 做 resolve true，讓取消鍵做 resolve false。如此一來，當 promise 被 resolve 並給予回應時，就可以在 handleCancelEdit 的流程中針對拿到的 promise result 做是否繼續執行，還是要做 early return 提早結束流程。</p><p>這樣實作的好處在於，開發人員可以較容易地了解 handleCancelEdit 流程會發生的事情。元件之間綁定的事件也不會做太多修改，語意正確，追蹤流程較為容易。如何實作使用者確認的方式，也被封裝在 checkUserConfirm method 裡面，並透過命名的方式加強語意表達。對於要維護需求但沒那麼在意確認流程實作的人員，能減輕很多負擔。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9FFBEjqIJJV_7WNl3zUq4w.png" /><figcaption>Promise 方式的實作前後比對圖</figcaption></figure><p>如果要移植並重複使用這一個確認使用者操作的需求，這一個方式也能迅速的包裝並移植。我們可以利用 custom hooks 來把對話框元件包裝起來，並提供元件實體與相關的 method 。需要實作確認環節的元件，引用這一個 hooks 之後，渲染 hooks 提供的元件實體(對話框元件)，並在需要做確認的流程中呼叫 checkUserConfirm method，相當的方便。</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpromise-fan-li-4-hooks-tdc3du%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark%26view%3Deditor&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpromise-fan-li-4-hooks-tdc3du%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark%26view%3Deditor&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Ftdc3du%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/c86cb03a407440af2ffda8a6204c3891/href">https://medium.com/media/c86cb03a407440af2ffda8a6204c3891/href</a></iframe><p>總結一下用這個方式設計的好處：</p><ul><li>易於追蹤需求流程，程式碼語意不會脫離太多。</li><li>加入新的流程時，不需調整太多元件之間的綁定事件。</li><li>易於封裝流程做重複使用。</li></ul><p>以上就是一個我在實務上有使用的設計方式，我認為這個設計解決了我所面臨到的一些困擾，且有新需求的時候也很好做相關的調整。若大家有這種需要做流程檢查確認，或是長時間等候一個回應、不知道何時會有回應等等的場景時，不妨使用看看這種設計方式吧！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bde713bd2b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>