<?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 😼ViPro👻 on Medium]]></title>
        <description><![CDATA[Stories by 😼ViPro👻 on Medium]]></description>
        <link>https://medium.com/@vdustr?source=rss-352b5e3b396b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*C3K58jx8_cXqE43NFqxW8w.png</url>
            <title>Stories by 😼ViPro👻 on Medium</title>
            <link>https://medium.com/@vdustr?source=rss-352b5e3b396b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 00:37:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vdustr/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[資料一直變，前端需要每次都 refetch 嗎？]]></title>
            <link>https://medium.com/%E6%BC%B8%E5%BC%B7%E5%AF%A6%E9%A9%97%E5%AE%A4-crescendo-lab-engineering-blog/p-debounce-query-invalidation-c21c87895f8a?source=rss-352b5e3b396b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c21c87895f8a</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[tanstack-query]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[ViPro]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 06:51:12 GMT</pubDate>
            <atom:updated>2026-11-25T06:51:12.729Z</atom:updated>
            <content:encoded><![CDATA[<p>同一個畫面放了多份資料、event 又一直進來，怎麼決定直接改 cache 還是 refetch，順便把重複 request 擋下來。</p><figure><img alt="多股透明藍色纖維交錯匯聚，形成一條連續流動的緞帶。" src="https://cdn-images-1.medium.com/max/1024/1*F0M_0mvP-pmi6YTjw8ZLQA.png" /></figure><p>最近大家都在聊 AI，好久沒聊聊技術了。</p><p>整理以前寫的技術文章時，順便翻出一些過去開發遇到的問題。如果你的專案剛好也有類似情境，可以直接把這篇餵給你的 AI，看看裡面有沒有用得上的做法。</p><p>這次想聊的是那種使用者會開著一整天的網頁。這類介面通常會把列表、明細、摘要數字跟各種狀態全放在同一個畫面裡，讓使用者不用一直切頁，就能處理手上的工作。</p><p>畫面開著，資料還是會一直變。使用者操作會改資料，WebSocket 也會一直推更新進來。有時候一個異動會波及好幾個區塊，同一份資料也可能同時出現在好幾個地方。畫面得跟上變化，各處的數字和狀態也要對得起來，不能這邊已經更新了，那邊還卡在舊狀態。</p><p>最直覺的做法是每次收到通知就 refetch。寫起來快，但通知一密集，很多 request 其實只是反覆 fetch 差不多的資料；反過來，如果更新得太保守，畫面又會落後。這篇想聊的，就是怎麼在資料正確、畫面即時和 server 負擔之間找平衡。</p><h3>已經拿到新狀態，就直接 update cache</h3><p>收到 event 先看 payload 裡有什麼。如果已經帶著更新後的完整狀態，直接拿來 update query cache 就好，不用先 refetch。設計 WebSocket payload 時，讓前端知道「現在是什麼」，通常比只告訴它「剛才發生了什麼」好同步得多。</p><p>舉個例子：cache 裡的數字是 10，server 連續加了兩次變成 12。如果 WebSocket 只送兩次「+1」，除了要避免漏收，還得考慮 API response 也在更新同一份 cache。</p><p>假設 GET 已經讀到 10，response 還沒回來，第一個 WS event 先把 cache 加到 11。接著舊 response 回來，又把 cache 蓋回 10；第二個「+1」再到，也只能加到 11。兩個 event 都沒漏收，畫面還是跟 server 對不起來。</p><figure><img alt="GET 的舊 response 插在兩次 WS +1 之間，讓 cache 最後停在 11，與 server 的 12 不一致。" src="https://cdn-images-1.medium.com/max/720/1*7tBEa7UdYHQcP_QbFw_rKw.png" /></figure><p>改成送 { value: 12, version: 2 }，前端收到這份比較新的完整 snapshot，就能直接把 cache 換成 12，不用重演中間發生過什麼，也<strong>不用再多發一次 invalidate 或 refetch</strong>。這裡講的「完整」，指的是資料足夠替換目標 cache entry。</p><p>但完整 snapshot 還是可能被晚到的舊 API response 蓋回去。有些情境可以先用 cancelQueries 取消目標 query 目前的 fetch，等取消完成後，再寫入 snapshot；如果 API 和 WS 還有其他寫入路徑，還是得一起比對 version，才不會讓畫面退回舊狀態。另外，<a href="https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientsetquerydata">setQueryData</a> 只負責改 cache，如果連最後一份 snapshot 都在斷線時漏掉了，恢復連線後還是得主動同步一次。</p><figure><img alt="沿用相同時序，API 與 WS 共同比對 version，略過舊 GET，cache 最後正確更新到 12。" src="https://cdn-images-1.medium.com/max/720/1*F4yB3nqbR2dZuwCE_BnCjg.png" /></figure><h3>需要 refetch 時，先決定更新有多頻繁</h3><p>有些 event 只通知「資料變了」，沒有帶足夠的狀態；有些異動會影響多份 query，前端不適合自己一個一個重組。這種時候直接 invalidate 相關的 queries，走原本的 fetch 流程反而單純。</p><p>我們會在 API 封裝裡宣告每個 mutation 會影響哪些 queries，成功後自動 invalidate，caller 不用每次自己記住要更新哪些資料。這套做法之前在〈<a href="https://medium.com/p/f3fa9faf59e3">從繁到簡：使用 Zodios 重塑您的 API 串接體驗</a>〉寫過（Zodios 上游已經很久沒維護了，目前我們自己維護 fork，新專案則多數改用 <a href="https://orpc.dev/">oRPC</a>）。</p><p>我們原本每次收到更新需求，就立即觸發 invalidation。同一份 query 已經有 cache 時，如果底層 request 沒有配合 AbortSignal 中止，連續觸發的 fetch 就會彼此重疊（例如八次呼叫打出八個 request）；就算有接 AbortSignal，密集通知還是可能讓 request 反覆取消重打，讓 server 多做白工，畫面也遲遲等不到一次完整回應。這些連續需求，其實大部分可以合併。</p><p>遇到密集的 WebSocket event，我們通常會先加上 throttle。這類 event 只是後端通知「有更新」，沒有 caller 在等這次 invalidation 跑完才做下一件事。跟使用者剛做完 mutation、等著看結果的情境比起來，WebSocket 的間隔可以拉長一點，接受畫面晚一點點才跟上。通知密集時先用 throttle 降頻，就能減少這個來源觸發的 refetch。</p><h3>頻率降下來之後，再接住執行中的新需求</h3><p>但 throttle 只看時間，不管上一個 request 跑完了沒。為了把重疊的狀況畫清楚，下面刻意把 fetch 耗時放大到 8s：就算 throttle 每 3s 才放行一次，新的 request 還是會在前一輪結束前發出去。下面以同一份 query 示意，時間與數量並非實測。</p><p>所以我們把同一份更新範圍的 refetch 呼叫都導進同一個共用入口，交給 p-debounce 的 promise 模式（加上 after: true）來排。第一輪 fetch 先跑，跑的期間收到的新呼叫先記下來，<strong>等這輪結束，再合併補跑一次 refetch</strong>。mutation 本身照常執行，合併的只有後面的讀取。</p><figure><img alt="同一 query 的八次更新需求：A 先 fetch，執行中收到的 B–H 合併成完成後的一次 refetch，共兩輪。圖中不含上游 throttle。" src="https://cdn-images-1.medium.com/max/720/1*YI-_96O2uAQwyLQMkVC_8w.png" /></figure><p>放回 WebSocket 的流程裡，throttle 管通知進來的頻率，p-debounce 看目前這輪做完了沒，決定要直接跑還是留到下一輪。fetch 很快的時候，加不加 p-debounce，request 數量可能差不多；一旦 fetch 慢到超過 throttle 間隔，排隊的需求就會合併，同一個入口的更新也會依序執行。</p><figure><img alt="相同通知與 throttle 間隔，fetch 快時兩者都是四次；fetch 慢時，只用 throttle 有四次且重疊，搭配共用 p-debounce 則三次且依序執行。" src="https://cdn-images-1.medium.com/max/720/1*GAFLoVlzRfHHMLj4VPKuMQ.png" /></figure><h3>需要等待的 caller，等到的是哪一輪？</h3><p>對 mutation 的 caller 來說，invalidation 什麼時候結束會影響後面的動作。假設 A 先開始 fetch，它還沒回來時，B 和 C 陸續改完資料也要求更新。就算 A 在 B、C 呼叫之後才結束，response 裡還是不一定有 B、C 的異動。<strong>完成得比較晚，不代表 fetch 開始得夠晚。</strong></p><p>B 要等的是 B 之後才開始的 fetch，C 也一樣。A 跑完後才觸發的那次共用 refetch，開始時間同時晚於 B 和 C，剛好能讓兩者都等到對應的那一輪：A 的 Promise 等第一輪，B、C 等下一輪。（前提一樣是前面的修改已經可以從 server 讀到，而且這輪 fetch 成功。）</p><p>p-debounce 是處理 async function 的小工具。一般的 pDebounce(fn, wait) 看時間間隔；這裡用的 pDebounce.promise(fn, options) 改看目前這輪 Promise 跑完了沒。預設 after: false 時，執行中進來的呼叫會共用當下這輪的結果；改成 after: true，才會留到下一輪，讓這批 caller 等那一輪跑完再 resolve。</p><pre>const invalidate =<br>  pDebounce.promise(<br>    refreshData,<br>    { after: true },<br>  );</pre><figure><img alt="after: false 時 A、B、C 都等第一輪；after: true 時，A 等第一輪，B、C 等完成後補跑的下一輪。示意 fetch 成功時的等待。" src="https://cdn-images-1.medium.com/max/720/1*GTdJljl-gGeqLYeGG35JQw.png" /></figure><h3>讓不同來源，共用同一份排程</h3><p>這份排程是記在 p-debounce 實例裡的。如果每個 component 各建一個，就算 query key 一樣，還是會各跑各的。同一份更新範圍得共用同一個入口，看是要從 Context 拿，或是用 WeakMap 掛在 QueryClient 上保存都可以。</p><figure><img alt="候選整合流程：完整較新的 snapshot 直接替換 cache；更新通知先經 throttle，mutation 則直接進入共用 p-debounce，再 refetch。" src="https://cdn-images-1.medium.com/max/720/1*4CPv7QLWr8nKOEPK7x75Dw.png" /></figure><p>這裡的「一次一個」，指同一個實例安排的更新輪次，而且 refreshData 回傳的 Promise 得包到真正 fetch 結束；如果外層設了 timeout 提早放行，底層 request 還在跑，一樣會重疊。共用排程也有取捨：背景通知和 mutation 的 invalidation 走同一個入口時，如果剛好撞上一輪比較慢的 fetch，正在等更新的 caller 也會跟著多等一下（mutation 的寫入不會被這個排程擋住）。另外，p-debounce 只會記住下一輪的最後一次參數，不會幫你蒐集不同 query 的需求，更新範圍還是得先切清楚（細節可看 <a href="https://github.com/sindresorhus/p-debounce/tree/v6.0.0#pdebouncepromisefunction_-options">p-debounce 官方說明</a>）。</p><p>query 條件複雜，畫面上的資訊又彼此關聯，想讓資料盡量即時，又要顧到 server 負載，真的不是一件容易的事。</p><p>以上是我們針對這類情境整理出來的一些做法和取捨，希望能給遇到類似問題的人一點參考，也很想知道大家平常都是怎麼處理的。</p><p>歡迎還願意聊聊技術的夥伴，分享你的想法和點子～</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c21c87895f8a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E6%BC%B8%E5%BC%B7%E5%AF%A6%E9%A9%97%E5%AE%A4-crescendo-lab-engineering-blog/p-debounce-query-invalidation-c21c87895f8a">資料一直變，前端需要每次都 refetch 嗎？</a> was originally published in <a href="https://medium.com/%E6%BC%B8%E5%BC%B7%E5%AF%A6%E9%A9%97%E5%AE%A4-crescendo-lab-engineering-blog">漸強實驗室 Crescendo lab — 職涯部落格 Career blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seamlessly Switching Between Node.js Projects]]></title>
            <link>https://medium.com/%E6%BC%B8%E5%BC%B7%E5%AF%A6%E9%A9%97%E5%AE%A4-crescendo-lab-engineering-blog/seamlessly-switching-between-node-js-projects-34bea8f851b7?source=rss-352b5e3b396b------2</link>
            <guid isPermaLink="false">https://medium.com/p/34bea8f851b7</guid>
            <category><![CDATA[package-manager]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[corepack]]></category>
            <category><![CDATA[nvm]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[ViPro]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 06:36:40 GMT</pubDate>
            <atom:updated>2025-11-07T04:01:18.671Z</atom:updated>
            <content:encoded><![CDATA[<h3>Seamlessly Switching Between Node.js Projects — Mastering Node Versions and Package Manager Management</h3><p>At <a href="https://cresclab.com/">Crescendo Lab</a>, Node.js plays a central role in our front-end technology stack and is widely used across our projects. We manage a diverse set of repositories — not just our customer-facing SaaS platforms, but also a variety of internal tools. In addition, we maintain in-house libraries, SDKs, POCs, and demos, and we occasionally contribute to side projects or fork open-source repositories to submit pull requests.</p><p>If you’ve ever found yourself dealing with any of the following, you’re not alone:</p><ul><li>👉 The number of repos you maintain keeps growing, and sometimes you need to revisit a project you haven’t touched in ages</li><li>👉 You clone a repo only to have the install fail right away</li><li>👉 Each project uses a different package manager</li><li>👉 Inconsistent versions of Node.js, npm, pnpm, or yarn across projects</li><li>👉 You’re so used to a specific package manager that you run the wrong command in an unfamiliar project — like using pnpm install in a yarn-based repo</li></ul><p>As both the company and individual developers grow, these situations tend to become more common. But imagine a world where you no longer have to worry about which versions or package manager each project uses — or look up the correct command every time. Wouldn’t that make your workflow so much smoother?</p><p>To address this issue, here is a guideline on automating the process of switching to the correct version of Node.js or the suitable package manager, outlining the responsibilities of a repository maintainer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g4cos4CoIoWoheud" /><figcaption>Generated using ChatGPT</figcaption></figure><blockquote>Node.js × nvm × Package Managers × corepack × antfu/ni</blockquote><blockquote>⚠️ To ensure seamless automatic switching, it is advisable to uninstall global installations of Node.js, npm, yarn, or pnpm, to avoid any potential side effects.</blockquote><h3>nvm</h3><p><a href="https://github.com/nvm-sh/nvm">https://github.com/nvm-sh/nvm</a></p><p>nvm allows you to quickly install and use different versions of node via the command line.</p><h4>Installing nvm</h4><pre>curl -o- &lt;https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh&gt; | bash<br># Alternatively,<br>wget -qO- &lt;https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh&gt; | bash</pre><blockquote>⚠️ Homebrew installation is not recommended. <br><a href="https://github.com/nvm-sh/nvm#:~:text=Homebrew%20installation%20is%20not%20supported">https://github.com/nvm-sh/nvm#:~:text=Homebrew%20installation%20is%20not%20supported</a>.</blockquote><h4>Integrating with Shell</h4><p><a href="https://github.com/nvm-sh/nvm#deeper-shell-integration">https://github.com/nvm-sh/nvm#deeper-shell-integration</a></p><p>This will automatically switch you to the appropriate Node.js version for the repository using the cd command, based on the closest .nvmrc file.</p><ul><li><a href="https://github.com/nvm-sh/nvm#bash">bash</a></li><li><a href="https://github.com/nvm-sh/nvm#zsh">zsh</a></li><li><a href="https://github.com/nvm-sh/nvm#fish">fish</a></li></ul><h3>Corepack</h3><p><a href="https://github.com/nodejs/corepack">https://github.com/nodejs/corepack</a></p><p>Corepack is a zero-runtime-dependency Node.js script that acts as a bridge between Node.js projects and the package managers they are intended to be used with during development. In practical terms, Corepack lets you use Yarn, npm, and pnpm without having to install them.</p><h4>Installing</h4><p>No additional installation is required. Corepack is <a href="https://nodejs.org/api/corepack.html">distributed by default with all recent Node.js versions</a>.</p><h4>Integrating with Shell</h4><p>Since we utilize nvm to switch between different versions of Node.js, please ensure that you place the script right after the nvm scripts:</p><pre># Enable corepack immediately after nvm setup.<br>if ! command -v corepack &amp;&gt; /dev/null<br>then<br>  npm install -g corepack<br>fi<br><br>corepack enable</pre><h3>@antfu/ni</h3><p><a href="https://github.com/antfu/ni">https://github.com/antfu/ni</a></p><p><strong>ni</strong> — use the right package manager</p><h4>Installing</h4><pre>npm i -g @antfu/ni</pre><h4>Usage</h4><p>Use the ni commands instead of npm / pnpm / yarn.</p><blockquote>💡 This tool is for personal use. We don’t use it in scripts within package.json or in CI. Not everyone uses this for convenience.</blockquote><p>Recommended to set npm as the global agent because if we ni -g serve in a yarn repository and ni -g serve in a pnpm repository, we’ll install two instances. And we always receive a warning if we use the wrong package manager. For instance, you cannot execute yarn add -g serve in a pnpm repository. However, npm is an exception for corepack.</p><pre>globalAgent=npm</pre><h3>Husky</h3><p><a href="https://typicode.github.io/husky/troubleshoot.html#command-not-found">https://typicode.github.io/husky/troubleshoot.html#command-not-found</a></p><p>Since we automatically switch the Node.js version and the package manager using the shell, the auto use and aliases are not loaded automatically. Therefore, we need to individually load them with ~/.config/husky/init.sh:</p><pre># This loads nvm.sh, sets the correct PATH before running hook, and ensures the project version of Node<br>export NVM_DIR=&quot;$HOME/.nvm&quot;<br><br># Add this if you encounter an error stating that  <br># &quot;nvm is not compatible with the &#39;npm_config_prefix&#39; environment variable.&quot;<br>unset npm_config_prefix<br><br>[ -s &quot;$NVM_DIR/nvm.sh&quot; ] &amp;&amp; \\. &quot;$NVM_DIR/nvm.sh&quot;<br><br># If you have an .nvmrc file, we use the relevant node version<br>if [[ -f &quot;.nvmrc&quot; ]]; then<br>  nvm use<br>fi<br><br># Enable corepack immediately after nvm.<br>if ! command -v corepack &amp;&gt; /dev/null<br>then<br>  npm install -g corepack<br>fi<br><br>corepack enable</pre><h3>Some Good Practices</h3><h4>Essential Setup</h4><p>As a repository maintainer, it is considered good practice to <a href="https://github.com/nvm-sh/nvm#nvmrc">set the Node.js version in the </a><a href="https://github.com/nvm-sh/nvm#nvmrc">.nvmrc file</a> and configure the <a href="https://docs.npmjs.com/cli/v8/configuring-npm/package-json#engines">engines</a> and <a href="https://nodejs.org/api/corepack.html#configuring-a-package">packageManager</a> fields in the package.json file.</p><p>For example:</p><pre># .nvmrc<br>22</pre><pre>// package.json<br>{<br>  &quot;packageManager&quot;: &quot;pnpm@8.6.4&quot;,<br>  &quot;engines&quot;: {<br>    &quot;node&quot;: &quot;&gt;=20&quot;,<br>    &quot;pnpm&quot;: &quot;&gt;=8&quot;<br>  }<br>}</pre><p>The checklist for your repository:</p><ul><li>✅ Node.js version in .nvmrc.</li><li>✅ Node.js version in the engines field in package.json.</li><li>✅ Package Manager in the engines field in package.json.</li><li>✅ Package Manager in the packageManager field in package.json.</li></ul><blockquote>💡 Because npm is included with Node.js, you probably don’t need to specify &quot;packageManager&quot; in package.json if you’re using npm for your project.</blockquote><h3>Integrating with GitHub Actions</h3><p><a href="https://github.com/actions/setup-node">https://github.com/actions/setup-node</a></p><pre>- name: Setup Node.js for use with actions<br>  uses: actions/setup-node@v4<br>  with:<br>    node-version-file: &#39;.nvmrc&#39;<br>- run: |<br>    if ! command -v corepack &amp;&gt; /dev/null; then<br>      npm install -g corepack<br>    fi<br><br>    corepack enable</pre><blockquote>💡 If you are using pnpm/action-setup@v2 or later, there is no need to explicitly set the version. It will automatically detect the packageManager field in package.json.</blockquote><h3>FAQ</h3><p>If you got problems with nvm, please refer to the official documentation first:</p><ul><li><a href="https://github.com/nvm-sh/nvm#problems">Problems</a></li><li><a href="https://github.com/nvm-sh/nvm#macos-troubleshooting">macOS Troubleshooting</a></li><li><a href="https://github.com/nvm-sh/nvm#wsl-troubleshooting">WSL Troubleshooting</a></li></ul><h4>The 3rd-party repository didn’t set up the .nvmrc</h4><p>Even if the 3rd-party repository didn’t configure the <strong>.nvmrc</strong> file, we can still use <strong>nvm use {version}</strong> to switch to the desired Node.js version.</p><h4>The 3rd-party repository didn’t config packageManager in package.json</h4><p><a href="https://github.com/nodejs/corepack?tab=readme-ov-file#corepack-pack--nameversion">https://github.com/nodejs/corepack?tab=readme-ov-file#corepack-pack--nameversion</a></p><p>Use pack:</p><pre>corepack pack yarn@2.4.3</pre><h4>pnpm and yarn work, but npm doesn’t</h4><p>If you encounter issues specifically with npm while pnpm and yarn are functioning properly, you can try removing the nvm versions by executing the following command:</p><pre>rm -rf ~/.nvm/versions/node/*</pre><p>npm should be available by reinstalling the Node.js version.</p><h4>npm shims wasn’t installed</h4><p><a href="https://github.com/nodejs/corepack#:~:text=Note%20that%20the%20npm%20shims%20will%20not%20be%20installed%20unless%20explicitly%20requested%2C%20as%20npm%20is%20currently%20distributed%20with%20Node.js%20through%20other%20means">https://github.com/nodejs/corepack#:~:text=Note%20that%20the%20npm%20shims%20will%20not%20be%20installed%20unless%20explicitly%20requested%2C%20as%20npm%20is%20currently%20distributed%20with%20Node.js%20through%20other%20means</a></p><blockquote><em>Note that the npm shims will not be installed unless explicitly requested, as npm is currently distributed with Node.js through other means.</em></blockquote><h4>Upgrade</h4><p>Upgrade Node.JS:</p><pre>nvm install node<br>nvm use node<br><br># Or install a specific version:<br>nvm install 20<br>nvm use 20<br><br># Save the current Node.js version to .nvmrc<br>node -v &gt; .nvmrc</pre><p>Upgrade the package manager (e.g., pnpm) with:</p><pre>corepack up<br># or<br>corepack use pnpm@latest</pre><h3>Demo</h3><p><a href="https://github.com/chatbotgang/demo-nvm-corepack-ni">GitHub - chatbotgang/demo-nvm-corepack-ni: A Node.js × nvm × Package Managers × corepack demo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34bea8f851b7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E6%BC%B8%E5%BC%B7%E5%AF%A6%E9%A9%97%E5%AE%A4-crescendo-lab-engineering-blog/seamlessly-switching-between-node-js-projects-34bea8f851b7">Seamlessly Switching Between Node.js Projects</a> was originally published in <a href="https://medium.com/%E6%BC%B8%E5%BC%B7%E5%AF%A6%E9%A9%97%E5%AE%A4-crescendo-lab-engineering-blog">漸強實驗室 Crescendo lab — 職涯部落格 Career blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced React Component Design with TypeScript]]></title>
            <link>https://medium.com/%E6%BC%B8%E5%BC%B7%E5%AF%A6%E9%A9%97%E5%AE%A4-crescendo-lab-engineering-blog/advanced-react-component-design-with-typescript-b679b85ad719?source=rss-352b5e3b396b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b679b85ad719</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[development-experience]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[ViPro]]></dc:creator>
            <pubDate>Thu, 29 Aug 2024 04:16:27 GMT</pubDate>
            <atom:updated>2024-08-29T16:27:23.546Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>As TypeScript continues to grow in popularity and strength, becoming an indispensable part of improving the library development experience, developers who are accustomed to TypeScript often feel something is missing without type definitions, much like navigating an unmarked intersection. React, on the other hand, has long held a prominent place in frontend development, with its simple design and close alignment with native JavaScript. Its flexibility and extensibility are key strengths. Today, let’s explore what sparks might fly when TypeScript and React come together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*onzLMeSPR0uoq0FZ" /><figcaption>Image generated using Microsoft Copilot</figcaption></figure><p>Our goal is to make the components reusable, flexible, extendable, and type-safe while ensuring a good developer DX with TypeScript-integrated editors. This article is ideal for those who are familiar with TypeScript and React and enjoy designing shared components or implementing design systems to enhance the development experience while maintaining flexibility.</p><h3>Grouping Components</h3><p>Generally, we group related components into a single file or folder to make it easier to use and understand how they should or can be used together:</p><pre>import { Select } from &#39;@component/Select&#39;;<br>import { Option } from &#39;@component/Select/Option&#39;;<br><br>&lt;Select&gt;<br>  &lt;Option value=&quot;1&quot;&gt;Option 1&lt;/Option&gt;<br>  &lt;Option value=&quot;2&quot;&gt;Option 2&lt;/Option&gt;<br>  &lt;Option value=&quot;3&quot;&gt;Option 3&lt;/Option&gt;<br>&lt;/Select&gt;</pre><p>We can group components in to a single instance to make it more easier to use:</p><pre>import { Select } from &#39;@component/Select&#39;;<br><br>&lt;Select&gt;<br>  &lt;Select.Option value=&quot;1&quot;&gt;Option 1&lt;/Select.Option&gt;<br>  &lt;Select.Option value=&quot;2&quot;&gt;Option 2&lt;/Select.Option&gt;<br>  &lt;Select.Option value=&quot;3&quot;&gt;Option 3&lt;/Select.Option&gt;<br>&lt;/Select&gt;</pre><p>For function components, we can assign the components to a property of the main component:</p><pre>import type { ReactNode } from &quot;react&quot;;<br><br>const Select = ({ children }: { children?: ReactNode }) =&gt; {<br>  return &lt;select&gt;{children}&lt;/select&gt;;<br>};<br><br>const Option = ({<br>  value,<br>  children,<br>}: {<br>  value?: string;<br>  children?: ReactNode;<br>}) =&gt; {<br>  return &lt;option value={value}&gt;{children}&lt;/option&gt;;<br>};<br><br>Select.Option = Option;<br><br>export { Select };</pre><p>However, in most cases, we use the React.FC type to validate the function component implementation. This approach does not allow us to assign components as properties of the main component.</p><pre>import type { FC, ReactNode } from &quot;react&quot;;<br><br>const Select: FC&lt;{ children?: ReactNode }&gt; = ({ children }) =&gt; {<br>  return &lt;select&gt;{children}&lt;/select&gt;;<br>};<br><br>const Option: FC&lt;{<br>  value?: string;<br>  children?: ReactNode;<br>}&gt; = ({ value, children }) =&gt; {<br>  return &lt;option value={value}&gt;{children}&lt;/option&gt;;<br>};<br><br>Select.Option = Option;<br>//     ^^^^^^ <br>//     Property &#39;Option&#39; does not exist on type &#39;FC&lt;{ children?: ReactNode;<br>//     }&gt;&#39;.ts(2339)<br><br>export { Select };</pre><p>To solve this, we use Object.assign to assign the components to the main component:</p><pre>import type { FC, ReactNode } from &quot;react&quot;;<br><br>const SelectInternal: FC&lt;{ children?: ReactNode }&gt; = ({ children }) =&gt; {<br>  return &lt;select&gt;{children}&lt;/select&gt;;<br>};<br><br>const Option: FC&lt;{<br>  value?: string;<br>  children?: ReactNode;<br>}&gt; = ({ value, children }) =&gt; {<br>  return &lt;option value={value}&gt;{children}&lt;/option&gt;;<br>};<br><br>const Select = Object.assign(SelectInternal, { Option });<br><br>export { Select };</pre><p>We can also assign various related elements to it, including hooks, styles, class names, default values, and more.</p><p>Note that when using React 18 or earlier, we need to manually forward the ref. Similarly, related utilities can be assigned using Object.assign.</p><pre>const ButtonInternal = forwardRef&lt;ButtonRef, ButtonProps&gt;((props, ref) =&gt; {<br>  return &lt;button {...props} ref={ref} /&gt;;<br>});<br><br>const Button = Object.assign(ButtonInternal, {<br>  // ...<br>});</pre><h3>Grouping Types</h3><p>Similarly to how we handle runtime components, we can also group related types within the component to make them easier to use:</p><pre>import { Button } from &quot;./Select&quot;;<br><br>const buttonProps: useMemo&lt;Button.Props&gt;(() =&gt; ({<br>  variant: &quot;primary&quot;,<br>}), []);<br><br>&lt;Button {...buttonProps} /&gt;;</pre><p>To implement this, we can use the namespace keyword:</p><pre>import type { FC, ReactNode } from &quot;react&quot;;<br><br>namespace Button {<br>  export interface Props {<br>    variant?: &quot;primary&quot; | &quot;secondary&quot;<br>    children?: ReactNode;<br>    onClick?: () =&gt; void;<br>  }<br>}<br><br>const ButtonInternal = forwardRef&lt;Button.Ref, Button.Props&gt;((props, ref) =&gt; {<br>  return &lt;button {...props} ref={ref} /&gt;;<br>});<br><br>const Button = Object.assign(ButtonInternal, {<br>  defaultRootElement,<br>});<br><br>export { Button };</pre><p>Please note that we only use namespace for types, not for runtime values. For reference, see <a href="https://x.com/mattpocockuk">@mattpocockuk</a> on <a href="https://x.com/">X</a> <a href="https://x.com/mattpocockuk/status/1805186401408778549">here</a> and <a href="https://x.com/mattpocockuk/status/1805606072167940167">here</a>.</p><h3>Inheritance and Extension</h3><p>Inherit the base component to create a new component:</p><pre>namespace Button {<br>  export interface Props extends ComponentProps&lt;&quot;button&quot;&gt; {}<br>}</pre><p>And now we can use all the props from the base component without redefining them.</p><p>Notice that when using React 18 or earlier, we have to forward the ref manually:</p><pre>namespace Button {<br>  export type Ref = ElementRef&lt;&quot;button&quot;&gt;;<br>  export interface Props extends ComponentProps&lt;&quot;button&quot;&gt; {}<br>}<br><br>const ButtonInternal = forwardRef&lt;Button.Ref, Button.Props&gt;((props, ref) =&gt; {<br>  return &lt;button {...props} ref={ref} /&gt;;<br>});<br><br>const Button = Object.assign(ButtonInternal, {<br>  // ...<br>});</pre><p>We can use default props and override props to extend the functionality of the component:</p><pre>&lt;select {...defaultProps} {...props} {...overrideProps} /&gt;</pre><p>To change the default props of a component, we can use defaultProps to override the existing defaults. For example, if we want to set the multiple attribute of a select element as the default, we can use the following code:</p><pre>const SelectInternal: FC&lt;Select.Props&gt; = (props) =&gt; {<br>  // ...<br>  return &lt;select multiple {...props} {...overrideProps} /&gt;;<br>}<br><br>const Select = Object.assign(SelectInternal, {<br>  // ...<br>});</pre><p>Then we can easily turn it off by setting the multiple attribute to false:</p><pre>&lt;Select multiple={false} /&gt;</pre><p>Alternatively, if we want to create a &lt;MultiSelect /&gt; component that always has the multiple attribute, we can use overrideProps like this:</p><pre>const MultiSelectInternal: FC&lt;Select.Props&gt; = (props) =&gt; {<br>  // ...<br>  return &lt;select {...props} {...overrideProps} multiple /&gt;;<br>}<br><br>const MultiSelect = Object.assign(MultiSelectInternal, {<br>  // ...<br>});</pre><p>Since the multiple prop should no longer be available for this component, remember to omit it from the Select.Props:</p><pre>namespace MultiSelect {<br>  export interface Props extends Omit&lt;ComponentProps&lt;&quot;select&quot;&gt;, &quot;multiple&quot;&gt; {}<br>}</pre><p>Note that we don’t always “override” props; sometimes we simply “extend” them. For example, if there is an internal onClick handler or className that we want to retain, we need to extend the props rather than override them:</p><pre>const onClick = useEventCallback&lt;<br>  NonNullable&lt;ComponentProps&lt;&quot;select&quot;&gt;[&quot;onClick&quot;]&gt;<br>&gt;((e) =&gt; {<br>  props.onClick?.(e);<br>  if (e.defaultPrevented) return;<br>  // Do something<br>});<br><br>const className = useMemo&lt;ComponentProps&lt;&quot;select&quot;&gt;[&quot;className&quot;]&gt;(() =&gt; {<br>  return clsx(<br>    {<br>      &quot;select-primary&quot;: variant === &quot;primary&quot;,<br>      &quot;select-secondary&quot;: variant === &quot;secondary&quot;,<br>    },<br>    props.className<br>  );<br>}, [props.className]);<br><br>return (<br>  &lt;select<br>    {...defaultProps}<br>    {...props}<br>    onClick={onClick}<br>    className={className}<br>  /&gt;<br>);</pre><p>When extending MUI components, we can style them using the sx prop like this:</p><pre>// Outside the component<br>const sxRecord = {<br>  selectRoot: {<br>    backgroundColor: &quot;red&quot;,<br>  },<br>} satisfies Record&lt;string, SxProps&gt;;<br><br>// In the component<br>const sx = useMemo&lt;ComponentProps&lt;typeof Select&gt;[&quot;sx&quot;]&gt;(<br>  // Merge the styles<br>  () =&gt; [sxRecord.selectRoot, props.sx],<br>  [props.sx],<br>);<br>return &lt;Select {...props} sx={sx} /&gt;;</pre><p>Other CSS-in-JS libraries can use similar methods to compose styles within a component. Remember to place external styles after internal styles to ensure that internal styles are overridden by external styles.</p><pre>// @emotion/css<br>const className = useMemo&lt;Props[&quot;className&quot;]&gt;(() =&gt; cx(styles.root, props.className), [props.className]);</pre><p>We don’t need to manually merge className with the Emotion CSS prop (@emotion/react) because Emotion handles it automatically.</p><h3>Inferring and Validating Component Props</h3><p>We can use TypeScript generics to validate the component props:</p><pre>namespace Select {<br>  export interface Props&lt;TValue&gt;<br>    extends Omit&lt;ComponentProps&lt;&quot;select&quot;&gt;, &quot;value&quot; | &quot;onChange&quot; | &quot;multiple&quot;&gt; {<br>    value?: TValue;<br>    onChange?: (value: TValue) =&gt; void;<br>  }<br>  export interface Type {<br>    &lt;TValue&gt;(props: Props&lt;TValue&gt;): ReactNode;<br>  }<br><br>  export interface OptionProps&lt;TValue&gt;<br>    extends Omit&lt;ComponentProps&lt;&quot;option&quot;&gt;, &quot;value&quot;&gt; {<br>    value?: TValue;<br>  }<br><br>  export interface OptionType {<br>    &lt;TValue&gt;(props: OptionProps&lt;TValue&gt;): ReactNode;<br>  }<br>}</pre><p>Define the component with the generic type, and we can declare the typed components:</p><pre>const values = [&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;] as const;<br>type Value = (typeof values)[number];<br>const TypedSelect = Select&lt;Value&gt;;<br>const TypedOption = Select.Option&lt;Value&gt;;<br><br>function Demo() {<br>  return (<br>    &lt;TypedSelect&gt;<br>      &lt;TypedOption value=&quot;foo&quot;&gt;foo&lt;/TypedOption&gt;<br>      &lt;TypedOption value=&quot;bar&quot;&gt;bar&lt;/TypedOption&gt;<br>      &lt;TypedOption value=&quot;baz&quot;&gt;baz&lt;/TypedOption&gt;<br>      &lt;TypedOption value=&quot;qux&quot;&gt;qux&lt;/TypedOption&gt;<br>      {/*          ^^^^^ Type &#39;&quot;qux&quot;&#39; is not assignable to type &#39;&quot;foo&quot; | &quot;bar&quot; | &quot;baz&quot;&#39;.ts(2322) */}<br>    &lt;/TypedSelect&gt;<br>  );<br>}</pre><p>Back in the real world, name the typed components with what they are, for example, CategorySelect and CategoryOption.</p><p>You can also infer types from the props passed to a component. For instance, if you have a Field component that accepts a path prop, you can infer the type of the path prop and use that to infer the type of the rules prop. Here’s an example:</p><pre>namespace Field {<br>  export interface Values {<br>    id: number;<br>    name: string;<br>    weight: number;<br>    height: number;<br>  }<br>  export interface Props&lt;Key extends keyof Values&gt; {<br>    path: Key;<br>    rules?: Array&lt;{<br>      test: (value: Values[Key]) =&gt; boolean;<br>      message: string;<br>    }&gt;;<br>    // ...More props here.<br>  }<br>  export interface Type {<br>    &lt;Key extends keyof Values&gt;(props: Props&lt;Key&gt;): null;<br>  }<br>}<br><br>const Field: Field.Type = () =&gt; ...<br><br>&lt;Field<br>  path=&quot;name&quot;<br>  rules={[<br>    {<br>      test: (value) =&gt; value.length &gt; 0,<br>      //     ^^^^^ Inferred as string from `path=&quot;name&quot;`<br>      message: &quot;Name is required&quot;,<br>    },<br>  ]}<br>/&gt;</pre><h3>Multiple Call Signatures</h3><p>We can define multiple call signatures to provide different patterns for using the component. For example, we can offer a children prop or an options prop for the &lt;Select /&gt; component.</p><pre>namespace Select {<br>  export interface PropsWithChildren&lt;TValue&gt;<br>    extends Omit&lt;ComponentProps&lt;&quot;select&quot;&gt;, &quot;value&quot; | &quot;onChange&quot; | &quot;multiple&quot;&gt; {<br>    value?: TValue;<br>    onChange?: (<br>      value: TValue,<br>      e: Parameters&lt;NonNullable&lt;ComponentProps&lt;&quot;select&quot;&gt;[&quot;onChange&quot;]&gt;&gt;[0],<br>    ) =&gt; void;<br>  }<br>  export interface PropsWithOptions&lt;TValue&gt;<br>    extends Omit&lt;PropsWithChildren&lt;TValue&gt;, &quot;children&quot;&gt; {<br>    options?: Array&lt;<br>      | (TValue &amp; Key)<br>      | (OptionProps&lt;TValue&gt; &amp; {<br>          key: Key;<br>        })<br>    &gt;;<br>  }<br>  export interface Type {<br>    &lt;TValue&gt;(props: PropsWithChildren&lt;TValue&gt;): ReactNode;<br>    &lt;TValue&gt;(props: PropsWithOptions&lt;TValue&gt;): ReactNode;<br>  }<br>}<br><br>&lt;Select options={[1, 2]} /&gt; // ✅ Valid<br><br>&lt;Select&gt;<br>  &lt;Select.Option value={1}&gt;One&lt;/Select.Option&gt;<br>  &lt;Select.Option value={2}&gt;Two&lt;/Select.Option&gt;<br>&lt;/Select&gt; // ✅ Valid<br><br>&lt;Select options={[1, 2]}&gt;<br>  &lt;Select.Option value={1}&gt;One&lt;/Select.Option&gt;<br>  &lt;Select.Option value={2}&gt;Two&lt;/Select.Option&gt;<br>&lt;/Select&gt; // Error: Property &#39;options&#39; does not exist on type ...</pre><h3>Overridable Root Element</h3><p>To enhance the flexibility of components, we offer a component prop, similar to MUI, or the as prop found in Chakra UI:</p><pre>&lt;Button component=&quot;a&quot; href=&quot;https://cresclab.com&quot;&gt;<br>  Crescendo Lab<br>&lt;/Button&gt;</pre><p>Before we begin implementing this, we need to introduce these type utilities borrowed from <a href="https://github.com/mui/material-ui/blob/78d723b/packages/mui-types/index.d.ts">MUI</a>:</p><pre>/**<br> * Remove properties `K` from `T`.<br> * Distributive for union types.<br> */<br>type DistributiveOmit&lt;T, K extends keyof any&gt; = T extends any<br>  ? Omit&lt;T, K&gt;<br>  : never;<br><br>/**<br> * Like `T &amp; U`, but using the value types from `U` where their properties overlap.<br> */<br>type Overwrite&lt;T, U&gt; = DistributiveOmit&lt;T, keyof U&gt; &amp; U;</pre><p>It’s a good idea to install @mui/types for reusability.</p><p>We can define the interface using multiple generic types as the component type:</p><pre>import type { ComponentProps, ElementType, ReactNode } from &quot;react&quot;;<br><br>const defaultRootElement = &quot;button&quot; as const;<br><br>namespace Button {<br>  export interface OwnProps {<br>    // Own props here.<br>    variant?: &quot;primary&quot; | &quot;secondary&quot;;<br><br>    /**<br>     * Override the default root element.<br>     */<br>    component?: ElementType;<br>  }<br>  export type Props&lt;<br>    TRootElement extends ElementType = typeof defaultRootElement,<br>  &gt; = Overwrite&lt;ComponentProps&lt;TRootElement&gt;, OwnProps&gt;;<br>  export interface Type {<br>    &lt;TRootElement extends ElementType = typeof defaultRootElement&gt;(<br>      props: Overwrite&lt;Props&lt;TRootElement&gt;, { component: TRootElement }&gt;,<br>    ): ReactNode;<br>    (props: DistributiveOmit&lt;Props, &quot;component&quot;&gt;): ReactNode;<br>  }<br>}<br><br>const ButtonInternal: Button.Type = ({<br>  component: Component = defaultRootElement,<br>  variant,<br>  ...props<br>}: Button.OwnProps) =&gt; {<br><br>  // ...Internal logic here.<br><br>  return &lt;Component {...props} /&gt;;<br>};<br><br>const Button = Object.assign(ButtonInternal, {<br>  defaultRootElement,<br>});<br><br>export { Button };</pre><p>Now we can use the component prop to override the root element:</p><pre>&lt;Button<br>  component=&quot;a&quot;<br>  href=&quot;https://cresclab.com&quot;<br>  onClick={(e) =&gt; e}<br>  //        ^? React.MouseEvent&lt;HTMLAnchorElement, MouseEvent&gt;<br>  ref={(e) =&gt; console.log(e)}<br>  //    ^? HTMLAnchorElement<br>/&gt;</pre><p>We can also use component instead of html element:</p><pre>&lt;Button component={Link} to=&quot;/&quot; /&gt;</pre><p>In React 18 or earlier, we need to manually forward the ref, and the type will look like this:</p><pre>export interface Type {<br>  &lt;TRootElement extends ElementType = typeof defaultRootElement&gt;(<br>    props: DistributiveOmit&lt;Props&lt;TRootElement&gt;, &quot;component&quot;&gt; &amp; {<br>      component: TRootElement;<br>    },<br>    ref?: ElementRef&lt;TRootElement&gt;,<br>  ): ReactNode;<br>  (<br>    props: Omit&lt;Props, &quot;component&quot;&gt;,<br>    ref?: ElementRef&lt;typeof defaultRootElement&gt;,<br>  ): ReactNode;<br>}</pre><p>To verify the component prop, for instance, if we want to ensure its className and onClick can be extended as in the example above, we can declare a BaseRootElementType to replace ElementType in the overridable component:</p><pre>namespace Button {<br>  export interface BaseRootElementProps {<br>    className?: undefined | string;<br>    onClick?: undefined | React.MouseEventHandler&lt;HTMLElement&gt;;<br>  }<br><br>  export type BaseRootElementType = ElementType&lt;BaseRootElementProps&gt;;<br><br>  export interface OwnProps {<br>    // Own props here.<br>    variant?: &quot;primary&quot; | &quot;secondary&quot;;<br><br>    /**<br>     * Override the default root element.<br>     */<br>    component?: BaseRootElementType;<br>  }<br>  export type Props&lt;<br>    TRootElement extends BaseRootElementType = typeof defaultRootElement,<br>  &gt; = Overwrite&lt;ComponentProps&lt;TRootElement&gt;, OwnProps&gt;;<br>  export interface Type {<br>    &lt;TRootElement extends BaseRootElementType = typeof defaultRootElement&gt;(<br>      props: Overwrite&lt;Props&lt;TRootElement&gt;, { component: TRootElement }&gt;,<br>    ): ReactNode;<br>    (props: DistributiveOmit&lt;Props, &quot;component&quot;&gt;): ReactNode;<br>  }<br>}<br><br>const ButtonInternal: Button.Type = ({<br>  component: Component = defaultRootElement,<br>  variant,<br>  ...props<br>}: Overwrite&lt;Button.BaseRootElementProps, Button.OwnProps&gt;) =&gt; {<br>  const defaultProps = useMemo&lt;Partial&lt;Button.BaseRootElementProps&gt;&gt;(<br>    () =&gt; ({<br>      // Calculate default props here.<br>    }),<br>    [],<br>  );<br><br>  // ...Internal logic here.<br><br>  const className = useMemo&lt;Button.BaseRootElementProps[&quot;className&quot;]&gt;(<br>    () =&gt;<br>      clsx(<br>        {<br>          &quot;my-button--primary&quot;: variant === &quot;primary&quot;,<br>          &quot;my-button--secondary&quot;: variant === &quot;secondary&quot;,<br>        },<br>        props.className,<br>      ),<br>    [props.className, variant],<br>  );<br><br>  const onClick = useEventCallback&lt;<br>    NonNullable&lt;Button.BaseRootElementProps[&quot;onClick&quot;]&gt;<br>  &gt;((e) =&gt; {<br>    props.onClick?.(e);<br>    if (e.defaultPrevented) return;<br>    // ...Custom logic here.<br>  });<br><br>  return (<br>    &lt;Component<br>      {...defaultProps}<br>      {...props}<br>      className={className}<br>      onClick={onClick}<br>    /&gt;<br>  );<br>};</pre><p>This approach allows us to achieve the following result:</p><pre>const IncompatibleComponent: FC&lt;{ onClick?: (value: Value) =&gt; void }&gt; = () =&gt; null;<br>const CompatibleComponent: FC&lt;{ onClick?: ComponentProps&lt;&quot;a&quot;&gt;[&quot;onClick&quot;] }&gt; = () =&gt; null;<br><br>&lt;Button component={IncompatibleComponent} onClick={(e) =&gt; e} /&gt;;<br>//      ^^^^^^^^^ Types of property &#39;onClick&#39; are incompatible.<br>&lt;Button component={CompatibleComponent} onClick={(e) =&gt; e} /&gt;;</pre><h3>Conclusion</h3><p>Here are the key points covered in this article:</p><ul><li>Some lint rules such as no-redeclare might warn with these patterns, it&#39;s fine to disable them if we already inspect the errors with TypeScript.</li><li>Notice that use namespace only for types, not for runtime values.</li><li>Always inherit and extend all props from the base component.</li><li>Place defaultProps before props to allow them to be overridden.</li><li>Place overrideProps after props. If a prop is always overridden, omit its type; otherwise, handle the merging of props.</li><li>If necessary, make the rootElement overridable, especially for clickable elements, as they may need to be used with &lt;a /&gt; or other router components like &lt;Link /&gt;.</li></ul><p>When developing shared components or utilities, it’s crucial to remember that developers are the end users, so DX is essentially UX. We aim to create components that are flexible, overridable, and easy to integrate. Inferring and validating props with TypeScript are fundamental aspects of our design, as we prioritize making these components intuitive and user-friendly for developers. Furthermore, always ensure you write comprehensive tests, including runtime tests, visual tests, and type checks, to verify that the components work correctly. Do you have any effective patterns or best practices to share? We’d love to hear your insights!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b679b85ad719" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E6%BC%B8%E5%BC%B7%E5%AF%A6%E9%A9%97%E5%AE%A4-crescendo-lab-engineering-blog/advanced-react-component-design-with-typescript-b679b85ad719">Advanced React Component Design with TypeScript</a> was originally published in <a href="https://medium.com/%E6%BC%B8%E5%BC%B7%E5%AF%A6%E9%A9%97%E5%AE%A4-crescendo-lab-engineering-blog">漸強實驗室 Crescendo lab — 職涯部落格 Career blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[從繁到簡：使用 Zodios 重塑您的 API 串接體驗]]></title>
            <link>https://medium.com/%E6%BC%B8%E5%BC%B7%E5%AF%A6%E9%A9%97%E5%AE%A4-crescendo-lab-engineering-blog/%E5%BE%9E%E7%B9%81%E5%88%B0%E7%B0%A1-%E4%BD%BF%E7%94%A8-zodios-%E9%87%8D%E5%A1%91%E6%82%A8%E7%9A%84-api-%E4%B8%B2%E6%8E%A5%E9%AB%94%E9%A9%97-f3fa9faf59e3?source=rss-352b5e3b396b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3fa9faf59e3</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[ViPro]]></dc:creator>
            <pubDate>Mon, 20 Mar 2023 04:39:40 GMT</pubDate>
            <atom:updated>2023-03-21T17:21:41.967Z</atom:updated>
            <content:encoded><![CDATA[<p>當前，API 已經成為了現代軟體開發的重要組成部分，然而，由於其繁雜的串接體驗，對於開發人員來說，這並不總是一個容易的過程。為了簡化這個過程，Zodios 提供了一個解決方案，它可以幫助您從繁雜的 API 串接中解放出來，讓您能夠更輕鬆地開發應用程式。在本文中，我們將探討如何使用 Zodios 來重塑您的 API 串接體驗，並為您提供更簡單、更高效的開發解決方案。</p><p><em>The English version simultaneously published on DEV Community: </em><a href="https://dev.to/vdustr/from-tedious-to-simple-reshaping-your-api-integration-experience-with-zodios-1oh9"><em>From Tedious to Simple: Reshaping Your API Integration Experience with Zodios</em></a></p><h3>技術背景</h3><p>「<a href="https://www.cresclab.com/">漸強實驗室 Crescendo Lab</a>」在多個大型產品中的技術基礎主要採用 Typescript 和 React。Typescript 能夠幫助我們編寫更穩定且易於維護的程式碼，而 React 則是一個熱門的 JavaScript 前端框架，能夠協助我們快速打造互動性強的網頁應用程式。</p><p>我們的網頁應用程式是以 Single Page Application 的形式呈現，讓使用者能夠享受流暢的使用體驗。同時，我們採用 RESTful API 進行資料交換，以便更好地管理和控制資料傳輸。值得一提的是，由於公司產品功能不斷更新，我們常常需要反覆確認 API 和新增功能。因此，這些與 API 有關的串接工作對我們來說非常繁重。</p><p>接下來，我們將列出我們在這樣的環境開發中遇到的幾個痛點或常見問題，並提出我們的觀點，分析問題，尋找解決方案。</p><h3>useEffect 的誤用</h3><p>以下是一個誤用 useEffect 的經典案例：</p><pre>useEffect(() =&gt; {<br>  async function fetchData() {<br>    const response = await fetch(`https://example.com/api/orgs/${orgId}`);<br>    const json = await response.json();<br>    setData(json);<br>  }<br>  fetchData();<br>}, [orgId]);</pre><p>這樣的寫法在 unmount 時會收到錯誤警告，而在切換 orgId 時也可能會出現 race condition。有些人或許會想要 disable 這個 eslint rule react-hooks/exhaustive-deps，以自己控制 useEffect 何時被觸發，但這些操作都是極為危險且會破壞開發體驗。</p><p>正確的做法是使用 abort controller signal 或是 cancel flag，這方面網路上資料很多，這裡就不再贅述。</p><p>此外，這個範例中也出現了不當的 URL 組合方式，接下來會進一步提到。</p><h3>不良的 URL 組合方式</h3><p>URL 中可能出現的參數包括 path parameters 和 search parameters。最常見的錯誤是錯誤地串接這些參數，例如以下的範例：</p><pre>const url = `users/${userId}/tags?q=${name}`;</pre><p>以上的參數串接方式可能會因存在特定字元而導致錯誤，因此使用 urlencode 是必要的：</p><pre>const url = `users/${strictUriEncode(userId)}/tags?q=${strictUriEncode(name)}`;</pre><p>然而，這種串接方式確實非常醜陋。特別是在搜尋參數的部分，也缺乏彈性。因此，我們更傾向於使用 path-to-regexp 搭配 query-string 或 qs：</p><pre>const url = pathToRegexp.compile(&#39;users/:userId/tags&#39;)({ userId }) + &#39;?&#39; + queryString.stringify({ q: name });</pre><p>如此一來，我們已經成功從 URL 中拆解出參數。然而，我們還有一個難題需要解決，因為我們的 API 使用的是 snack_case 命名規則，而前端的 coding style 則是使用 camelCase。</p><h3>snake_case vs camelCase</h3><p>由於命名規則的不同，前端在發出請求之前必須將 search parameter keys 和 request body 內的 property keys 都轉換為 snake_case，並在取得 response 後將 data 內的 property keys 都轉換為 camelCase。這個過程相當繁瑣且重複。理想的設計應該是在更底層就進行轉換，並且在使用時完全不去在意它在傳輸過程的樣貌。</p><h3>Date 型態的轉換問題</h3><p>由於在 API 中無法傳遞 Date 物件，通常我們會使用序列化資料，常見的格式有 ISO-8601 / RFC3339（傳數字的都是邪門歪道），我們在每個元件中取得的都是字串，每次使用時都必須再進行一次轉換。假如能自始至終取得 Date 型別的物件，使用資料時的體驗就會好很多，除了很明確地知道該值是 Date 之外（否則都是字串），也可以直接使用 Date 的方法。如果使用 Day.js 的話，直接使用 Day.js 物件也是不錯的選擇。</p><h3>人類語言的誤解</h3><p>這是我們公司發生的一件真實故事。為了一個特定的資源，我們設計了新的規範。當初，後端工程師與前端的約定是：舊版本不會有某一個屬性，只有新版本才有。由於沒有這件事的紀錄，我（作為前端工程師）使用了很激進的判斷方式，即 hasOwnProperty。然而，後端工程師只是將該屬性值回傳為 null。這導致了判斷錯誤，因為我將舊版本的資料傳遞到了新版本的處理方式，最終導致程式錯誤並中斷。</p><p>另一個有趣的例子也經常發生在工程師與設計師的溝通上，也就是何謂「必填」(required)，以 API 的角度 required 是表示該 field 必須存在，但以使用者的角度卻成了「不可為空」(non-empty)。</p><p>這樣的資訊落差在人類溝通介面時用簡單的描述很容易發生，但若能夠透過像 schema 或是文件等來協助釐清，甚至能夠提供 playground 測試，真正地透過統一語言達成共識。</p><p>在型態定義不一致的情況下，錯誤往往發生在程式運作時，使問題難以追溯。因此更好的做法是在接收到 API 回應後，先對資料進行初步驗證。從團隊角度來看，這可以讓團隊第一時間確定問題應由前端工程師還是後端工程師來處理。有些人可能會認為，在大部分情況下，不進行驗證也能讓程式正常運作。然而，這樣心存僥倖的做法最終會使程式變得不可靠。不過，像 GraphQL 或 tRPC 這種能透過 schema 同時產生前後端接口的方式，就不需要額外進行資料驗證了。</p><h3>散亂各處的 API</h3><p>將 API 的實作混雜在 app 中會讓維護變得困難。例如，若我們對 API 進行了調整，我們將很難在一個龐大的專案中找到受影響的程式碼。因此，更理想的做法是將 API 的定義放在一個單獨的 package 中，這樣一旦 API 的規格有任何變化，我們只需要進入該 API package 進行相對應的調整即可。</p><h3>Cache Key 之亂</h3><p>對於初學者來說，在使用 TanStack Query 或是 SWR 時最常遇到的挑戰是 cache 及 cache key 的管理。為了讓更新能夠在介面上呈現，通常我們會在請求後使指定的 query invalidate 以重新向後端同步資料。若在 component 內處理此事會變得非常繁瑣，且在開發或維護的過程中很容易有遺漏。繁複的 cache 管理，就像記憶體管理一樣複雜。我們在編寫 JavaScript 程式時，雖然會關注記憶體的使用情況，但並不會真的發出指令去控制它，對吧？若能建立一套邏輯或策略，使 cache 及 cache key 的管理自動化，甚至能讓資料自動更新，這將大大減輕開發的負擔。最簡單也是最極端的方法是每次 mutate 後都 invalidate 所有 query，而像 tRPC 就提供了這樣的策略：<a href="https://trpc.io/docs/useContext#invalidate-full-cache-on-every-mutation%E3%80%82">https://trpc.io/docs/useContext#invalidate-full-cache-on-every-mutation</a> 。</p><h3>與 Zodios 相遇</h3><p>為了解決上述問題，在尋找工具的過程中，我們建立了一些標準以評估工具：</p><ul><li>為了避免使用 useEffect 帶來的心智負擔，需要能夠整合 TanStack Query 或其他類似工具。</li><li>必須能夠定義 Date 並將 response 中的 ISO8601 轉換為 Date 型別。</li><li>定義必須簡單明瞭。</li><li>如果能夠提供 type guard 的話，就更好了。</li></ul><p>最近我發現 Zod 在 v3.20 發佈了 z.coerce 功能，尤其是其中的 z.coerce.date() 可以同時驗證並轉換 API 回傳的日期格式，因此我開始在 Zod 的生態系統中尋找解決方案，結果找到了 Zodios。</p><p>Zodios 是一個方便的工具，可以透過簡單描述 API 規格，實現程式即文件。它使用了 zod 來實現 end-2-end typesafe。此外，由於它整合了 axios 和 Tanstack Query，因此無論是擴充能力、開發體驗甚至是使用體驗，都能獲得良好的效果。以下是一個簡單的範例，介紹如何透過 Zodios 從定義 API 規格到在 component 中應用：</p><pre>import { makeApi, Zodios } from &#39;@zodios/core&#39;;<br>import { ZodiosHooks } from &#39;@zodios/react&#39;;<br>import { z } from &#39;zod&#39;;<br><br>const api = makeApi([<br>  {<br>    alias: &#39;getUsers&#39;,<br>    method: &#39;get&#39;,<br>    path: &#39;orgs/:orgId/users&#39;,<br>    response: z.array(<br>      z.object({<br>        id: z.string().uuid(),<br>        name: z.string(),<br>        email: z.string().email(),<br>        createdAt: z.coerce.date(),<br>      }),<br>    ),<br>  },<br>]);<br><br>const apiClient = new Zodios(&#39;/api&#39;, api);<br>const apiHooks = new ZodiosHooks(&#39;myAPI&#39;, apiClient);<br>const query = apiHooks.useGetUsers({<br>  params: {<br>    orgId,<br>  },<br>});</pre><p>在此之前，我們已經調整了 pnpm workspace 的架構。我們在這個 repository 中建立了一個新的 package，專門用於定義 API。我們在這個專案中建立了一個名為 models.ts 的檔案，用於定義所有 models 的 schema，可以將其視為 Open API 的 Models 的概念。同時，我們會盡量讓模型可以重複使用，對於一些特殊情況，我們會在 endpoint 中 inline 單獨處理。例如，某些特定的 API 會在 response 中缺少一個 status 欄位，此時我們會直接省略它，例如：</p><pre>// frontend-repo/packages/api-sdk/user.ts<br><br>{<br>  alias: &#39;update&#39;,<br>  method: &#39;put&#39;,<br>  path: &#39;api/v1/orgs/:orgId/users/:userId&#39;,<br>  parameters: [<br>    {<br>      name: &#39;body&#39;,<br>      type: &#39;Body&#39;,<br>      schema: CreateUpdateRequestBodySchema,<br>    },<br>  ],<br>  response: UserSchema.omit({<br>    status: true,<br>  }),<br>},</pre><p>我們將 API 功能切割成多個不同的 module，每個 module 都是一個獨立的檔案，並且都各自使用一個 makeAPI()。此外，我們也對 @zodios/react 做了一些調整，讓每個模組都能夠自動 invalidate 同一個 module 的 query，並且可以在 module 之間建立關聯，使它們可以互相影響，從而省去所有 cache 和 cache key 管理的麻煩，並且不會在每次 mutate 時使畫面上的所有 query invalidate。</p><pre>/frontend-repo<br>└── packages<br>    ├── api-sdk<br>    │   ├── api<br>    │   │   ├── message.ts<br>    │   │   ├── organization.ts<br>    │   │   ├── team.ts<br>    │   │   └── user.ts<br>    │   └── models.ts<br>    └── app<br>        ├── src<br>        ├── vite.config.ts<br>        ├── package.json<br>        └── tsconfig.json</pre><p>值得注意的是，上述範例中的 CreateUpdateRequestBodySchema 將被保留在該 module 的檔案中，而不是放在全局共用的 models.ts。這樣做可以避免由於過多僅在特定區域重複使用的內容而使 models.ts 過於臃腫。</p><p>由於 Zodios 整合了 axios，因此我們利用這個特點，在 axios 上將 request body 和 query string 的 camelCase 轉成 snake_case，同時將 response 的 snake_case 轉為 camelCase，並且在 axios 上處理 token 的管理以及 baseURL 等瑣事。此外，useMutation().reset() 本身並不會中斷請求，儘管已經重置狀態，但當 response 回來時仍會觸發 onSuccess、onError、onSettled 等 callback。因此，我們還建立了一個簡單的共用函數，可以將其插入 useMutation 回傳的物件中，以同時 reset mutation 並真正取消請求。</p><p>我們將最終結果傳送到名為 cantata 的物件中（也是這個 product 的 server 開發代號），從現在開始，我們只需要將 API 規格書寫在這個 package 中，就能夠直接通過這個物件使用所有 API 請求。一旦規格有變化，我們也可以立即透過 typescript 的 type checking 了解受影響範圍並進行相應的調整。</p><pre>const userListQuery = cantata.user.useList({ orgId });<br>const currentUserQuery = cantata.user.userGetById({ orgId, userId });<br><br>const updateCurrentUserMutation = cantata.user.useUpdate({ orgId, userId });<br>// Note that both `userListQuery` and `currentUserQuery` will be automatically invalidated after each mutation.</pre><h3>API 規範</h3><p>list 或 getById 等 query 使用 GET Method; create / update / delete / enable / disable 等 mutation 使用 POST, PUT, PATCH, DELETE。部分的 query 比如說 search 可能會使用 POST 而不是 GET, 此時只要將 API definition 加上 immutable: ture 即可, 該 API 就會從 mutation 變成 query。</p><p>為了讓 API 的使用更加簡潔明瞭，我們建議在呼叫 API 時使用 aliases 代替 useQuery 和 useMutation。這樣可以避免因瑣碎的 path 和 method 影響到應用程式。然而，我們不希望這些 aliases 覆蓋原有的 zodios hooks。因此，我們會盡量避免使用 get 和 delete 等名稱作為 aliases，而是使用 getById 和 deleteById 等替代方案。</p><pre>// ✅ Preferred approach<br>api.useList();<br><br>// ❌ Avoid using this approach<br>api.useQuery(&#39;/list&#39;);</pre><h3>更多好處與未來的規劃</h3><p>使用 Zodios 創建 API SDK 非常容易維護，即使是不熟悉 TypeScript 的後端工程師也能輕鬆上手。並且有了型別檢查，我們甚至可以包裝 makeApi，讓檢查更加嚴格。把這些檔案集中放在一個 package 內，也能讓維護 API 規範更加方便，不受無關內容的干擾。Zodios 還可以直接輸出 OpenAPI 文件，並透過 Swagger UI 等工具瀏覽。此外，既然 API contract 在 repository 中，這意味著它可以像其他程式碼一樣被 commit、發布 Pull Request 進行 code review，甚至還能產生 changelog。</p><p>目前 Zodios 官方提供了 React 和 Solid 的整合，同時也有 Express 的整合。我們的下一步計畫是透過 @zodios/express 建立一個 stub server，並在其中維護 test cases，再提供一個介面讓每個 API 可以在 test cases 之間切換，或是直接 bypass 到後端維護的 server，以方便前端或測試工程師在開發或檢視相對應的畫面時切換不同的狀態，並降低前端對後端開發效率和共用環境的依賴。</p><h3>結語</h3><p>對於前端程式碼中 API 的維護工作，我們堅信將 API SDK 的開發和應用程式開發分離是改善方向。透過將重複且瑣碎的事情交給底層做統一的處理，直接在應用程式中使用 API 的痛苦將會減輕許多。使用 API SDK 可以大大降低工作成本，提高工作效率。此外，由於維護 API SDK 只需要關注 API contracts 本身，因此也十分輕鬆。將 API 的維護工作從應用程式中抽離出來，對開發人員來說，這是「<strong>將一件原本困難的事情變成兩件簡單的事情</strong>」<em>。</em>透過 Zodios 的應用驗證，我們已經得到了一個良好的結果。因此，我們在這裡分享了我們過去所見到的問題和想法，希望能為大家提供幫助。</p><h3>Reference</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal">AbortSignal</a></li><li><a href="https://github.com/axios/axios">axios</a></li><li><a href="https://graphql.org/">graphql</a></li><li><a href="https://www.openapis.org/">OpenAPI</a></li><li><a href="https://pnpm.io/">pnpm</a></li><li><a href="https://swagger.io/tools/swagger-ui/">Swagger UI</a></li><li><a href="https://swr.vercel.app/">swr</a></li><li><a href="https://tanstack.com/query">TanStack Query</a></li><li><a href="https://trpc.io/">trpc</a></li><li><a href="https://zod.dev/">Zod</a></li><li><a href="https://www.zodios.org/">Zodios</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HV9QYpkFH2KkS7sa8dKl3Q.png" /><figcaption>這篇文章透過 ChatGPT 協助完成，這張圖片也透過 Stable Diffusion 生成。</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3fa9faf59e3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E6%BC%B8%E5%BC%B7%E5%AF%A6%E9%A9%97%E5%AE%A4-crescendo-lab-engineering-blog/%E5%BE%9E%E7%B9%81%E5%88%B0%E7%B0%A1-%E4%BD%BF%E7%94%A8-zodios-%E9%87%8D%E5%A1%91%E6%82%A8%E7%9A%84-api-%E4%B8%B2%E6%8E%A5%E9%AB%94%E9%A9%97-f3fa9faf59e3">從繁到簡：使用 Zodios 重塑您的 API 串接體驗</a> was originally published in <a href="https://medium.com/%E6%BC%B8%E5%BC%B7%E5%AF%A6%E9%A9%97%E5%AE%A4-crescendo-lab-engineering-blog">漸強實驗室 Crescendo lab — 職涯部落格 Career blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>