<?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 Lastor on Medium]]></title>
        <description><![CDATA[Stories by Lastor on Medium]]></description>
        <link>https://medium.com/@lastor?source=rss-34af170eeca3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*g9jQOGSpXjFH_cNqV8pFVg.png</url>
            <title>Stories by Lastor on Medium</title>
            <link>https://medium.com/@lastor?source=rss-34af170eeca3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 20:20:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lastor/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[Node.js 解析存成 bits 的 status]]></title>
            <link>https://medium.com/codememo/node-js-%E8%A7%A3%E6%9E%90%E5%AD%98%E6%88%90-bits-%E7%9A%84-status-dc80680d7f56?source=rss-34af170eeca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc80680d7f56</guid>
            <category><![CDATA[心得]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Lastor]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 06:01:49 GMT</pubDate>
            <atom:updated>2026-03-04T06:02:36.945Z</atom:updated>
            <content:encoded><![CDATA[<p>最近在把以前 A 產品串接過的 API，挪到 B 產品上來使用。看到一段當時寫的、跟記憶體操作有關的 code，還真的花了點時間回想一下這是在做什麼。</p><p>由於這種 case 對於我這幹 Web 前端的來說實在過於罕見，就來記錄分享一下這奇葩的案例。</p><h3>情境需求</h3><p>我這邊是用 electron 做桌面端 App，會使用 Node Native Addons (Node-API) 去串接 C 語言所寫的 API functions。</p><p>C 是會直接操作記憶體的低階語言，有一筆資料 C 工程師那邊直接存在記憶體上，用 raw binary data 回傳出來。C 那邊使用的 type 叫做 uint8_t，指的是一個不包含正負號資訊的 8 位元整數。</p><p>由於是一段記憶體 data，在 Node.js 拿到的 raw data 會是一段 Buffer。並且該 API 回傳的 Buffer 塞了很多筆不同的 data，我實際需要的只放在其中某一塊 bytes 上。</p><p>這筆資料是代表某個功能的註冊狀態，總共有 5 個位置 (slot) 可以用，可以想像成…… 例如註冊 user，最多只能註冊 5 個。我們前端 App 需要知道哪個 slot 被註冊了，哪個還沒被註冊過。</p><p>C 工程師跟我說明，他將這 5 筆註冊資訊存在 1 個 bytes 上，1 byes 有 8 個 bits，他取最前面 5 個 bits 用 0、1 表示 true、false，剩下 3 個 bits 是多的。</p><p>例如 00000101 ，最右邊第一個數是 1，表示 slot 1 被註冊了，第二個數是 0，表示沒被註冊，後面類推。</p><p>所以，在 Node.js 這邊需要做的操作，是從 Buffer 中取出特定位置的 bytes，然後去 parse 這塊 bytes 的值。</p><h3>Node.js 解析 Buffer bits</h3><p>串 API 的 code 大概這種感覺，拿到的是一個 Buffer。</p><pre>// 較新版的 @types/node 會是一個 Buffer&lt;ArrayBuffer&gt;<br>const buf: Buffer = myNative.getDeviceStatus()</pre><p>直接用 console.log 把 Buffer 印出來會是種格式。</p><pre>&lt;Buffer 01 1a 00 05 2b&gt;</pre><p>上面這段 Buffer 有 5 組數字，每一組兩個數，表示一塊 bytes，該數字是 16 進位的 hex，例如第二塊的 1a 換算成 10 進位是 26。</p><p>也就是這塊 Buffer 有 5 bytes，length 是 5，index 1 的值是 1a。可以用類似 Array 的 API 去取這些值。</p><pre>buf.length // 5<br>buf[1] // 26 (0x1a)</pre><p>(16 進位在 JS 可以用 0x 前綴的數字表示)</p><p>繼續以上面這塊 Buffer 舉例，例如 C 工程師那邊跟我說，我要的註冊資料是放在第 4 塊 bytes 上，也就是 index 3，我就可以直接取出來。</p><pre>const buf: Buffer = myNative.getDeviceStatus()<br>const info10 = buf[3] // 5 (0x05)<br><br>// 也可以用 method 來取, int8 表 8 bits, 也就是 1 bytes 的 int<br>buf.readInt8(3) // 5 (0x05)</pre><p>接下來問題來了，Node.js Buffer methods 處理的層級只有到 bytes，他無法處理到 bits。我不是本科生，沒學過計算計概論那些，缺少記憶體這些相關知識，我到這就卡住不知道怎麼辦了。</p><p>就去 Google、問 AI 學習相關知識，才知道上述那些知識，像是 Buffer 顯示的數字是 hex，一塊記憶體是 1 bytes，1 bytes 是 8 bits 等等。</p><p>思考了一下，bytes vs bits 的關係，其實就是用不同的單位去顯示相同的值，就如同公分、公尺、公里。</p><p>而 console.log 印出來的 Buffer bytes 是 16 進位，用 index 對 Buffer 取值、Node.js 會自動轉成 10 進位。而我要的是 2 進位的 bits，也就是我要做的事情是對這筆數字進行單位換算。</p><pre>// 原本 16 進位, 取值自動轉 10 進位<br>const info10 = buf[3] // 5 (0x05)<br><br>// 轉成 2 進位, 填充 8 位數的前綴 0, 方便閱讀整塊 8 btis 值<br>const info2 = info10.toString(2).padStart(8, &#39;0&#39;) // &quot;00000101&quot;</pre><p>這樣就成功的拿到各 bits 的值，然後再看狀況，轉換成 object 或 array 就變成常規的 JS 資料結構了。</p><pre>// 實際只要前 5 個 bits<br>const info2 = info10.toString(2).padStart(5, &#39;0&#39;) // &quot;00101&quot;<br><br>const result = info2<br>  // 切成 array<br>  .split(&#39;&#39;)<br>  // 反轉成左邊起始, 以符合 array 順序<br>  .reverse()<br>  // 轉 boolean<br>  .map((bits) =&gt; bits === &#39;1&#39;)<br>  // 轉 object, 對 key 命名<br>  .reduce((res, val, index) =&gt; ({ ...res, [`slot${index}`]: val}), {})<br><br>console.log(result)<br>/*<br>{<br>  slot0: true,<br>  slot1: false,<br>  slot2: true,<br>  slot3: false,<br>  slot4: false,<br>}<br>*/</pre><h3>Node.js 寫入 bits</h3><p>解決核心問題之後，也研究了一下怎麼反過來做，在 Node.js 去把這筆 bits 資料給寫回 Buffer 的特定位置。</p><p>假設，我要把 11001 這 5 bits 給寫進一段長度 5 的 Buffer 的第 4 個 bytes 上。Node.js 對於 Buffer 單位進行 set 時，接受的是 number 也就是 10 進位的數字，可以利用 parseInt 將 2 進位的數字字串轉換成 10 進位 number。</p><pre>// 挖出 5 bytes 的記憶體<br>const buf = Buffer.alloc(5)<br><br>const bits = &#39;11001&#39;<br>const num = parseInt(bits, 2) // 25 (0x19)<br>buf[3] = num<br>// 或 buf.writeInt8(num)<br><br>console.log(buf)<br>// &lt;Buffer 00 00 00 19 00&gt;</pre><p>或是，算出 11001 是 16 進位的 0x19 之後，也能直接這樣去建立 5 bytes 的 Buffer。</p><pre>const buf = Buffer.from([0x00, 0x00, 0x00, 0x19, 0x00])<br>// &lt;Buffer 00 00 00 19 00&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc80680d7f56" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codememo/node-js-%E8%A7%A3%E6%9E%90%E5%AD%98%E6%88%90-bits-%E7%9A%84-status-dc80680d7f56">Node.js 解析存成 bits 的 status</a> was originally published in <a href="https://medium.com/codememo">Code 隨筆放置場</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[用 Bun 將 Node.js 的 Native Addons (Node-API) 打包成單一執行檔 CLI 工具]]></title>
            <link>https://medium.com/codememo/%E7%94%A8-bun-%E5%B0%87-node-js-%E7%9A%84-native-addons-node-api-%E6%89%93%E5%8C%85%E6%88%90%E5%96%AE%E4%B8%80%E5%9F%B7%E8%A1%8C%E6%AA%94-cli-%E5%B7%A5%E5%85%B7-f317a1ec3ef9?source=rss-34af170eeca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f317a1ec3ef9</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[buns]]></category>
            <dc:creator><![CDATA[Lastor]]></dc:creator>
            <pubDate>Mon, 15 Dec 2025 06:12:29 GMT</pubDate>
            <atom:updated>2025-12-15T06:17:09.148Z</atom:updated>
            <content:encoded><![CDATA[<p>紀錄、分享一下最近被許願的奇妙需求：</p><blockquote><em>想要將包含 Native Addons 的 Node.js CLI script 打包成單一執行檔 (Single-File Executable)，不安裝任何環境就能直接使用。</em></blockquote><p>先上結論，Bun 可以做到。</p><p>Bun 除了能打包單一執行檔，也能兼容 Node.js 的 Node-API。這樣就能利用 Bun 去包裝一個 Node.js 已經寫好的、調用 Native Addon 的 CLI 工具，將其打包成單一執行檔來使用。</p><h3>關於 Native Addons</h3><p>先簡單介紹一下 Native Addons，大概因為 Node.js 底層是 C++ 寫的，所以有官方提供一組叫做 Node-API 的玩意，可以把 C++ 的程式串接到 Node.js 使用。</p><p><a href="https://nodejs.org/api/addons.html">C++ addons | Node.js v25.2.1 Documentation</a></p><p>C++ 透過 Node-API 相關工具，可以編譯出 Node.js 可執行的 .node binary 文件，使用 require(./xxx.node) 引入，就能呼叫 C++ 寫好的 API。這允許我們能用 Node.js 去開發桌面應用，實現一些 Web 做不到的事。</p><p>例如在 C++ 寫一個 function foo 回傳 string “bar”，透過 Node-API 在 C++ 包裝轉接，以 CommonJS module 的格式導出給 Node.js。</p><pre>// C++, main.cpp<br>#include &lt;napi.h&gt;<br><br>// 等同 ts 宣函式:<br>// function foo(): string { return &#39;bar&#39; }<br>Napi::String foo(const Napi::CallbackInfo&amp; info) {<br>  return Napi::String::New(info.Env(), &quot;bar&quot;);<br>}<br><br>// 粗略等於定義 CommonJs export:<br>// function Init(exports: Object) {<br>//   exports.foo = foo<br>//   return exports<br>// }<br>// module.exports = Init({})<br>Napi::Object Init(Napi::Env env, Napi::Object exports) {<br>  exports.Set(Napi::String::New(env, &quot;foo&quot;), Napi::Function::New(env, foo));<br><br>  return exports;<br>}<br><br>NODE_API_MODULE(mylib, Init)</pre><p>需要使用 node-gyp 或 cmake-js 將寫好的 C++ 檔案，編譯成 .node binary 文件，就能在 Node.js 用 require 引入使用。(不能用 ESM import)</p><pre>const mylib = require(&#39;./path/to/mylib.node&#39;)<br>console.log(mylib.foo()) // &quot;bar&quot;</pre><h3>需求情境</h3><p>我們開發的桌面端 App 就有使用 Native Addons 去操作硬體裝置。</p><p>為了開發時能方便的設定硬體，我就用 Node.js 寫一個簡單的 CLI 工具。後來其他部門要參與測試時，也需要設定硬體，就想借這包 CLI 工具去使用。</p><p>由於這包 CLI 工具算是額外做的，本來就只有 for dev 給我們部門自己使用。所以其他部門的人，就嘗試 git clone 專案下來使用，那就需要自己 build 進行編譯。</p><p>很自然的，遇上了環境設置問題，要打包成 Native Addons 除了要裝 Node.js 之外，也需要有 C++ 編譯環境，這可比 Node.js 環境麻煩多了。</p><p>於是，就被許願說，能不能直接做成一個 .exe 那種單一執行檔？讓他們點兩下直接使用。</p><h3>初步解法</h3><p>最簡單的自然是我們 build 好 C++ 那塊，把檔案給他們用。但有些人希望能全程自己獨立處理，而不是每次需要時還要找我們幫忙 build。</p><p>嘗試過尋找 npm 上有無打包單一執行檔的套件，但 team 裡其他人研究過後，說是遇上了 Native Addons 就不 work。</p><p>也有人提出說包成 docker 試試，但我們的 C / C++ 程式是 for windows 的，只能在 windows 上編譯，似乎 docker 要起 linux 以外的容器存在許多問題。並且用 docker 好像讓事情複雜化了，沒有變簡單，總之最後沒有被採用。</p><p>由於核心問題是出在 C++ 的編譯環境，那回歸「我們 build 好給他們」這個思路，我就想說那還是做成 npm 的 bin scripts 一起發佈進 npm package 吧。這樣要用的人只要裝 Node.js 跑個 npm install 就可以了。</p><p>就這樣運作了一陣子，直到某天，天上降下了一顆包子……</p><h3>Claude Code 收購了 Bun</h3><p><a href="https://www.ithome.com.tw/news/172593">Anthropic收購JavaScript執行環境Bun強化Claude Code底層效能</a></p><p>前陣子猛然看到了這條新聞，Claude 的母公司收購了 Bun。</p><p>新聞稿內容寫道：</p><blockquote>「Claude Code目前已以Bun編譯出的執行檔形式發布給用戶，搭配Bun提供的單一執行檔（Single-file Executable）能力，讓用戶不需要預先安裝Node.js即可運行」</blockquote><p>等等，你說 Bun 可以打包單一執行檔!? 這不就表示……</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*9Pmbx6SAw54VzOyzLNu7nA.jpeg" /></figure><p>初步嘗試之後，居然真的可以! 太神奇了，包子大人!!</p><p>當然，也踩到了一些坑點。接下來就來聊聊重點，Bun 如何打包單一執行檔。</p><h3>Bun 打包單一執行檔</h3><p>我試用的當下是 Bun v1.3.4 版，使用 Mac。</p><p>安裝這部分不贅述，官網有詳細說明。我的理解上，Bun 是個全家桶，集合了 JS / TS Runtime、Package Manager、Bundler 以及 Tester 於一身。不需要另外裝套件就可以直接透過 bun cli 使用上述功能。</p><p>Bun Runtime 可以直接跑 Typescript，與 Node-API 的 Native Addons，原本 Node.js + npm 的專案，也能直接改用 Bun 來執行。要打包單一執行檔，只需要下 Bun Bundler 的 CLI 指令就行。</p><p>可以參照 Bun 官方文件的 Quick Start，寫一個簡單的 HTTP Server。</p><pre>// server.ts<br>const server = Bun.serve({<br>  port: 3000,<br>  routes: {<br>    &quot;/&quot;: () =&gt; new Response(&#39;Bun!&#39;),<br>  },<br>})<br><br>console.log(`Listening on ${server.url}`)</pre><p>然後下 Bun CLI 指令，就能打包成單一執行檔。</p><pre>$ bun build --compile ./index.ts --outfile ./build/server</pre><p>對打包出的 ./build/server binary 檔，用左鍵點兩下，一個 localhost Server 就跑起來了。</p><p>Bun 還支援跨平台打包，想在 Mac 上打包出 Windows 的 .exe 執行檔，只要加上 --target 參數，指定成 windows 就行。</p><pre>$ bun build ... --target=bun-windows-x64-modern</pre><h3>Bun 打包 Native Addons</h3><p>實際將含有 Native Addons 的程式，打包成單一執行檔就會出現一些坑。</p><p>串接其他 C / C++ 工程師寫好的 scripts，他們會先編譯成動態連結檔，然後 .node 會去依賴他們。mac 上是 .dylib ，windows 則是 .dll。</p><pre>.node -&gt; 依賴 main dylib -&gt; 依賴 lib dylib</pre><p>這些 linker 資訊是在編譯 .node 時就決定的，所以我們在 Node.js 引入時，只會出現 .node 的引用。</p><pre>const native = require(&#39;./native/mylib.node&#39;)</pre><p>很理所當然的，bundler 就只會看到 .node，他不知道也不會處理其他的子依賴。</p><p>例如資料結構可能是這樣，用一個 native/ 資料夾把依賴都裝起來。</p><pre>mycli # 單一執行檔<br>native/<br>  lib/<br>    libA.dylib<br>    libB.dylib<br>  mylib.node # natvie addon 進入點<br>  libA.dll<br>  libB.dll</pre><p>打包時，Bun 看到 require(&#39;./native/mylib.node&#39;) 會將 .node 作為 assets 一起包進 binary 文件，導致執行 .node 時找不到其他的依賴檔。</p><p>就會出現明明 run dev 可以跑，但打包後卻會報錯的現象。</p><pre>error: dlopen(/private/tmp/.7acdbfaffbe8fffe-00000000.node, 0x0001):<br>  Library not loaded: @rpath/libA.dylib<br>  Referenced from: &lt;4D862909-8117-3B3D-9F51-8DD748C066BB&gt; /private/tmp/.7acdbfaffbe8fffe-00000000.node<br>  Reason: tried: &#39;/private/tmp/lib/libA.dylib&#39; (no such file),<br>    &#39;/private/tmp/lib/libA.dylib&#39; (no such file)<br> code: &quot;ERR_DLOPEN_FAILED&quot;</pre><p>從這錯誤訊息我們也可以觀察出，打包成單一執行檔後，Bun 在執行時就不會去原本的相對路徑找 .node 了。</p><p>Bun 是將 .node 改取了一個 hash 名稱，然後放到 OS 的 tmp 資料夾下，再去引用，因為 require 機制上需要讀的是一個檔案。</p><p>總之就是 .node 會被包進去，然後 require path 會被改，不會維持原本寫的相對路徑，導致 .{dylib,dll} 跟不過去，產生失聯問題。</p><p>我們可以先改成普通打包，去掉 --compile 參數，不包成單一執行檔，來驗證一下。</p><pre>$ bun build ./index.ts --target=node --outdir ./build</pre><p>結果可以看到，build 資料夾中也出現了 .node，並且檔名還被加上後綴。看來這跟 vite、webpack 處理 assets 的邏輯類似，他會被轉換。</p><pre>// 打包前<br>require(&#39;./native/mylib.node&#39;)<br><br>// 打包後<br>__require(&quot;./mylib-w2g9qaq6.node&quot;);</pre><p>那來試試改用動態 dir 路徑為基準。</p><pre>const nodeFile = path.resolve(import.meta.dir, &#39;./mylib.node&#39;)<br>const native = require(nodeFile)</pre><p>打包成單一執行檔，執行後還是報錯。</p><pre>error: Cannot find module &#39;/$bunfs/root/native/mylib.node&#39;<br>  from &#39;/$bunfs/root/index.js&#39;</pre><p>從錯誤訊息看起來，打包之後 dirname 指向到了 /$bunfs/root ，看起來像是 Bun 產生的虛擬位置，而不是打包後執行檔所在的 ./build 目錄。</p><p>看來也沒法用 dirname 來定位外部依賴。爬了下文件，雖然有 publicPath 這個參數，但他的工作方式與 vite、webpack 的 public 機制不同，無法利用。</p><p>所幸直接問問 AI，他說：「何不試試 process.execPath？」</p><p>哦!? 實測後，打包前，會指向 Bun 的 binary 路徑，打包後，則會拿到執行檔的所在路徑，這樣僅需處理 run dev 與 prod 的差異就行了。</p><pre>// run dev, 打包前<br>process.execPath // &quot;/opt/homebrew/Cellar/bun/1.3.4/bin/bun&quot;<br><br>// prod, 打包後, 拿到了單一執行執行檔所在位置<br>process.execPath // &quot;~/.../build/mycli&quot;</pre><p>可以進一步的利用 argv[0] 在打包前後的差異……</p><pre>// 打包前<br>Bun.argv[0] // &quot;/opt/homebrew/Cellar/bun/1.3.4/bin/bun&quot;<br><br>// 打包後<br>Bun.argv[0] // &quot;bun&quot;</pre><p>來判斷當前是跑在 dev 還是 prod，做出兼容的 require 路徑。</p><pre>// 判斷是否跑在打包後<br>const isPacked = process.execPath !== Bun.argv[0]<br>const execDir = isPacked ?<br>  // 打包後找單一執行檔所在目錄<br>  path.dirname(process.execPath) :<br>  // 打包前找 source index.ts 目錄<br>  import.meta.dir<br><br>const nodeFile = path.resolve(execDir, &#39;./native/mylib.node&#39;)<br>const native = require(nodeFile)</pre><p>如此，順利讓 .node 成為外部依賴，我們只需在打包後，將 .node 等依賴檔，一起 copy 到單一執行檔相同目錄下就能成功 work 了。</p><h3>Bun Bundler</h3><p>最後稍微聊聊 Bun 的打包機能，它目前在介面上跟其他 bundler 比，是比較陽春的。</p><p>像是他沒有 copy 功能，也不提供 configure file 設定的形式，沒法像 vite.config.ts 那樣使用。</p><p>但可以利用 Bun 的 Build API，用執行 JS 觸發的方式，來避免寫一長串 Bun CLI 參數。</p><pre>// bun cli<br>$ bun build --compile ./index.ts \<br>    --target=bun-windows-x64-modern \<br>    --outfile ./build/mycli<br><br>// build API<br>await Bun.build({<br>  entrypoints: [&#39;./index.ts&#39;],<br>  compile: {<br>    target: &#39;bun-windows-x64-modern&#39;,<br>    outfile: &#39;./build/mycli&#39;,<br>  },<br>})</pre><p>同時，他有 plugins 介面，開發者可以自己寫 plugins。像是 vite 的 copy 功能，其實也是依賴 vite-plugin-static-copy 而非原生提供。</p><p>但我找了一下，雖然是有人做 Bun 的 copy plugins，但不是很活躍，都是最後更新長達 1 ~ 2 years，週下載僅個位數、十位數。</p><p>需要斟酌一下是要用不活躍的套現、自己手寫簡單的 JS copy，或是自己做 plugins。如果要使用 Build API 的話，就可以順便在裡面自己寫簡單的 JS copy。</p><pre>// copy .dylib<br>const files = fs.globSync(&#39;./native/**/*.dylib&#39;)<br>const dest = &#39;./build/native/lib&#39;<br>for (const file of files) {<br>  const filename = path.basename(file)<br>  fs.cpSync(file, path.join(dest, filename))<br>}</pre><p>除了 copy 機能尚缺之外，Bun Bundler 目前也沒有 clean 功能，他在 build 前一率不會先清空 dest。如果需要的話，也可以自己用 JS 寫，或是用下終端機指令 rm -rf 之類來做，但要小心別把自己 D 槽給砍了 (笑)。</p><p>還有就是，Bun 在打包單一執行檔時，會額外產生一個 .bun-build 文件，我爬官方文件沒有找到相關說明。</p><pre>.18806fff1e44fffe-00000000.bun-build</pre><p>但這似乎只是打包時的臨時文件，所以我另外在 build 腳本，把它給清除。</p><pre>await Bun.build({<br>  // ...<br>})<br><br>// 注意要加上 &quot;dot&quot;: true<br>const bunTmpGlob = new Bun.Glob(&#39;./*.bun-build&#39;)<br>for await (const file of bunTmpGlob.scan({ dot: true })) {<br>  fs.rmSync(file, { force: true })<br>}</pre><p>這個 tmp 檔由於檔名是 . 開頭，在 mac 上是個隱藏檔，我還沒在 windows 上 build 過，不太確定會不會也產生相同格式的臨時檔案。</p><p>而新版 node.js 自帶的 fs.glob() 是無法 match 到隱藏檔的，目前也沒提供參數設定。不想裝套件的話，可以利用 Bun 提供的 Glob API，在參數加上 &quot;dot&quot;: true 就能 match 到隱藏檔，雖然 Bun Glob 的用法有點神奇就是。</p><p>這個 glob.scan() 會回傳 AsyncIterableIterator，要用 for await 去解他。如果不習慣，也有提供 glob.scanSync() 方法。</p><p>以上。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f317a1ec3ef9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codememo/%E7%94%A8-bun-%E5%B0%87-node-js-%E7%9A%84-native-addons-node-api-%E6%89%93%E5%8C%85%E6%88%90%E5%96%AE%E4%B8%80%E5%9F%B7%E8%A1%8C%E6%AA%94-cli-%E5%B7%A5%E5%85%B7-f317a1ec3ef9">用 Bun 將 Node.js 的 Native Addons (Node-API) 打包成單一執行檔 CLI 工具</a> was originally published in <a href="https://medium.com/codememo">Code 隨筆放置場</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mac 右鍵啟動 Electron App 並傳遞參數]]></title>
            <link>https://medium.com/codememo/mac-%E5%8F%B3%E9%8D%B5%E5%95%9F%E5%8B%95-electron-app-%E4%B8%A6%E5%82%B3%E9%81%9E%E5%8F%83%E6%95%B8-eefcb6ea481c?source=rss-34af170eeca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/eefcb6ea481c</guid>
            <category><![CDATA[applescript]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[mac]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[electron]]></category>
            <dc:creator><![CDATA[Lastor]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 13:55:04 GMT</pubDate>
            <atom:updated>2024-11-17T13:55:04.290Z</atom:updated>
            <content:encoded><![CDATA[<p>需求案例快速筆記：<br>要在 Mac 上對 files 點右鍵，開啟 Electron App 並取得檔案路徑。</p><p>要拿到路徑可以用啟動參數來傳，node.js 在終端機執行時可以帶參數。</p><pre>$ node path/to/file.js --custom-argv</pre><p>在 node.js 中，可透過 process.argv 取得啟動參數。</p><pre>process.argv<br><br>// [&#39;path/to/file.js&#39;, &#39;--custom-argv&#39;]</pre><p>Electron 也可用一樣方式傳遞啟動參數。</p><pre>$ npx electron path/to/main.js --custom-argv</pre><p>用 electron-builder 打包成安裝檔裝進 Mac 後，可用終端機啟動並以相同方式傳遞。(需要開權限)</p><pre>$ &quot;/Applications/My App.app&quot; --custom-argv</pre><p>知道傳遞參數的方法後，只需要能在右鍵選單上加一個 item 來執行上面這段 command 即可。</p><p>Mac 最簡單的自訂右鍵選單方法是用「快速動作」執行 AppleScript。在啟動台開起 Automator &gt; 快速動作，左側「動作」選單上搜尋「AppleScript」就能看到一個「執行 AppleScript」的節點。</p><p>將其拖曳到右邊工作區，就會出現一個輸入框，裡面有初始程式碼。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H9mbGil21ZMw9nawS_DEwg.png" /></figure><p>加上一行 code 命令以 shell 指令啟動 App 並帶參數。</p><pre>(* Open MyApp.workflow *)<br><br>on run {input, parameters}<br> (* 用 shell 啟動 Electron App *)<br> do shell script &quot;open -n &#39;/Applications/My App.app&#39; --args --custom-arg&quot;<br><br> return input<br>end run</pre><p>Mac 會將被右鍵點擊的檔案傳入到 input 變數上，要拿到他的 path 需要轉手一下。</p><pre>(* Open MyApp.workflow *)<br><br>on run {input, parameters}<br>  (* 宣告 filePath 變數，將 input file path 值裝進去*)<br>  set filePath to POSIX path of input<br><br>  do shell script &quot;/Applications/My App.app &quot; &amp; quoted form of filePath<br><br>  return input<br>end run</pre><p>要注意檔名、資料夾名是可以有空格的，所以在 command 上需要用引號包成一段 string，才不會被錯誤當成兩段命令。</p><p>AppleScript 沒有 JavaScript 那種 template string 功能，要把 string 跟變數拚到一起，得用傳統 + 的寫法，且需要把 input 變數值也加上引號。</p><p>這是 JavaScript 的 + 號字串拼接寫法。</p><pre>// javascript<br>&quot;path/to/file.js &quot; + &quot;&#39;&quot; + filePath + &quot;&#39;&quot;<br><br>// output: &quot;path/to/file.js &#39;path/to/input&#39;&quot;</pre><p>這是 AppleScript 的拼接寫法。</p><pre>(* AppleScript 是用 &amp; 替代 + 號*)<br>&quot;path/to/file.js &quot; &amp; &quot;&#39;&quot; &amp; filePath &amp; &quot;&#39;&quot;<br><br>(* 也可用指令讓 AppleScript 幫變數值自動加上引號 *)<br>&quot;path/to/file.js &quot; &amp; quoted form of filePath</pre><p>存檔時會要求輸入檔名，檔名即是右鍵選單上出現的顯示名稱。這邊取作Open MyApp.overflow，儲存完之後，對檔案或資料夾點右鍵 &gt; 快速動作，應該就能看到。</p><p>這些快速動作 Mac 會存在 ~/Library/Services 裡面，副檔名是 .overflow 預設是不顯示的。</p><p>overflow file 其實是個資料夾，把他 copy 到 VSCode 的工作區打開來看就能發現。裡面有個 Info.plist 檔案，可以手動修改右鍵選單上的顯示名稱。但是用 Automator 編輯過之後，又會自動跟檔名同步。</p><pre>// Info.plist<br>&lt;dict&gt;<br>  &lt;key&gt;default&lt;/key&gt;<br>  &lt;string&gt;Open MyApp&lt;/string&gt; // 右鍵顯示名稱<br>&lt;/dict&gt;</pre><p>用 Automator 做完右鍵選單的 overflow 檔後，可以把他複製到 Electron 專案中，開個資料夾裝起來。</p><p>然後在裡面新增一個 shell script 叫做 postinstall ，寫下希望在安裝時執行的終端機命令。</p><pre>#!/bin/sh<br><br># 複製快速動作到 Services 資料夾, 視同安裝效果<br>cp -r &quot;$(pwd)/Open MyApp.workflow&quot; ~/Library/Services</pre><p>這邊的 pwd 作用類似 node.js 的 __dirname。</p><p>接著在 electron-builder 設定安裝程式，告訴他要執行的 scripts 位置</p><pre>// electron-builder conifg<br>{<br>  pkg: {<br>    scripts: &#39;../path/to/postinstall&#39;,<br>  }<br>}</pre><p>如此就能在 Electron App 安裝時，存入快速動作的檔案。最後要注意 user 可能需要手動去開啟才能在「右鍵 &gt; 快速動作」中看到。</p><pre>系統設定 &gt; 延伸功能 &gt; Finder &gt; 勾選要啟用的快速動作</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*bXw90ABECKfbRgHtyE9hxA.png" /></figure><p>最後分享一下 AppleScript debug 方法。</p><p>上面這些做法需要 build 完，安裝上去才能跑，但 production 根本沒有終端機可監控，無法用 dev 啟動快速確認 AppleScript 傳進來的 argv 到底長啥樣，幾乎等於是盲寫。</p><p>我們可以在一個簡短的 path 上建立一個 .js 檔。</p><pre>$ touch ~/test.js</pre><p>接著在這個 js 檔裡面寫一個拋錯，就能透過 Error Message 的系統 Alert 把接收到的 argv 給印出來。</p><pre>throw JSON.stringify(process.argv, null, 2)</pre><p>用拋錯的方式是我目前想到最暴力無腦的，因為快速動作是在背景執行，正常手段根本看不到 print。</p><p>讓這個 js 假裝是 electron 執行檔，在 AppleScript 裡用 node 去執行它。</p><pre>do shell script &quot;node ~/test.js &quot; &amp; quoted form of filePath</pre><p>但直接這樣寫可能會報錯，因為 AppleScript 的執行環境裡未必有 node 這個 alias。</p><p>可以在終端機用 where 確認 node 指令的實際位置，把他替換掉。</p><pre>$ where node<br><br># ~/.nvm/versions/node/v18.20.3/bin/node</pre><p>要對應框選多檔案點右鍵的寫法比較麻煩，概念是在 AppleScript 宣一個類 Array 的變數，跑迴圈把 input path 逐個加進去。同時需要在 path 之間添加一個分隔符，這樣餵到 js 之後才有辦法去 split 出來。</p><pre>on run {input, parameters}<br>  (* 宣告 *)<br>  set filePaths to {}<br>  set separator to &quot;|;;|&quot;<br><br>  (* 跑迴圈 *) <br>  set counter to 1<br>  repeat with eachItem in input<br>    set end of filePaths to POSIX path of eachItem<br><br>    (* last 不加分隔符 *)<br>    if counter &lt; (input count) then<br>      set end of filePaths to separator<br>    end if<br><br>    set counter to counter + 1<br>  end repeat<br><br>  (* 將類 array to string *)<br>  set result to filePaths as text<br><br>  do shell script &quot;[path/to/node] ~/test.js &quot; &amp; quoted form of result<br>end run</pre><p>由於 AppleScript 比較語意化，一行一行讀應該是能看懂的。真不行可以問 chatGPT。畢竟我也是問 chatGPT 問出來的……</p><p>以上。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eefcb6ea481c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codememo/mac-%E5%8F%B3%E9%8D%B5%E5%95%9F%E5%8B%95-electron-app-%E4%B8%A6%E5%82%B3%E9%81%9E%E5%8F%83%E6%95%B8-eefcb6ea481c">Mac 右鍵啟動 Electron App 並傳遞參數</a> was originally published in <a href="https://medium.com/codememo">Code 隨筆放置場</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue3 在 Child 定義 Parent 的具名插槽 (Define named slots of Parent from Child Component)]]></title>
            <link>https://medium.com/codememo/vue3-%E5%9C%A8-child-%E5%AE%9A%E7%BE%A9-parent-%E7%9A%84%E5%85%B7%E5%90%8D%E6%8F%92%E6%A7%BD-define-named-slots-of-parent-from-child-component-ba28a182f8e2?source=rss-34af170eeca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba28a182f8e2</guid>
            <category><![CDATA[vue-3]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[components]]></category>
            <dc:creator><![CDATA[Lastor]]></dc:creator>
            <pubDate>Fri, 20 Sep 2024 08:58:18 GMT</pubDate>
            <atom:updated>2024-09-20T09:15:07.288Z</atom:updated>
            <content:encoded><![CDATA[<p>最近工作專案很常碰到這樣的需求，希望在 Dialog 或類似 Dialog 的額外視窗上面去跑一段 steps 流程。大概這種感覺：</p><p>(此篇以 Element-Plus 來舉例)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*I5UOT9rdvDelw9dFdwAA-A.png" /></figure><p>這種彈窗類的 UI 通常都會包成一個 &lt;Dialog&gt; Component 組件，然後將 header、footer 開放成 slots，讓使用者可以去局部自定義自己想要的 html 與 styles。</p><pre>&lt;template&gt;<br>  &lt;ElDialog model-value title=&quot;Setup Something&quot; width=&quot;640&quot;&gt;<br>    StepA<br><br>    &lt;template #footer&gt;<br>      &lt;ElButton @click=&quot;emits(&#39;next&#39;)&quot;&gt;Next&lt;/ElButton&gt;<br>    &lt;/template&gt;<br>  &lt;/ElDialog&gt;<br>&lt;/template&gt;</pre><p>各頁面勢必都會有複雜度不一的商業邏輯，所以會傾向把各個 Step 都包成一個組件來分別管理，方便維護。</p><p>由於各頁面的 header title 以及底下的 buttons 可能都會不一樣，所以一種直接的拆法是把每個 Dialog 都包到 Child 組件裡面，讓他們自行管理。</p><pre>// Index.vue<br>&lt;StepA v-if=&quot;step === 0&quot; /&gt;<br>&lt;StepB v-if=&quot;step === 1&quot; /&gt;<br>...<br><br>// StepA.vue<br>&lt;ElDialog&gt;<br>  ...<br><br>  &lt;template #footer&gt;<br>    ...<br>  &lt;/template&gt;<br>&lt;/&lt;ElDialog&gt;</pre><p>可偏偏 Dialog 這種玩意，在 v-if 條件切換從 StepA 變成 StepB 時，UI 會有一個明顯的開關效果，這顯然是不期望的行為。為了不出現開關現象，就得把 Dialog 放在父層去共用，然後只替換 content 的部分。</p><pre>&lt;ElDialog&gt;<br>  &lt;StepA v-if=&quot;step === 0&quot; /&gt;<br>  &lt;StepB v-if=&quot;step === 1&quot; /&gt;<br><br>  &lt;template #footer&gt;<br>    ...<br>  &lt;/template&gt;<br>&lt;/&lt;ElDialog&gt;</pre><p>雖然解決了跳頁會開關的問題，但 title 跟 footer 都定義在 Parent 了，沒法寫在 Child 讓其自己去管理，被迫得把各頁面的部份邏輯與 footer 的 html 寫在 Parent。</p><p>最終將導致 Parent 無可避免地出現許多代管與分配的邏輯，變得越來越肥大，自己寫完後過一兩個禮拜再回來看，會連自己都看不太懂在寫甚麼……</p><h3>解決方案</h3><p>遇上這樣的情況，我就在找尋有沒有辦法把 &lt;template #footer&gt; 寫在 Child 並讓 Parent 能吃到？但 Vue slots 的機制是不允許 slots 隔層的。</p><pre>// Index.vue<br>&lt;ElDialog&gt;<br>  &lt;StepA v-if=&quot;step === 0&quot; /&gt;<br>  &lt;StepB v-if=&quot;step === 1&quot; /&gt;<br>  ...<br>&lt;/&lt;ElDialog&gt;<br><br>// StepA.vue<br>&lt;template&gt;<br>  &lt;div&gt;StepA&lt;/div&gt;<br><br>  &lt;template #footer&gt; // &lt;- Error<br>    ...<br>  &lt;/template&gt;<br>&lt;/template&gt;</pre><p>查了許久，似乎都沒辦法做到這件事。後來跟同事討論，得到了一個想法，如果是把 footer 內容包成一個組件，在父層傳進去呢? 例如這樣：</p><pre>&lt;ElDialog&gt;<br>  &lt;StepA /&gt;<br><br>  &lt;template #footer&gt;<br>    &lt;!-- 另外做一個 Component 定義好傳進去 --&gt;<br>    &lt;StepA.Footer /&gt;<br>  &lt;/template&gt;<br>&lt;/&lt;ElDialog&gt;</pre><p>概念上看起來是可行的，但 Vue 要包成這樣是挺麻煩的，甚至還會被 eslint 擋，就算不用 chain 鏈，每個 Step page 都要單獨包一個 Footer 組件也是手續繁雜。</p><p>但這倒是給了我一個靈感，本質上就是要想辦法把 footer 的 VNode 給存起來，然後在 Parnet 的 &lt;template #footer&gt; 給它倒進去就是了。如果 footer 能夠在 Child 直接定義那就更好了。</p><p>剛好 Vue 生態圈就有一個現成的工具可以使用，也就是 VueUse 的 createReusableTemplate，這玩意就是在做 VNode 的儲存與傳遞的。</p><p><a href="https://vueuse.org/core/createReusableTemplate/">VueUse</a></p><p>於是，我們就可以利用它，在 Parent 這個共用的 scope 去建立出 ReuseableTemplate，然後把 Definer 傳給 Child 讓它們各自去定義就行了。</p><p>Parent：</p><pre>// Index.vue<br>&lt;template&gt;<br>  &lt;ElDialog v-model=&quot;show&quot; title=&quot;Setup Something&quot; width=&quot;640&quot;&gt;<br>    &lt;StepA v-if=&quot;step === 0&quot; :definer=&quot;DefineFooter&quot; /&gt;<br>    &lt;StepB v-if=&quot;step === 1&quot; :definer=&quot;DefineFooter&quot; /&gt;<br><br>    &lt;template #footer&gt;<br>      &lt;Footer /&gt;<br>    &lt;/template&gt;<br>  &lt;/ElDialog&gt;<br>&lt;/template&gt;<br><br>&lt;script setup lang=&quot;ts&quot;&gt;<br>// ...skip others<br>import { createReusableTemplate } from &#39;@vueuse/core&#39;<br><br>const [DefineFooter, Footer] = createReusableTemplate()<br>&lt;/script&gt;</pre><p>Child：</p><pre>// StepA.vue<br>&lt;template&gt;<br>  &lt;div&gt;StepA&lt;/div&gt;<br><br>  &lt;DefineFooter&gt;<br>    &lt;ElButton @click=&quot;emits(&#39;next&#39;)&quot;&gt;Next&lt;/ElButton&gt;<br>  &lt;/DefineFooter&gt;<br>&lt;/template&gt;<br><br>&lt;script setup lang=&quot;ts&quot;&gt;<br>import { computed } from &#39;vue&#39;<br>import type { Component } from &#39;vue&#39;<br><br>const props = defineProps&lt;{ definer: Component }&gt;()<br><br>// Rename to PascalCase<br>const DefineFooter = computed(() =&gt; props.definer)<br>&lt;/script&gt;</pre><p>這樣一切就簡單了，header slot 也可以用同樣的方式處理，如此一來 Parent 僅需專心管理頁面切換就好，Child 自己的邏輯跟 html 都可以交還給它們自行管理。</p><h3>沒裝 VueUse 怎麼辦?</h3><p>當然，並非每個專案都有使用 VueUse，遇上沒有裝、不想裝、沒辦法裝等情況，有沒有辦法自己刻這個機制呢?</p><p>自然是可以的，去翻一下 VueUse 的原始碼就能大概知道 createReusableTemplate 是怎麼做的。</p><p><a href="https://github.com/vueuse/vueuse/blob/main/packages/core/createReusableTemplate/index.ts">vueuse/packages/core/createReusableTemplate/index.ts at main · vueuse/vueuse</a></p><p>原理是去做一個 Define 組件用來接收 slots，然後用一個 state 去儲存起來。最後再做一個用來 render 這些 slots 的組件。</p><p>理解原理之後，我們可以做一個簡單版，只傳遞 default slot 的仿品。</p><pre>// Index.vue<br>&lt;template&gt;<br>  &lt;ElDialog v-model=&quot;show&quot; title=&quot;Setup Something&quot; width=&quot;640&quot;&gt;<br>    &lt;StepA v-if=&quot;step === 0&quot; :definer=&quot;DefineFooter&quot; /&gt;<br>    &lt;StepB v-if=&quot;step === 1&quot; :definer=&quot;DefineFooter&quot; /&gt;<br><br>    &lt;template #footer&gt;<br>      &lt;Footer /&gt;<br>    &lt;/template&gt;<br>  &lt;/ElDialog&gt;<br>&lt;/template&gt;<br><br>&lt;script setup lang=&quot;ts&quot;&gt;<br>// ...skip others<br>import { shallowRef, useSlots, h, Fragment } from &#39;vue&#39;<br>import type { Slot, Component } from &#39;vue&#39;<br><br>const children = shallowRef&lt;Slot&gt;()<br><br>const DefineFooter: Component = () =&gt; {<br>  const slots = useSlots()<br>  children.value = slots.default<br>}<br><br>const Footer: Component = () =&gt; {<br>  return h(Fragment, children.value?.())<br><br>  // or<br>  // return children.value?.()<br>}<br>&lt;/script&gt;</pre><p>宣告 Vue Component 的方式有許多種，VueUse 那邊使用的是 defineComponent，而我這邊使用更精簡的 Functional Component。</p><p>這個 Component Function 其實就是 Vue 的 render function，在使用 jsx 時經常會用到，而 slots 也是用這種 render function 的形式保存的。所以要 render 時，不一定要包裹 h()，也可以直接執行就能拿到返回的 VNode。</p><p>響應式 state 要儲存 Component 這種複雜內容時，會更建議使用淺層的 shallowRef()，這樣 Vue 就不會去做深層 Proxy 並且我們也不需要，可節省些資源。</p><p>透過這樣的手法就能成功的拐個彎，在 Child 去定義 Parent 的 named slots 了。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba28a182f8e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codememo/vue3-%E5%9C%A8-child-%E5%AE%9A%E7%BE%A9-parent-%E7%9A%84%E5%85%B7%E5%90%8D%E6%8F%92%E6%A7%BD-define-named-slots-of-parent-from-child-component-ba28a182f8e2">Vue3 在 Child 定義 Parent 的具名插槽 (Define named slots of Parent from Child Component)</a> was originally published in <a href="https://medium.com/codememo">Code 隨筆放置場</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vite Library submodules 專案設置 for Typescript]]></title>
            <link>https://medium.com/codememo/vite-library-submodules-%E5%B0%88%E6%A1%88%E8%A8%AD%E7%BD%AE-for-typescript-ce02d5f229d5?source=rss-34af170eeca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce02d5f229d5</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[submodules]]></category>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Lastor]]></dc:creator>
            <pubDate>Sat, 03 Aug 2024 14:59:31 GMT</pubDate>
            <atom:updated>2024-08-03T14:59:31.958Z</atom:updated>
            <content:encoded><![CDATA[<p>研究了一下坊間那些 npm packages 的這種 submodules exports 是怎麼做的。寫篇 Blog 記錄一下。</p><pre>import { funcA } form &#39;some-lib/moduleA&#39;<br>import { funcB } form &#39;some-lib/moduleB&#39;</pre><p>在開發 npm library 給其他專案安裝使用時，需要一些設定讓 npm 知道該如何 import 這個 lib。</p><p>如果想要拆分成多個子 modules，最簡單的方法就是做一個 index 把所有 module 全部一起 export，然後在 package.json 設定為進入點。</p><p>例如一個用 vite 做打包的 lib 專案叫做 my-lib，假設檔案結構如下：</p><pre>lib/<br>  moduleA/<br>    index.ts<br>  moduleB/<br>    index.ts<br>  index.ts</pre><p>內部拆分成兩個 module A 與 B，然後用根目錄的 index.ts 統一輸出。</p><pre>// lib/moduleA/index.ts<br>export const funcA = () =&gt; console.log(&#39;a&#39;)<br><br>// lib/moduleB/index.ts<br>export const funcB = () =&gt; console.log(&#39;b&#39;)<br><br>// lib/index.ts<br>export * from &#39;./moduleA&#39;<br>export * from &#39;./moduleB&#39;</pre><p>vite build 簡單設定一下，讓 dist 最後長得像下面這樣。不清楚這一塊設定的話，可以參考<a href="https://vitejs.dev/guide/build#library-mode">官方文件</a>。</p><pre>dist/<br>  index.js<br>  index.cjs</pre><p>其他專案透過 npm 安裝 my-lib 之後，用 import 或 require 載入 my-lib 時，npm 會自動去 node_modules 底下找同名的資料夾，並讀取裡面的 package.json 來得知該如何導入這個套件。</p><p>如果是 ESM 專案的話，它會去看 module 屬性，CommonJS 的話則會去找 main 屬性。</p><pre>// my-lib package.json<br>{<br>  &quot;name&quot;: &quot;my-lib&quot;,<br>  &quot;main&quot;: &quot;./dist/index.cjs&quot;, // CommonJS entry point<br>  &quot;module&quot;: &quot;./dist/index.js&quot;, // ESM entry point<br>  // ...<br>}</pre><p>設定好之後，就能在 runtime 時正確載入 my-lib 的檔案，VScode 也能偵測到檔案內容給出智能提示。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2WJzN1BxYl5n5-NHOIk9QQ.png" /></figure><p>這是最簡單也好理解的方式。但如果要設定成下面這種 submodules 子路徑形式的話，就得多寫一些設定了。</p><pre>// consumer project<br>import { funcA } from &#39;my-lib/moduleA&#39;<br>import { funcB } from &#39;my-lib/moduleB&#39;</pre><p>首先要改 vite config 的 build 設定，將進入點拆成 moduleA 與 moduleB。fileName 也要改成 callback 來設定，才能分別取不同的檔名。</p><pre>// my-lib vite.config.ts<br>import { defineConfig } from &#39;vite&#39;<br>import { resolve, dirname } from &#39;node:path&#39;<br>import { fileURLToPath } from &#39;node:url&#39;<br><br>const __dirname = dirname(fileURLToPath(import.meta.url));<br><br>export default defineConfig({<br>  build: {<br>    lib: {<br>      entry: {<br>        moduleA: resolve(__dirname, &#39;lib/moduleA/index.ts&#39;),<br>        moduleB: resolve(__dirname, &#39;lib/moduleB/index.ts&#39;),<br>      },<br>      name: &#39;MyLib&#39;,<br>      formats: [&#39;es&#39;, &#39;cjs&#39;],<br>      fileName: (format, name) =&gt; {<br>        return format === &#39;cjs&#39; ? `${name}.cjs` : `${name}.js`<br>      },<br>    },<br>  },<br>})</pre><p>接著 package.json 要加上 exports 屬性，來設定子路徑映射。</p><pre>// my-lib package.json<br>{<br>  &quot;exports&quot;: {<br>    &quot;./moduleA&quot;: {<br>      &quot;import&quot;: &quot;./dist/moduleA.js&quot;,<br>      &quot;require&quot;: &quot;./dist/moduleA.cjs&quot;<br>    },<br>    &quot;./moduleB&quot;: {<br>      &quot;import&quot;: &quot;./dist/moduleB.js&quot;,<br>      &quot;require&quot;: &quot;./dist/moduleB.cjs&quot;<br>    }<br>  }<br>}</pre><p>這樣其他專案就能用 submodules 子路徑的方式載入了。</p><p>But!! 這僅限於 JS 專案，當下游專案是 TS 時，案情就不單純了……</p><h4>For Typescript 專案</h4><p>要讓 TS 專案引入，就得在 build 時一併將 .d.ts 定義檔產出，用 vite 打包的話，直接使用 vite-plugin-dts 是個比較簡單的方式。</p><p>輸出的 .d.ts 則會依照原本的檔案結構放置，各 module 的 bundle 則會跟原本一樣輸出到 dist 像是這樣：</p><pre>dist/<br>  moduleA/<br>    index.d.ts<br>  moduleB/<br>    index.d.ts<br>  moduleA.js<br>  moduleA.cjs<br>  moduleB.js<br>  moduleB.cjs</pre><p>由於產出的 .d.ts 跟進入點的位置不一樣，所以要在 package.json 的 exports 追加上 types 屬性，告訴 TS type 定義檔在哪裡。</p><pre>// my-lib package.json<br>{<br>  &quot;exports&quot;: {<br>    &quot;./moduleA&quot;: {<br>      &quot;types&quot;: &quot;./dist/moduleA/index.d.ts&quot;, // add this<br>      &quot;import&quot;: &quot;./dist/moduleA.js&quot;,<br>      &quot;require&quot;: &quot;./dist/moduleA.cjs&quot;<br>    },<br>    &quot;./moduleB&quot;: {<br>      &quot;types&quot;: &quot;./dist/moduleB/index.d.ts&quot;, // add this<br>      &quot;import&quot;: &quot;./dist/moduleB.js&quot;,<br>      &quot;require&quot;: &quot;./dist/moduleB.cjs&quot;<br>    }<br>  }<br>}</pre><p>這樣一來，「比較新的」TS 專案安裝這個 my-lib 後，TS 就能抓到定義了。對，是比較新的才行。</p><p>TS 專案只有比較新的設定才能直接吃到 package.json 的 exports，需要將 tsconfig 的moduleResolution 設定成 Node16 或 NodeNext 才行。</p><p>而變更了 moduleResolution 同時也會被 TS 要求變更 module 的設定，但這個設定對專案的影響很大，老專案可能會牽一髮動全身。顯然，限制使用者的 tsconfig 設定並不是一個好作法。</p><p>後來找到一個解，是利用 package.json 有一個叫做 typesVersions 的設定，這設定本來是用來指定不同版本的 typescript 可以指定使用不同的 .d.ts 定義檔，換個思路也可以用來告訴非 NodeNext 的專案該去哪裡找定義檔。</p><pre>// my-lib package.json<br>{<br>  &quot;typesVersions&quot;: {<br>    &quot;*&quot;: {<br>      &quot;moduleA&quot;: [&quot;./dist/moduleA/index.d.ts&quot;],<br>      &quot;moduleB&quot;: [&quot;./dist/moduleB/index.d.ts&quot;],<br>      &quot;*&quot;: [&quot;./dist/index.d.ts&quot;] // 有需要 root 可加, 注意有順序差異<br>    }<br>  },<br>  // ...<br>}</pre><p>typesVersions 底下的第一層 object 是設定 TS 版本，但我們目的不是這個，所以直接給 all 星號，第二層 object 的設定方式有點類似 path alias 那種路徑映射的寫法。</p><p>如果要設定 root 的話，記得 exports 那邊也要加上 root module 的設定才行。</p><p>Reference:<br><a href="https://antfu.me/posts/types-for-sub-modules">Types for Submodules</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce02d5f229d5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codememo/vite-library-submodules-%E5%B0%88%E6%A1%88%E8%A8%AD%E7%BD%AE-for-typescript-ce02d5f229d5">Vite Library submodules 專案設置 for Typescript</a> was originally published in <a href="https://medium.com/codememo">Code 隨筆放置場</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node ReadStream 轉接 Web ReadableStream 的 memory leak 問題]]></title>
            <link>https://medium.com/codememo/node-readstream-%E8%BD%89%E6%8E%A5-web-readablestream-%E7%9A%84-memory-leak-%E5%95%8F%E9%A1%8C-2138798c67cb?source=rss-34af170eeca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2138798c67cb</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[backpressure]]></category>
            <dc:creator><![CDATA[Lastor]]></dc:creator>
            <pubDate>Sat, 03 Aug 2024 10:00:27 GMT</pubDate>
            <atom:updated>2024-08-03T10:00:27.249Z</atom:updated>
            <content:encoded><![CDATA[<p>記錄一下最近碰到的問題。</p><p>公司的桌面端 App 專案，有個需求是讀取硬碟上 file 做一些加工處理之後再存回硬碟上。</p><p>由於 Node.js 本身存在記憶體限制，所以為了應對大檔案讀寫，勢必得用 Stream 串流來處理。但實際遇上好幾十 GB 量級的檔案時，App 最終還是遭遇了記憶體 alloc 挖不出來的問題，花了許多功夫排查原因……</p><p>找了幾天之後發現，似乎是 Node.js 的 Stream 本身就存在一些 GC 不良的問題，且 stream.pipe() 串接時，也不會自動控制水流。必須要使用 node:stream module 的 pipeline 去串接才有自動控制機制。</p><p><a href="https://github.com/nodejs/node/issues/50762">High memory consumption when piping between streams · Issue #50762 · nodejs/node</a></p><p>由於 Node Stream 不會在後面忙碌時自動暫停水流，導致 ReadStream 一直無腦把 chunk 往下送，但後面又來不及處理，最後記憶體爆炸。</p><p>就算是將 Node Stream 轉接到有自動控制功能的 Web Stream 上也會有一樣的問題，畢竟 Web Stream 就是不同的介面，他沒辦法直接管理 Node Stream。</p><pre>import fs from &quot;node:fs&quot;<br><br>const readStream = fs.createReadStream(&#39;/path/to/file&#39;)<br><br>const readable = new ReadableStream({<br>  async start(controller) {<br>    try {<br>      for await (const chunk of readStream) {<br>        controller.enqueue(chunk) // 串流一接上, 就會一直往下流<br>      }<br>    } finally {<br>      controller.close()<br>    }<br>  }<br>})<br><br>await readable<br>  .pipeThrough(someStream)<br>  .pipeThrough(heavyStream) // 處理較慢時, 前面還一直送 chunk 水管就會爆炸<br>  .pipeTo(writable)</pre><p>後來才找到了正確的串接方式，Stream 有一種叫做 Backpressure 概念，就是在講，當上游的資料產生速度快過下游的消費速度時的處理方式。</p><p>而具體做法很單純，就是 ReadStream API 是有個暫停跟繼續的，不能直接用 for-await 去接水流，而是要用傳統串流 on 監聽的方式，去手動做暫停跟繼續。</p><p>需要把 ReadableStream 的部分改一下。</p><pre>// Backpressure support<br><br>const readStream = fs.createReadStream(&#39;/path/to/file&#39;)<br><br>const readable = new ReadableStream({<br>  async start(controller) {<br>    readStream.on(&#39;data&#39;, (chunk) =&gt; {<br>      controller.enqueue(chunk)<br><br>      // 當下游請求 size 小於零表示忙碌中, 暫停 read<br>      if (controller.desiredSize &lt;= 0) {<br>        readStream.pause()<br>      }<br>    })<br><br>    readStream.on(&#39;error&#39;, () =&gt; controller.error())<br>    readStream.on(&#39;end&#39;, () =&gt; controller.close())<br>  },<br>  /** 下游閒置時會呼叫 pull 向上游請求資源 */<br>  pull() {<br>    readStream.resume() // 恢復 read<br>  },<br>  cancel() {<br>    readStream.destroy()<br>  }<br>})</pre><p>這樣在下游忙碌時，就可以自動暫停 Node ReadStream，並在閒置時自動繼續串流，就不會有 memory leak 的問題了。</p><p>Reference:</p><ul><li><a href="https://nodejs.org/en/learn/modules/backpressuring-in-streams">Node.js - Backpressuring in Streams</a></li><li><a href="https://streams.spec.whatwg.org/#example-rs-push-backpressure">Streams</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2138798c67cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codememo/node-readstream-%E8%BD%89%E6%8E%A5-web-readablestream-%E7%9A%84-memory-leak-%E5%95%8F%E9%A1%8C-2138798c67cb">Node ReadStream 轉接 Web ReadableStream 的 memory leak 問題</a> was originally published in <a href="https://medium.com/codememo">Code 隨筆放置場</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[JS] tc39 新提案 iterator helpers]]></title>
            <link>https://medium.com/codememo/js-tc39-%E6%96%B0%E6%8F%90%E6%A1%88-iterator-helpers-6fb3ef1a9688?source=rss-34af170eeca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fb3ef1a9688</guid>
            <category><![CDATA[iterator-helpers]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[iterators]]></category>
            <dc:creator><![CDATA[Lastor]]></dc:creator>
            <pubDate>Sat, 04 May 2024 10:20:25 GMT</pubDate>
            <atom:updated>2024-05-05T03:29:20.132Z</atom:updated>
            <content:encoded><![CDATA[<p>分享一下最近才得知的一個提案 iterator helpers。</p><p><a href="https://github.com/tc39/proposal-iterator-helpers">GitHub - tc39/proposal-iterator-helpers: Methods for working with iterators in ECMAScript</a></p><p>此提案已經到了 stage3，且 Chrome 已經實裝可以使用了。</p><p>該提案可以解決 JavaScript 中，Array 的 method chaining 較為耗資源的問題。相信這種寫法，在處理 Array data 時，就算沒用過，也應該多少都看過。</p><pre>;[1, 2, 3, 4, 5]<br>  .map((num) =&gt; num * num)<br>  .filter((num) =&gt; num % 2 === 1)</pre><p>這種 chaining 作法，利用了 method name 的語義，本身具有不錯的易讀性，可以很快速的知道這段 code 在做些甚麼。</p><p>但這樣的寫法是把 1 個迴圈就能做完的事情，分成了多個迴圈，且 map() 與 filter() 這些方法本身，都會產生一組新的 Array，增加記憶體消耗。</p><p>所以在意效能的人，會更傾向使用傳統 for 迴圈、forEach()，或是 reduce()、flatMap() 這類方法，透過一個迴圈去處理掉。可是，這樣勢必得添加一些 if 條件判斷，手法不好的人，可能會寫出易讀性欠佳的 code。</p><p>那有沒有辦法做到 method chaining 的易讀性，同時又兼具效能呢?</p><p>這就是 iterator helpers 想解決的問題。</p><h4>關於 iterator helpers</h4><p>先來看一段範例 code，該提案已經在 Chrome 上面實裝，所以較新版的 Chrome 是可以直接運行的。</p><pre>// 給定一個 array 將其轉成 generator<br>function* toIterator(arr) {<br>  for (const val of arr) {<br>    yield val<br>  }<br>}<br><br>// 然後跟 Array 的 method chaining 一樣的寫法<br>// 但屁股需要多加個 toArray()<br>const result = toIterator([1, 2, 3, 4, 5])<br>  .map((n) =&gt; n * n)<br>  .filter((n) =&gt; n % 2 === 1)<br>  .toArray()<br><br>console.log(result) // [1, 9, 25]</pre><p>這個作法是利用了帶星號的 function*，也就是 Generator 去產生一個 Iterator 迭代器。這玩意平常寫 JavaScript 很少會用到，它可以簡單理解成一種有別於 for 迴圈的特殊形式 each 方法。</p><pre>function* generator() {<br>  yield 1<br>  yield 2<br>  yield 3<br>}<br><br>const gen = generator()<br>gen.next() // { value: 1, done: false }<br>gen.next() // { value: 2, done: false }<br>gen.next() // { value: 3, done: false }<br>gen.next() // { value: undefined, done: true}</pre><p>在我們執行 next() 之前，generator 就會彷彿時間暫停一樣，不會動作。當執行了 next() 之後，就會 run 到有 yield 的地方停下，並回傳右邊的 value。</p><p>詳細可以參考 MDN。</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator">Generator - JavaScript | MDN</a></p><p>這個 iterator helpers 就是利用 generator 的可操作性，去把 method chaining 的 callback 給串到同一個迴圈裡去做掉。</p><p>至於為什麼要叫做 iterator helper 而不是 generator helper？我想應該是因為 Generator Class 是繼承自 Iterator Class 的。</p><pre>function* generator() {}<br>const gen = generator()<br><br>gen instanceof Iterator // true</pre><p>附帶一提，在瀏覽器中 Array Class 裡面都有一個 Symbol.iterator 屬性，它的值是一個用來製作 iterator 的 function。JavaScript 的 for 迴圈就是靠這個屬性去運作的。</p><p>可以看到，這玩意在瀏覽器中跟 generator 是一樣的。</p><pre>const iter = [1, 2, 3][Symbol.iterator]()<br><br>iter.next() // { value: 1, done: false }</pre><p>所以前面的 iterator helpers 那段範例也可以寫成這樣。</p><pre>;[1, 2, 3, 4, 5][Symbol.iterator]()<br>  .map((n) =&gt; n * n)<br>  .filter(n =&gt; n % 2 === 1)<br>  .toArray()<br><br>// [1, 9, 25]</pre><p>為什麼要強調瀏覽器呢？因為 Node.js 的實現方式不太一樣，它並不存在一個全域的 Iterator Class。</p><h4>簡單實作 iterator helpers</h4><p>接下來實作看看 iterator 的 map() 與 filter() 方法，以便了解它是怎麼實現的。</p><p>再來看一下這段範例 code。</p><pre>function* toIterator(arr) {<br>  for (const val of arr) {<br>    yield val<br>  }<br>}<br><br>toIterator([1, 2, 3, 4, 5])<br>  .map((n) =&gt; n * n)<br>  .filter((n) =&gt; n % 2 === 1)<br>  .toArray()</pre><p>直接在瀏覽器中觀察，toIterator() 會回傳一個 genteror，為了實現 method chaining，勢必 map() 與 filter() 會回傳 this，也就是 genteror。</p><p>實際去看 map() 的回傳值，會發現 Chrome 顯示的是 iterator，而我們知道它是 genteror 的父層，推測成立。</p><p>也就是說，map() 與 filter() 這兩個方法是直接擴充到 Iterator Class 上的，這樣只要對 Iterator.prototype 實作新方法就可以了。</p><p>為了避免跟 Chrome 已經實作的 map() 撞名，來改個名字叫做 myMap()。</p><pre>// 對 Iterator 原型添加新方法<br>window.Iterator.prototype.myMap = function* myMap(cb) {<br>  let index = 0<br><br>  while (true) {<br>    const { done, value } = this.next()<br>    if (done) break<br><br>    yield cb(value, index++)<br>  }<br>}<br><br>// 也可以用 Object.defineProperty() 來做<br>Object.defineProperty(window.Iterator.prototype, &#39;myMap&#39;, {<br>  get() {<br>    return function* (cb) {<br>      let index = 0<br><br>      while (true) {<br>        const { done, value } = this.next()<br>        if (done) break<br><br>        yield cb(value, index++)<br>      }<br>    }<br>  },<br>})</pre><p>對 prototype 直接添加方法之後，所有新 new 出來的 iterator instance 都能夠享有該方法，且由於是同一個 instance，所以 this 就能拿到前一個方法所回傳的 iterator，也就能夠透過 next() 去 trigger 迭代器往下走，拿到要 each 的目標值。</p><p>最後就是比照 map() 該有的邏輯去寫就好，callback 回傳甚麼就回傳甚麼，map() 的概念是相對簡單的。</p><p>另外加一個 index 去記數，才能還原 Array.prototype.map 的第二參數 index。</p><pre>;[1, 2, 3].map((val, index) =&gt; { ... })</pre><p>至於第三參數先跳過，畢竟那不是重點，就沒有多去研究。</p><p>再來 filter() 也是一樣，另取一個名字 myFilter()。</p><pre>window.Iterator.prototype.myFilter = function* myFilter(cb) {<br>  let index = 0<br><br>  while (true) {<br>    const { done, value } = this.next()<br>    if (done) break<br><br>    if (cb(value, index++)) yield value<br>  }<br>}</pre><p>做到這邊應該多少能 get 到，為什麼 iterator helper 屁股需要接一個 toArray()，因為它 chaining 回傳的都是一個個 iterator，所以需要有一個把結果轉回 Array 的方法。</p><p>toArray() 這邊一樣另取一個名字，就叫 run() 吧。</p><pre>window.Iterator.prototype.run = function run() {<br>  let array = []<br><br>  while (true) {<br>    const { done, value } = this.next()<br>    if (done) return array<br><br>    array.push(value)<br>  }<br>}</pre><p>它很單純就是蒐集前面的 iterator 一路傳下來的 item，宣一個 Array 去把他們裝起來，最後 return 回去。</p><p>都做完了之後就可以來跑看看了，大功告成!!</p><pre>;[1, 2, 3, 4, 5][Symbol.iterator]()<br>  .myMap((v) =&gt; v * v)<br>  .myFilter((v) =&gt; v &amp; 1)<br>  .run()<br><br>// [1, 9, 25]</pre><h4>如何在 Node.js 實作</h4><p>最後稍微提一下，如果想在 Node.js 實作的話會比較麻煩。如同前面所提，Node.js 的 globalThis 是沒有 Iterator 的。所以要用比較 hack 的方式去取得。</p><p>參考這篇討論：</p><p><a href="https://stackoverflow.com/questions/38580048/modifying-generator-function-prototype">Modifying generator function prototype</a></p><p>可以利用 Object.getPrototypeOf() 這個方法來強行取得 Generator Class。</p><pre>const Generator = Object.getPrototypeOf(function* () {})</pre><p>接下來就跟瀏覽器一樣，對它的 prototype 添加新方法就可以了。</p><pre>Generator.prototype.map = function* map(cb) {<br>  // ...<br>}</pre><p>目前也有人已經把 iterator helper 的 polyfill 給做出來了，有興趣的話可以在還沒實裝的環境下搶先使用喔。</p><p><a href="https://github.com/MadProbe/iterator-helpers-polyfill">GitHub - MadProbe/iterator-helpers-polyfill: A polyfill for Iterator helpers proposal written in Typescript for environments supporting ES2018+</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fb3ef1a9688" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codememo/js-tc39-%E6%96%B0%E6%8F%90%E6%A1%88-iterator-helpers-6fb3ef1a9688">[JS] tc39 新提案 iterator helpers</a> was originally published in <a href="https://medium.com/codememo">Code 隨筆放置場</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue2 從 Webpack4 遷移到 Vite]]></title>
            <link>https://medium.com/codememo/vue2-%E5%BE%9E-webpack4-%E9%81%B7%E7%A7%BB%E5%88%B0-vite-8d371fbf3f36?source=rss-34af170eeca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d371fbf3f36</guid>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[webpack4]]></category>
            <dc:creator><![CDATA[Lastor]]></dc:creator>
            <pubDate>Sun, 01 Oct 2023 07:30:11 GMT</pubDate>
            <atom:updated>2023-10-01T07:39:51.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*btx5eV5HvB4l4egf2OJT5A.png" /></figure><p>前陣子幫公司完成了 Vue2 老專案升級。從 node10 升到 node16，並從 @rails/webpacker (webpack4) 成功遷移到了 vite。</p><p>這篇來給自己紀錄一下。</p><pre>## 目錄<br><br>- 情境介紹<br>- 關於 Rails Webpacker<br>- 重建 Node.js Webpack Config<br>  - @rails/webpacker 依賴 node-sass<br>  - 棄用 @babel/polyfill<br>  - postcss-loader 的順序<br>  - postcss 插件 autoprefixer 與 browserslist<br>  - 處理 css 要區分 dev 與 build<br>- 遷移到 Vite<br>  - import 需加上 .vue 副檔名<br>  - sass 的 /deep/ 寫法變更<br>  - sass v2 棄用顯示數學計算<br>  - 在 css import node_modules<br>  - jsx 用法變更<br>  - process.env 不可用<br>  - vite 不支援 CommonJS 需改為 ESM<br>  - vite build 需另外設定處理 CommonJS<br>  - webpack require.context() 不可用<br>  - vite 與 webpack5 不再提供 path 等 polyfill<br>  - 處理 css :export<br>  - 替代 webpack svg-sprite-loader<br>  - pnpm ignore missing peer 警告<br>  - build 後 el-table 呈現空白<br>  - element-ui 自訂 theme 被 umy-ui 搶 css 權重<br>  - vite 中 template whitespace 間隔消失<br>  - ES6+ 語法出現 VScode ts 報錯<br>  </pre><h3>情境介紹</h3><pre># 專案環境<br><br>- Ruby on Rails 前後端共構專案 (使用 Webpacker)<br>- 前端透過 @rails/webpacker 構建 Vue2<br>- node10，有 node-sass<br>- 當前是 Server build，Node.js 版本被 Server 限制</pre><p>一直以來這個前端專案就很想脫離 Rails 的掌控，分離出來獨立維護。前端環境從 node14 開始有了許多的變化，Node.js 不再能無腦向下兼容。</p><p>最近紛紛出現使用 Mac M1 的同事，遇上了 node10 無法安裝的問題，再加上 node-sass 等舊套件已被棄用，無法運作於 node12 以上環境等因素，早晚都得面對專案升級的問題。</p><p>於是，趁著工作的空閒期，嘗試將專案升級。目標大致如下：</p><pre>- 升級 Node.js 版本，至少到 14 or 16<br>- 脫離 @rails/webpacker 依賴<br>- 前後端 git repo 分離<br>- 遷移至 Vite</pre><h3>關於 Rails Webpacker</h3><p>先說明一下 Rails Webpacker 這玩意是啥，它是類似 vue-cli、create-react-app 那種 webpack 腳手架，不過是 Ruby on Rails 的版本，但它已不再維護。</p><p>當前版本內部使用 webpack4，並內置 node-sass 等等，當時主流的前端工具。由於它是針對 Rails 來建構的，所以會出現一些前端不熟悉的配置。</p><p>不過 webpack 配置本質上都是差不多的，只要搞清楚 config 在哪、html 進入點、js 進入點這些東西，就能夠重架一個 Node.js 主導的 webpack 配置。</p><p>先網上查詢關於 Rails Webpacker 的文章，然後找出核心配置有哪些，其他的可以不用太深入。</p><p>對照此專案的情況，可以整理出這些檔案。</p><pre># rails webpacker 設定檔<br>config/webpacker.yml<br><br># 終端機 cli 的執行檔<br>bin/webpack<br>bin/webpack-dev-server<br><br># webpack 設定檔<br>config/webpack/custom.js (非預設)<br>config/webpack/environment.js<br>config/webpack/development.js<br>config/webpack/production.js<br>// ...<br><br># js 進入點<br>app/javascript/pack/application.js<br>app/javascript/pack/main.js (非預設)<br><br># vue 的 source files<br>app/javascript/src/**/*<br><br># html 進入點<br>app/views/layouts/application.html.erb <br>app/views/layouts/vue.html.erb  (非預設)<br>app/views/vue/index.html.erb</pre><p>在 webpacker 的設定檔 config/webpacker.yml 可以找到 inpurt 與 output 設定。</p><pre># config/webpacker.yml<br>source_path: app/javascript<br>source_entry_path: packs<br>public_root_path: public<br>public_output_path: packs</pre><p>從 source_xxx 得知 input 在 app/javascript/packs/* 底下，似乎預設會是 application.js，但我這專案改成了 main.js。而 output 則會根據 public_xxx 的設定 build 到 public/packs/*。</p><p>執行檔是用 rails cli 指令，進行 dev 啟動或 build 時，會根據那兩個檔案的內容去調用 webpack。</p><pre># 縮寫 rails s, 後端 dev 啟動<br># 進到 vue 頁面會執行 bin/webpack<br>$ rails server<br><br># 依據 Procfile 的設定同時啟動前後端 dev server<br># 這邊會調用 bin/webpack-dev-server<br>$ foreman start<br><br># 前端 build<br>rake assets:precompile</pre><p>再來是 webpack 的設定檔，裡面有很多個，但從命名可以看出那只是區分成 development、production、test 不同模式而已。</p><p>從內容可以推斷出核心檔案是 environment.js，不同模式的檔案都會引入它。我這專案有另外寫一個 custom.js，這支會在 environment.js 被引入，用來覆蓋預設設定。</p><p>而 custom.js 這支檔案的寫法與 webpack config 是一樣的，所以就可以從這支檔案得知具體設定。</p><p>js 進入點沒甚麼特別的機制，但 html 進入點就比較麻煩，因為他是 .erb 檔，可以視作 Rails 的模板文件，它會接收一些從 Rails render 出來的內容。</p><p>大概是長這樣。</p><pre>&lt;!-- app/views/layouts/vue.html.erb --&gt;<br>&lt;head&gt;<br>  &lt;%= javascript_pack_tag &#39;main&#39; %&gt;<br>  &lt;%= stylesheet_pack_tag &#39;main&#39; %&gt;<br>  &lt;%= csrf_meta_tags %&gt;<br>  &lt;!-- ... --&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>  &lt;div class=&quot;container&quot; data-behavior=&quot;app&quot;&gt;<br>    &lt;%= render &#39;path/to/file&#39; %&gt;<br>    &lt;%= yield %&gt;<br>  &lt;/div&gt;<br>&lt;/body&gt;</pre><p>那些看起來奇怪的 html &lt;%= … %&gt; 是 erb 的模板語法。head 裡面的 javascript_pack_tag 是指定在這邊塞 webpack 編譯後的 js 檔，顧名思義，這段會去 app/javascript/pack/* 底下尋找 main.js。而後面兩個我這專案實際運行確認是空的，所以不理它。</p><p>body 底下的 render 從命名可以看出，這邊是插入指定的模板組件進來。我這專案引入的只是一塊版本資訊的 banner，先不理它，之後可以在 Vue 裡面重做。</p><p>另一個 yield，則會導入 rails contoller 定義的模板。</p><pre># app/controllers/vue_controller.rb<br>class VueController &lt; ApplicationController<br>  layout &#39;vue&#39;<br>  def index<br>  end<br>end<br><br># app/views/vue/index.html.erb<br>&lt;div id=&quot;app&quot;&gt;&lt;/div&gt;</pre><p>layout &#39;vue&#39; 指的是 app/views/* 底下的 vue 資料夾，然後再指向裡面的 index.html.erb。</p><p>確認 Rails 注入的東西有哪些之後，就可以改寫回單純的 index.html 了。</p><p>如此，進入點都找到了，也有 config 了，那就可以進入下一步。</p><h3>重建 Node.js Webpack Config</h3><p>先嘗試重建 webpack config，讓 Node.js 可以執行 dev 啟動以及 build，脫離 Rails 控制。</p><p>除了上述的核心檔案之外，也別忘了根目錄底下各式 js 相關的 config：</p><pre># npm &amp; js 設定<br>package.json<br>yarn-lock (or package-lock.json or pnpm-lock.yaml)<br>jsconfig.json (or tsconfig.json)<br>.nvmrc<br><br># babel (JS 編譯器)<br>.babelrc<br><br># postcss (css 後處理器)<br>postcss.config.js<br>.browserslistrc<br><br># eslint (風格規範)<br>.eslintignore<br>.eslintrc.js<br><br># prettier (auto formatter)<br>.prettierrc.js</pre><p>原本 webpack 是 @rails/webacker 底下的子依賴，實際並沒有安裝。</p><p>需先補安裝。可以在 lock 檔確認 @rails/webpacker 使用的 webpack 版本。</p><pre>$ yarn add webpack@&quot;^4.41.2&quot;<br>$ yarn add webpack-cli@&quot;^3.3.10&quot;<br>$ yarn add webpack-dev-server@&quot;3.10.1&quot;</pre><p>補上 npm scripts。</p><pre>// package.json<br>&quot;scripts&quot;: {<br>  &quot;dev&quot;: &quot;webpack-dev-server&quot;,<br>  &quot;build&quot;: &quot;webpack --mode production&quot;<br>  // ...<br>}</pre><p>接著新增 webpack.config.js，把 config/webpack/custom.js 搬過來，就可以嘗試啟動，進入除錯之旅。</p><p>但我因為想順便複習一下 webpack，所以找了一篇教學從零一個一個去設定。</p><p><a href="https://juejin.cn/post/6989491439243624461">webpack4 从零搭建 vue 项目开发环境</a></p><p>我這專案的情況，照這教學做完，再跟原本 custom.js 的設定核對之後，就能順利啟動了。</p><p>webpack 這玩意麻煩在它不是開箱即用的，幾乎所有設定都要自己去弄。不過概念上也不複雜，就是每一個 assets 都要告訴 webpack 要如何解析。無非就是指定 css 使用這個 loader，img 使用那個 loader，然後設定細節。</p><p>確認 Node.js 端啟動沒問題之後，可以新建 repo 搬過去了，不確定的話就直接抄 vite 或 vue-cli 的目錄結構。</p><pre># 新建專案<br><br>public<br>  favicon.ico<br>  logo.svg<br>src<br>  ...<br>  App.vue<br>  main.js # 原本在 rails 是單獨放置, 現在將它放到 src 裡面<br>index.html<br>...configs</pre><p>搬移之後，修改 webpack config 的 entry、output、alias 那些路徑。</p><p>接著移除 @rails/webpacker。</p><pre>$ yarn remove @rails/webpacker</pre><p>再嘗試啟動，由於 webpacker 內包的子依賴已移除，會發現需要補裝一些套件，我的情況是這些：</p><pre>{<br>  &quot;node-sass&quot;: &quot;^4.14.1&quot;,<br>  &quot;postcss&quot;: &quot;^7.0.39&quot;,<br>  &quot;postcss-flexbugs-fixes&quot;: &quot;^4.2.1&quot;,<br>  &quot;postcss-import&quot;: &quot;^12.0.1&quot;,<br>  &quot;postcss-preset-env&quot;: &quot;^6.7.0&quot;,<br>  &quot;sass-loader&quot;: &quot;^7.3.1&quot;,<br>}</pre><p>現在，已經成功將前端獨立拆了出來，脫離了 Rails Webpacker 依賴。再來就是系統升級了。</p><p>移除 node-sass，更換為 sass。它的兼容性很強，可以無腦安裝最新版，當前是 v1.66.1。</p><pre>$ yarn remove node-sass<br>$ yarn add sass</pre><p>這邊要注意一下，換成 sass 之後原本 /deep/ 的寫法被棄用，需要改成 :deep，直接 VSCode 搜尋替換就好。</p><pre>/* node-sass */<br>/deep/.my-style {}<br><br>/* sass */<br>:deep .my-style {}</pre><p>接著升級 Node.js。用 nvm 之類的版本管理器切換到 node16，然後移除 node_modules 與 yarn-lock 重裝套件。並依喜好，順道將 yarn 更換成 pnpm。</p><pre># 切換 node16<br>$ nvm install 16<br>$ nvm use 16<br><br># 啟用 pnpm 並更新到最新<br>$ corepack enable<br>$ corepack prepare pnpm@latest --activate<br><br># 以 node16 與 pnpm 重裝套件<br>$ pnpm install</pre><p>然後測試 dev 啟動以及 build，確認沒問題之後就告個段落。</p><p>成功完成了：</p><ul><li>Node.js 升級至 v16</li><li>脫離 @rails/webpacker 與 node-sass 依賴</li><li>前後端分離</li></ul><p>流水帳記錄一下 webpack config 重建遇上的坑。</p><h4>@rails/webpacker 依賴 node-sass</h4><p>node-sass，只能運行在 node12 以下版本。這是因為它使用了 node-gyp 牽扯到 python 一些雜七雜八的。Mac M1 由於架構不同會裝不上去。</p><p>升級到 node14+ 之後，只要將套件換成 sass 就行了，webpack 的話要記得 sass-loader 也要升。</p><h4>棄用 @babel/polyfill</h4><p>babel 7.4.0 開始棄用 @babel/polyfill，改用 @babel/preset-env，設定方式不一樣。前者會寫在 webpack config 上，後者會寫在 babel config 上。</p><h4>postcss-loader 的順序</h4><p>webpack 的 loader 設定採用 Array，但執行順序是「反著來的」，它會從後面的 loader 先開始解析。</p><p>所以使用 Sass + postcss 時，postcss-loader 要放在 sass-loader 的前面，先解析 Sass 完成之後，postcss 才能接手。</p><pre>module: {<br>  rules: {<br>    {<br>      test: /\.(sass|scss)$/,<br>      use: [&#39;vue-style-loader&#39;, &#39;css-loader&#39;, &#39;postcss-loader&#39;, &#39;sass-loader&#39;],<br>    },<br>  }<br>}</pre><h4>postcss 插件 autoprefixer 與 browserslist</h4><p>autoprefixer 透過 postcss 驅動，幫 css 添加 -webkit- 這些兼容性前綴。同時它會根據 .browserslistrc 的設定編譯成不同內容。</p><p>browserslist 這玩意也會影響到 babel，如果指定兼容比較舊的瀏覽器，會造成 ?. 以及 ?? 這些 js 新語法在編譯時報錯，需要補裝相關 plugin。</p><pre># 處理 ?.<br>@babel/plugin-transform-optional-chaining<br><br># 處理 ??<br>@babel/plugin-transform-nullish-coalescing-operator</pre><p>然後這個 autoprefixer 在 postcss 新版本已可用 postcss-preset-env 取代。</p><h4>處理 css 要區分 dev 與 build</h4><p>啥都不設定的話，webpack 預設會將 css 打包到 js 裡面，造成 js 過度肥大。</p><p>dev 啟動一般會用 style-loader (vue 使用 vue-style-loader) 將 css 編譯到 &lt;style&gt; 裡面往 html 塞。</p><p>build 則會希望打包成獨立的 .css file，這就必須將 style-loader 替換為 mini-css-extract-plugin 。</p><p>可以使用 webpack-merge 來分割 dev 與 prod build 的 webpack config。</p><h3>遷移到 Vite</h3><p>成功將前端分離出來之後，接著嘗試從 webpack4 遷移到 vite。在 config 與插件部分，因為 Vite 開箱即用，比 webpack 要簡單許多。</p><p>先把 vite 與 Vue2 相關插件裝上，jsx 插件則看專案有沒有用到。</p><pre>$ pnpm i -D vite @vitejs/plugin-vue2 @vitejs/plugin-vue2-jsx</pre><p>加入 npm scripts，webpack 的內容可以先保留，遷移完成再移除。</p><pre>&quot;scripts&quot;: {<br>  &quot;dev&quot;: &quot;vite&quot;,<br>  &quot;build&quot;: &quot;vite build&quot;,<br>  &quot;preview&quot;: &quot;vite preview&quot;,<br><br>  &quot;dev:w&quot;: &quot;webpack-dev-server&quot;,<br>  &quot;build:w&quot;: &quot;webpack --mode production&quot;,<br>},</pre><p>建立 vite config 配置，比起 webpack 相當的精簡。</p><pre>// vite.config.js<br>import { defineConfig } from &#39;vite&#39;<br>import vue from &#39;@vitejs/plugin-vue2&#39;<br>import vueJsx from &#39;@vitejs/plugin-vue2-jsx&#39;<br>import path from &#39;node:path&#39;<br><br>export default defineConfig({<br>  plugins: [vue(), vueJsx()],<br>  resolve: {<br>    alias: {<br>      &#39;@&#39;: path.join(__dirname, &#39;src&#39;),<br>      // ...<br>    },<br>  },<br>})</pre><p>然後這些東西可以全砍了。</p><pre># webpack<br>webpack<br>webpack-dev-server<br>webpack-cli<br>webpack.config.js<br><br># webpack loaders<br>vue-loader<br>css-loader<br>// ...<br><br># webpack plugins<br>mini-css-extract-plugin<br>html-webpack-plugin<br>// ...<br><br># babel<br>@babel/core<br>@babel/preset-env<br>// ...<br><br># postcss<br>postcss<br>postcss-import<br>cssnano<br>// ...</pre><p>webpack 相關的東西，特別是那一大堆的 loader 與 plugins 都不再需要了。</p><blockquote>postcss 在 vite 雖有內建，但 postcss-preset-env 沒內建，要另外裝。</blockquote><p>babel 除非有特殊需求，不然在 IE 已經正式走入歷史的現在，for 現代瀏覽器的 vite，babel 已不再是標配。需要編譯 jsx 的話，vite 有專門的 plugin。</p><p>如果真有兼容老瀏覽器的需求，可以裝 @vitejs/plugin-legacy ，裡面已包好 babel 配置。</p><p>再來就是嘗試啟動的除錯之旅。</p><p>vite 雖然在 config 沒有一堆煩人的 loader 與 plugins，但這只是在設定上比較精簡，實際跟 webpack 環境還是有很多需要磨平的地方。</p><h4>import 需加上 .vue 副檔名</h4><p>webpack4 環境多數會設定省略 .vue 副檔名。 vite + Vue3 環境則是強烈建議加上副檔名，以便 VScode + Volar 獲取 type 定義。</p><pre>// 加上 .vue<br>import App from &#39;./App.vue&#39;</pre><p>可是一個一個去加 .vue 太吐血了，vite 現在也支援 webpack 同款設定，去省略副檔名。</p><pre>// vite.config.js<br>resolve: {<br>  extensions: [&#39;.mjs&#39;, &#39;.js&#39;, &#39;.mts&#39;, &#39;.ts&#39;, &#39;.vue&#39;], // 省略副檔名<br>},</pre><h4>sass 的 /deep/ 寫法變更</h4><p>前面有提過，雖然不是 vite vs webpack 的問題，但還是要注意一下。原本舊的 /deep/ 寫法要改成 :deep。</p><p>這種寫法 /deep/.my-class 替換時要注意加空格 :deep .my-class。而更新的版本會要求使用 :deep()。</p><p>雖然這嚴格來說不是 sass 的語法，但它會被 sass 或其他預處理器的版本所影響。</p><p><a href="https://blog.51cto.com/knifeedge/5648025">Scss--将node-sass切换为sass(原dart-sass)</a></p><h4>sass v2 棄用顯示數學計算</h4><p>sass v1.32 以上版本，會出現棄用提示，不再支持直接的數學計算寫法。</p><pre>// NG<br>1 / 5</pre><p>要改成這種 function 調用的寫法。</p><pre>// OK<br>calc(1 / 5)<br>math.div(1, 5)</pre><p>如果有用 element-ui，它內部 Sass 有用舊的數學寫法，會一直噴警告，只能將 sass 退版到 ~1.32，忽略警告。</p><h4>在 css import node_modules</h4><p>webpack 支持使用波浪號 ~ 在 css 導入 node_modeuls。但這個 vite 看不懂，vite 是採用跟 js 同款寫法來處理。</p><pre>// webpack<br>@import &quot;~element-ui/packages/theme-chalk/src/index&quot;;<br><br>// vite<br>@import &quot;element-ui/packages/theme-chalk/src/index&quot;;</pre><p>懶得手動修改的話，可以透過 alias 設定，讓 vite 辨識波浪號。</p><pre>resolve: {<br>  alias: [<br>    // 正規判斷 ~ 開頭, 指向 node_modules<br>    {<br>      find: /^~(?!\/)/,<br>      replacement: path.join(__dirname, &#39;node_modules/&#39;),<br>    },<br>  ],<br>}</pre><h4>jsx 用法變更</h4><p>webpack 環境下，隨著 babel 等相關插件的新舊版本差異，jsx 的用法略有不同。而 vite 這邊畢竟比較新，可直接在 &lt;script setup&gt; 裡面使用 jsx。</p><p>但要注意，vite 中使用 jsx 需要打上 lang 標記作為識別符號。</p><pre>&lt;script lang=&quot;jsx&quot;&gt;<br>// ...<br>&lt;/script&gt;</pre><h4>process.env 不可用</h4><p>process.env 為 Node.js 語法，在 vite 中不可用，需以 import.meta 替代。</p><pre>// webpack<br>process.env.NODE_ENV<br><br>// vite<br>import.meta.env.MODE</pre><p><a href="https://vitejs.dev/guide/env-and-mode.html#env-variables">Vite</a></p><h4>vite 不支援 CommonJS 需改為 ESM</h4><p>vite 使用 ESM 而不是 CommonJS，需將 require / module.exports 改為 import / export。</p><pre>// NG<br>const axios = require(&#39;axios&#39;)<br>module.exports = { foo: &#39;bar&#39; }<br><br>// OK<br>import axios from &#39;axios&#39;<br>export default { foo: &#39;bar&#39; }</pre><p>社群也有人製作 vite 的 CommonJS 插件 vite-plugin-commonjs ，懶得手動改的話可以試試。</p><p>另外 webpack 還有 script-loader 提供的特殊語法。雖然我這專案有這行 code，但排查後發現沒有被使用到，我就先跳過了。</p><pre>// webpack + script-loader<br>require(&#39;script-loader!jsonlint&#39;)</pre><p>目前只知道 script-loader 在做的事，是把目標 js 引入後，直接在 global 執行一次。也就是該 js 的內容會註冊到 window 上可供調用。</p><p>我查不到 vite 該如何實現等價操作，但這專案的這段 code 研究了一下，主要是用 codemirror + jsonlint 在瀏覽器上弄一個 JSON 編輯器出來。</p><p>網上比較新的相關教學，是使用模塊化版本的 jsonlint-mod 來做，這樣就不需要使用到 script-loader 了。</p><pre>import jsonlint from &#39;jsonlint-mod&#39;<br>window.jsonlint = jsonlint</pre><h4>vite build 需另外設定處理 CommonJS</h4><p>如果選擇使用 vite-plugin-commonjs ，那在 build 時會碰到問題，因為這插件是 for dev mode 的。</p><p>另外，也可能會碰到老套件內部使用 CommonJS，我們無法去改它。只能透過 vite-plugin-commonjs 來處理。</p><p>這樣在 build 時，要去設定 rollup 轉換 CommonJS。</p><pre>// vite.config.js<br>build: {<br>  commonjsOptions: {<br>    transformMixedEsModules: true, // 轉換兼容 commonjs<br>  },<br>},</pre><p><a href="https://github.com/originjs/vite-plugins/issues/9#issuecomment-924668456">build以后，vit preview 会报Uncaught ReferenceError: require is not defined · Issue #9 · originjs/vite-plugins</a></p><h4>webpack require.context() 不可用</h4><p>require.context() 是 webpack 提供的特殊語法，可用來獲取資料夾目錄，實現自動化導入。這個 vite 自然是看不懂的。</p><p>但 vite 有等價語法，可用 <a href="https://vitejs.dev/guide/features.html#glob-import">import.env.glob</a> 來改寫。例如要匯入 files 資料夾裡的所有 js：</p><pre>// webpack<br>const files = require.context(&#39;./files&#39;, true, /\.js$/)<br>const fileObj = files.keys().reduce((obj, path) =&gt; {<br>  const file = files(path)<br>  obj[path] = file.default<br>  return obj<br>}, {})<br><br><br>// vite<br>const files = import.meta.glob(&#39;./files/*.js&#39;, { eager: true })<br>const fileObj = Object.keys(files).reduce((obj, path) =&gt; {<br>  const file = files[path]<br>  obj[path] = file.default<br>  return obj<br>}, {})</pre><p>要注意回傳的東西不太一樣，require.context() 回傳的是 function，並帶有 props。而 import.meta.glob() 則是回傳一個 object。</p><h4>vite 與 webpack5 不再提供 path 等 polyfill</h4><p>path 是 Node.js 提供的模塊，並不是瀏覽器有的東西。</p><p>如今 vite 與 webpack5 都不再提供 polyfill，在瀏覽器端執行的 code，不能直接引入使用。</p><p>vite 環境下，瀏覽器端的 code 原則上都不該使用 path 這些 Node.js 的功能了。但是老 code 已經這樣寫了，怎麼辦？</p><p>可以安裝瀏覽器版本 <a href="https://www.npmjs.com/package/path-browserify">path-browserify</a> 頂一下，但最好找時間把有用到的地方重寫。安裝之後，利用 alias 設定來映射。</p><pre>// vite.config.js<br>resolve: {<br>  alias: {<br>    // remapping to path-browserify<br>    path: &#39;path-browserify&#39;,<br>  },<br>},</pre><p>如果老 code 有用到 path.resolve() 會很麻煩，它會在內部以 global 的方式調用 process.cwd() 。</p><p>這雖然也有瀏覽器版本 <a href="https://www.npmjs.com/package/process">process</a>。</p><p>但由於它是在 global 被調用的，沒有使用 import 關鍵字，所以無法設定 alias 來處理，得用比較 cheat 的做法，將其在 html 頭部導入後，掛到 window 上面。</p><pre>&lt;!-- index.html --&gt;<br>&lt;script type=&quot;module&quot;&gt;<br>  import process from &#39;process&#39;<br>  window.process = process<br>&lt;/script&gt;</pre><p><a href="https://github.com/vitejs/vite/issues/3817#issuecomment-864450199">vite use web3.js throw Uncaught ReferenceError: process is not defined · Issue #3817 · vitejs/vite</a></p><h4>處理 css :export</h4><p>webpack 的 css-loader 有提供一種 :export 語法，讓 js 可以 import 在 css 或 sass 中被定義的變數。</p><p>而在 vite 則透過 css-modules 支援此語法，但要將有用到 :export 的檔案更名為 css modules 的格式，添加中間名 xxx.module.css。</p><p>另外要注意，如果在有使用 :export 的檔案中 import node_modules 的話，vite 會把套件裡面定義的變數也全都導出，嚴重影響編譯速度。</p><pre>// somthing.scss<br>$--color-primary: #1890ff;<br><br>/* js import 時，vite 會將 element-ui 內的變數也全數導入 */<br>@import &quot;element-ui/packages/theme-chalk/src/index.scss&quot;;<br><br>:export {<br>  theme: $--color-primary;<br>}</pre><p>這部分要視專案情況改寫，把 import 跟 :export 分離開來。</p><p><a href="https://github.com/vitejs/vite/discussions/9601">How to share variables between JS and SCSS? · vitejs/vite · Discussion #9601</a></p><h4>替代 webpack svg-sprite-loader</h4><p>svg-sprite-loader 這玩意顧名思義是用精靈圖的概念去一次性導入 svg 檔案。</p><p>如果有用到這個，應該會有一段使用 require.context() 批次導入 svg icon 的 code，並依靠該 loader 在導入時自動註冊 svg。</p><pre>// 自動導入 ./svg 資料夾下的所有 .svg files<br>const req = require.context(&#39;./svg&#39;, false, /\.svg$/)<br>const requireAll = (requireContext) =&gt; {<br>  return requireContext.keys().map(requireContext)<br>}<br>requireAll(req)</pre><p>vite 有個等價的插件 vite-plugin-svg-icons，並且會把自動導入部分也處理好，所以上面那段 code 可以直接砍掉，改去 config 設定就好。</p><pre>// vite.config.js<br>import { createSvgIconsPlugin } from &#39;vite-plugin-svg-icons&#39;<br><br>export default defineConfig({<br>  plugins: [<br>    // svg 預加載, 替代 webpack svg-sprite-loader<br>    createSvgIconsPlugin({<br>      // 指定 dir 自動導入<br>      iconDirs: [path.join(__dirname, &#39;src/icons/svg&#39;)],<br>      // svg-sprite-loader 會打上一個供調用的 id<br>      // 這邊設成一樣的讓老 code 能呼叫到<br>      symbolId: &#39;icon-[name]&#39;,<br>    }),<br>  ],<br>})</pre><p><a href="https://juejin.cn/post/7221750009141002277">如何在vue3+vite中使用svg-sprite-loader（SVG精灵图）</a></p><h4>pnpm ignore missing peer 警告</h4><p>vite 有很多套件的 core 都內建了，只要安裝相關 plugin 就好，例如要使用 postcss-preset-env 時，並不需要安裝 postcss。</p><p>但是 pnpm 會偵測到它依賴 postcss，可它在 vite 底下，pnpm 不做深度檢查，所以它會誤判沒有安裝 peer 依賴，跳出 missing peer 警告。</p><p>另外像是 ant-design-vue 也有設定依賴 vue-template-compiler ，可是 vite 不需要裝這個，pnpm 也會跳出警告。</p><p>這問題可以在 package.json 設定 pnpm ignore missing peer 解決。</p><pre>// package.json<br>{<br>  &quot;pnpm&quot;: {<br>    &quot;peerDependencyRules&quot;: {<br>      &quot;ignoreMissing&quot;: [&quot;vue-template-compiler&quot;, &quot;postcss&quot;]<br>    }<br>  }<br>}</pre><h4>build 後 el-table 呈現空白</h4><p>如果使用 element-ui 與 Vue2.7，可能會碰到 dev 啟動一切正常，但 build 後 el-table 卻 render 空白的情況。</p><p>這似乎是 vue2.7 採用新版 vue-template-complier 與 element-ui 內部寫法衝突導致的問題。在 build 時 element-ui 導入了不同的 vue core，錯誤產生了兩個不同的 vue instance，造成 el-table 吃不到專案的 context。</p><p>可透過 alias 配置，強制統一 vue 的引入目標。</p><pre>// webpack<br>resolve: {<br>  alias: {<br>    &#39;vue$&#39;: &#39;vue/dist/vue.esm.js&#39;,<br>  },<br>},<br><br>// vite<br>resolve: {<br>  alias: {<br>    vue: &#39;vue/dist/vue.esm.js&#39;,<br>  },<br>},</pre><p><a href="https://github.com/ElemeFE/element/issues/21984">[Bug Report] webpack下vue2.7.x, el-table渲染空白 · Issue #21984 · ElemeFE/element</a></p><h4>element-ui 自訂 theme 被 umy-ui 搶 css 權重</h4><p>我這專案同時使用 element-ui 與 umy-ui，都是全域引入該庫的 css。遷移到 vite 後卻發現 element-ui 的 class name 跟 umy-ui 撞名，自定義 theme 的 css 被 umy-ui 給搶權重。</p><p>研究半天發現，這兩個套件的 css 引入順序是這樣寫的。</p><pre>import element-ui css<br>import custom element-ui theme sass<br>import umy-ui css</pre><p>由於 umy-ui 最後才引入，必然它的權重是最強的。但由於 webpack 本身的 bug，錯誤將 Sass 文件最後才引入，所以在 webpack 環境下反而運行正常。</p><p>遷移到 vite 之後，只需調整正確的順序即可。</p><pre>import element-ui css<br>import umy-ui css<br>import custom element-ui theme sass // change this</pre><p><a href="https://github.com/webpack/webpack/issues/215">CSS resolving order · Issue #215 · webpack/webpack</a></p><h4>vite 中 template whitespace 間隔消失</h4><p>這問題蠻瞎的，原本 webpack 環境下，把兩個 html &lt;input&gt; 放一起，渲染結果會有個小小的、類似 margin 效果的間隔。但遷移到 vite 之後卻消失了。</p><p>最初以為是 css 跑掉了，查了半天才發現是 template 編譯的問題……</p><pre>&lt;!-- source --&gt;<br>&lt;input /&gt;<br>&lt;input /&gt;<br><br>&lt;!-- webpack 編譯後 --&gt;<br>&lt;input /&gt; &lt;input /&gt;<br><br>&lt;!-- vite 編譯後 --&gt;<br>&lt;input /&gt;&lt;input /&gt;</pre><p>Vue 的 template 本身是種模板引擎，跟 pug 那些一樣，會有 white space 的相關設定。</p><p>webpack 的 vue-loader 預設是將 line break 轉換成 space。而 vite 的 plugin-vue2 則會完全 minify。</p><p>可以透過設定 vue template 的 whitespace 還原。</p><pre>// vite.config.js<br>plugins: [<br>  vue({<br>    template: {<br>      compilerOptions: {<br>        // 使 template 編譯保留空格<br>        whitespace: &#39;preserve&#39;,<br>      },<br>    },<br>  }),<br>],</pre><ul><li><a href="https://stackoverflow.com/questions/55334508/prevent-vue-render-newline-between-elements">Prevent vue render newline between elements</a></li><li><a href="https://github.com/vuejs/vue/tree/dev/packages/vue-template-compiler#options">vue/packages/vue-template-compiler at dev · vuejs/vue</a></li></ul><h4>ES6+ 語法出現 VScode ts 報錯</h4><p>專案環境改變後，莫名其妙這一些 ES6+ 語法，在 VScode 中出現了紅線。</p><pre>Object.entries()<br>// Property &#39;entries&#39; does not exist on type &#39;ObjectConstructor&#39;<br><br>async function foo() {}<br>// An async function or method in ES5/ES3 requires the &#39;Promise&#39; constructor</pre><p>排查後發現，是因為 VScode 將 ES+6 的語法拆成了不同的包，預設是不使用。需要在 jsconfig 或 tsconfig 添加 lib ESNext 設定。</p><pre>// jsconfig.json<br>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;lib&quot;: [&quot;DOM&quot;, &quot;DOM.Iterable&quot;, &quot;ESNext&quot;]<br>  }<br>}</pre><p>參考:</p><ul><li><a href="https://kaochenlong.com/2019/11/21/webpacker-with-rails-part-1/">如何在 Rails 使用 Webpacker（上） | 高見龍</a></li><li><a href="https://medium.com/@jogarcia/vuetify-from-webpack-to-vite-ad7f0765f9b6">Vuetify, from Webpack to Vite</a></li><li><a href="https://zhuanlan.zhihu.com/p/402343262">🖖 Vue2.x 改造 ⚡️ Vite</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d371fbf3f36" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codememo/vue2-%E5%BE%9E-webpack4-%E9%81%B7%E7%A7%BB%E5%88%B0-vite-8d371fbf3f36">Vue2 從 Webpack4 遷移到 Vite</a> was originally published in <a href="https://medium.com/codememo">Code 隨筆放置場</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[從 Heroku 遷移至 Fly.io]]></title>
            <link>https://medium.com/codememo/%E7%AD%86%E8%A8%98-%E5%BE%9E-heroku-%E9%81%B7%E7%A7%BB%E8%87%B3-fly-io-5f9f5cdb837b?source=rss-34af170eeca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f9f5cdb837b</guid>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[flyio]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Lastor]]></dc:creator>
            <pubDate>Thu, 03 Aug 2023 09:27:50 GMT</pubDate>
            <atom:updated>2023-08-03T10:07:01.558Z</atom:updated>
            <content:encoded><![CDATA[<p>最近花了點時間，把以前跟別人一起做的 side project 練習作，從 Heroku 搬到 Fly.io 上。</p><p>Heroku 取消免費方案後，搜尋了許多替代方案，大多人推薦的是 <a href="https://fly.io/">Fly.io</a> 或是 <a href="https://render.com/">Render</a>，姑且先選擇了 Fly.io 來試試。</p><p>Fly.io 可以直接使用 GitHub 註冊，而他操作的方式主要是透過終端機 CLI 上傳部署，似乎無法像 Heroku 那樣，用 Web GUI 來操作，也沒辦法直接連接 GitHub repo 進行同步。</p><p>Fly.io 會先透過 CLI 工具進行初始化，偵測你的專案環境生成兩份設定檔，其中一份是 docker 的 image 設定，上傳後就直接用 docker 建構。</p><p>Fly.io 有提供 Heroku 的遷移方案，但我這邊選擇從零新架一個 App，想嘗試直接遷移的可以自行嘗試。</p><p><a href="https://fly.io/docs/rails/getting-started/migrate-from-heroku/">Migrate from Heroku</a></p><p>註冊之後就會有一連串的引導訊息，會教你起一個 Hello World 的 App，可以自行選擇要用 Node.js 亦或是其他語言。基本上照作就好，這篇會記錄一些自己認為的重點，或著該說是坑點的地方。</p><p>本文紀錄的是 2023 / 08 版本的 Fly.io。</p><h3>Pricing 收費</h3><p>先講一下收費，因為我被這個坑到了。目前 Google 搜尋到的許多文章，會建議使用 Fly.io，很大原因也是因為他有基本免費方案，且不用綁信用卡也能使用基本功能。</p><p>但他改了，可能因為 Heroku 難民大量湧入，所以改了收費相關的細節。可以參考官方關於 Pricing 的頁面。</p><p><a href="https://fly.io/docs/about/pricing/">Fly App Pricing</a></p><p>重點大概是說，他們現在不提供一般意義上的免費方案，而是依照用量來收費，只要低於這個用量，無論你是用甚麼方案，都會是免費。</p><ul><li>Up to 3 shared-cpu-1x 256mb VMs<strong>†</strong></li><li>3GB persistent volume storage (total)</li><li>160GB outbound data transfer</li></ul><p>雖然我對 Server 這塊不是說很熟，有點沒看明白。但我的理解上應該是一個組織 (Personal 個人也算一個組織) 最多可以有 3 個 VM，每個都不得超過 256mb。</p><p>volume 是管儲存空間相關的東西，不得超過 3GB。最後一條應該網站流量吧，我不太確定。</p><p>操作 Fly.io 的 CLI 時，會有一個 scale 指令，這開頭的指令大多都是擴充容器配置用的。看網上文章，似乎之前的版本只有操作到 scale 時才會跟你說要綁信用卡。</p><p>但是當前版本的 Fly.io 已經改成要先綁信用卡才允許基本使用了。</p><p>另外要注意的是，官方的 Get Started 教學，會誘導你去設定超出免費額度的容器配置，跟著照作的會就會直接被收費。雖然收的不多就是，我大概被收了 0.2 美元。</p><h3>註冊 &amp; 安裝 flyctl CLI</h3><p>自己挑一個喜歡的方式註冊，完成之後會跳出歡迎訊息，跟你說推薦安裝他們的 CLI 工具 flyctl。如果不想裝東西，也可以使用 Web 平台。</p><p>但這是一個 Modal 彈窗，我不小心點到旁邊就直接關掉了，然後就找不到他所謂的 Web 平台相關訊息。不過整體看來他是推薦使用 CLI 的，Web 操作平台就先無視吧。</p><p>直接照這個教學，依照不同 OS 安裝就好。</p><p><a href="https://fly.io/docs/hands-on/install-flyctl/">Install flyctl</a></p><p>我的是 Windows，經過測試無法使用 cmder 以 Linux Shell 的語法安裝。還是得乖乖的用 PowerShell 去安裝。</p><pre>$ pwsh -Command &quot;iwr https://fly.io/install.ps1 -useb | iex&quot;</pre><p>安裝之後可以用以下指令確認是否可以呼叫，如果不行的話重開終端機試試。</p><pre>$ flyctl -h<br><br>// alias<br>$ fly -h</pre><p>然而官網教學沒有說明怎麼移除他，要去爬官方的<a href="https://community.fly.io/t/how-to-uninstall-or-remove-flyctl/7155">討論串</a>才有。大致上是沒有快速 uninstall 的指令或程式，要手動去移除他的資料夾。</p><pre># 列出指令所在的 path<br>$ where fly<br><br>// C:\Users\[USER_NAME]\.fly\bin\fly.exe</pre><p>接下來要從 CLI 登入取得權限，他會打開瀏覽器做驗證。</p><pre>$ fly auth login</pre><h3>建立 App</h3><p>繼續跟著官方的新手引導走，或是在 Dashboard 首頁，都會提示說可以先選擇一個擅長的語言，建立一個 Hello World App。我是選擇 Node.js 然後跟著跑一遍。</p><p>他會給你一個 GitHub example repo，裡面是一個很簡單的 Express.js App。可以直接 clone 下來使用，或是要自己弄一個也可以。</p><p>反正一個簡單的專案弄好之後，就在專案根目錄執行 Fly.io 的 App 初始化。</p><pre>$ fly launch</pre><p>然後會跟 vite create app 類似，問你一些問題，有選項可以選。比較重要的是 region 區域，顧名思義是問機器要架在哪。預設會選擇所在地最近的地方。台灣的話預設會是香港。</p><p>但香港比較適合面對大陸客群，如果目標是東南亞可以選新加坡，如果是東北亞可以選日本東京。他這邊可以直接 key in 搜尋，輸入 sin 就會出現新加坡，輸入 to 就會出現東京。</p><p>之後可能會問說要不要設 PostgreSQL 以及 Redis，因為我這專案是用 MySQL，沒有用 Redis，所以都選 No。</p><p>基礎訊息選完之後，他會問要不要直接 deploy，但有時候不會問，我不確定判斷依據是啥。先選擇 No，因為還有其他必要設定得先弄。</p><p>初始化完成之後，會多出兩支檔案 fly.toml 與 Dockerfile ，前者是機器的設定，後者是 docker image 的設定。他會自動偵測你的環境去產生預設配置，可以自己再去改。</p><p>回到 Fly.io 網站上的 Dashboard 重新整理，應該可以看到 App 已經被 new 出來，正在待命。</p><p>可以直接點進去看配置，或是用下列指令確認基本訊息，例如現在使用的 memory 有多少之類。要特別注意 memory 超過 256mb 就會被收費，預設啥都不改的話，就會是 256mb。</p><pre>// 查看 App 基本訊息<br>$ fly status<br><br>// 查看 memory, CPU 個數這些配置<br>$ fly scale show</pre><p>陽春的 Hello World 專案的話，可以直接 deploy，看看跑起來是啥感覺。deploy 期間，會列出進度 log，需要跑一陣子，因為他要跑 docker 然後裝一些東西。</p><pre>$ fly deploy</pre><p>跑完之後我記得會列出最終網址，也可以輸入指令直接開啟網頁，或是在 Web 進入該 App 設定，也能看到部署後的網址。</p><pre>$ fly open</pre><h3>設定環境變數</h3><p>fly.toml 這檔案看副檔名可以得知是 TOML 格式。</p><p><a href="https://toml.io/en/">TOML</a></p><p>裡面有個 [env] 區塊，可以用來設定 非敏感 的環境變數，像是 port 這類東西可以直接寫在這。要注意一下 port 是否跟後面的 internal_port 一樣，有看到老外被這個寫不一樣給坑到。</p><pre># fly.toml<br>[env]<br>  PORT = &quot;8080&quot;<br><br>[http_service]<br>  internal_port = 8080<br>  # ...</pre><p>敏感訊息的環境變數，可以用 CLI 設置。</p><pre># set 環境變數<br>$ fly secrets set KEY=value<br><br># 移除<br>$ fly secrets unset KEY<br><br># list all<br>$ fly secrets list</pre><p>這個設定是那種 set 上去就再也看不到值的設計，不像 Heroku 那樣還可以在後台打開來看。所以最好找個地方 memo 下來，免得以後忘了。</p><p>也可以在 Web 上操作，點進 App 之後 menu 有一個 Secrets 可以設定。</p><h3>指定 Node.js 版本</h3><p>Dockerfile 裡面可以直接指定 Node.js 版本。因為我這是老專案，當初是用 node10，所以我這邊手動指定用 v10 LTS 的版本。</p><pre># Adjust NODE_VERSION as desired<br>ARG NODE_VERSION=10.24.1</pre><p>其實在前面執行 fly launch 的時候，就會跳提示說偵測到我是 node10，但該版本已不支援，自動設定為 node18。而我這邊把它改回來。</p><p>然後要把 Dockerfile 下面關於 python 的部分砍掉。這一段在 node10 會跑不起來。</p><pre># Install packages needed to build node modules<br>RUN apt-get update -qq &amp;&amp; \<br>    apt-get install -y python-is-python3 pkg-config build-essential</pre><p>這一段 python-is-python3 的安裝，推測應該是跟 node-gyp 有關，這玩意跟 node-sass 有關，相信這陣子 node14 到 16 之間，應該很多人被 node-sass 坑過。</p><p>因為我這專案沒有用 Sass，也沒有其他會調用到 node-gyp 編譯的套件，所以直接把這段 python 砍掉不裝了，不然這問題太難搞。</p><p>那如果你是 node10，又有使用 Sass 的話，就要再研究看看該怎麼辦了…… 可能得改裝 python2，或是想辦法把專案升到 node14+，並把 node-sass 換成 sass。</p><h3>配置 MySQL Database</h3><p>Fly.io 似乎是推薦使用 PostgreSQL 的，要用 MySQL 的話可以在官網文件直接搜尋 MySQL。</p><p><a href="https://fly.io/docs/app-guides/mysql-on-fly/">Use a MySQL Database</a></p><p>基本上跟著官方教學跑就可以了，他這概念上是 MySQL 也要起一個 fly app 專門放置。</p><p>他有一個已經寫好的 docker image 用來配置 MySQL，所以只要在本機上開一個新資料夾作為空專案，直接初始化 fly app 就好。</p><pre># Make a directory for the mysql app<br>mkdir my-mysql<br>cd my-mysql<br><br># Run `fly launch` to create an app<br>fly launch</pre><p>區域設置跟前面網站 App 一樣的地方，初始化完之後會發現只有 fly.toml，不會有 Dockerfile。</p><p>這邊要注意，官方教學會要你 create volumns，並設置 10gb，這邊很坑，記得最前面的免費額度是 3gb 嗎? 如果這跟著設 10gb 就會被收費了。</p><pre># 不要照官方教學，改設 3gb<br>fly volumes create mysqldata --size 3 # gb</pre><p>接著設定你希望的 MySQL 帳號與密碼。</p><pre># Set secrets:<br># MYSQL_PASSWORD      - password set for user $MYSQL_USER<br># MYSQL_ROOT_PASSWORD - password set for user &quot;root&quot;<br>fly secrets set MYSQL_PASSWORD=password MYSQL_ROOT_PASSWORD=password</pre><p>這邊我實驗過，環境變數名稱不能改，改了就抓不到了。至於密碼可不可以為空，我就沒測了。</p><p>然後照官方文件，新起的 App 用 v2 的設定去重新配置 fly.toml，注意區域設定 primary_region 不要把他覆蓋掉了。</p><p>這邊因為設定太長，我就不貼上來了。要注意的是這一段，很坑。</p><pre>[processes]<br>app = &quot;--datadir /data/mysql <br>  --default-authentication-plugin mysql_native_password <br>  --performance-schema=OFF <br>  --innodb-buffer-pool-size 64M&quot;</pre><p>照著他這樣寫，之後 deploy 會報錯說 string 不能有多行。但這邊把換行符去掉改單行會很難閱讀，可以參照 TOML 文件的多行寫法，改用三引號。</p><p>但要注意，要使用沒有斜線的版本，有斜線的會不 work。</p><pre># NG<br>app = &quot;&quot;&quot;/<br>  --datadir /data/mysql /<br>  --default-authentication-plugin mysql_native_password /<br>  --performance-schema=OFF /<br>  --innodb-buffer-pool-size 64M /<br>&quot;&quot;&quot;<br><br># OK<br>app = &quot;&quot;&quot;<br>  --datadir /data/mysql <br>  --default-authentication-plugin mysql_native_password <br>  --performance-schema=OFF <br>  --innodb-buffer-pool-size 64M<br>&quot;&quot;&quot;</pre><p>MySQL 版本官方文件有標註 8.0.33 有 bug，所以用 8.0.32。</p><pre># As of 04/25/2023:<br># MySQL 8.0.33 has a bug in it<br># so avoid that specific version<br>[build]<br>  image = &quot;mysql:8.0.32&quot;</pre><p>環境變數設定的 MYSQL_USER 要注意一下，不能設 root 之外，也不能設 user ，因為預設已經有這兩個 user 了。</p><pre>[env]<br>  MYSQL_DATABASE = &quot;some_db&quot;<br>  MYSQL_USER = &quot;non_root_user&quot; # 不能設 &quot;root&quot; 或 &quot;user&quot;</pre><p>改好之後就可以 deploy 了。</p><pre>$ fly deploy</pre><p>要注意官方文件會推薦你說，MySQL 8+ 最好擴充記憶體到 2048mb，千萬別設定這個，擴上去就直接收費了。</p><pre># 別設這個, 超過 256mb 會被收費<br>$ fly scale memory 2048</pre><h3>DB Migrate 與 Seed</h3><p>MySQL deploy 上去之後，需要去初始化 table 以及上種子資料。</p><p>這邊網上查到的做法，其他人會推薦我們在「網站」的那個 App 上去設定 deploy 之後幫我們跑一次 migrate。</p><pre># fly.toml, 我用的 ORM 是 sequelize<br>[deploy]<br>  release_command = &quot;npx sequelize db:migrate&quot;</pre><p>但這有個問題，就是像 sequelize 這種 ORM，他得額外安裝一個 sequelize-cli 才能運行終端機指令。</p><p>也就是說，必須要讓虛擬機也裝上 sequelize-cli 才行，所以得把它裝到 package.json 的 dependencies 上面。(Fly.io 的 docker 配置，預設是不裝 devDependencies)</p><p>所以這邊要考量一下要不要這樣處理，得多裝一個 runtime 用不到的套件。</p><p>我們也可以選擇在本地直接連線 Fly.io 的 MySQL 去操作，flyctl 有幫我們做這方面的快速配置。可以在 MySQL 的 App 根目錄下，輸入以下指令設定反向代理。</p><pre># 反向代理 localhost:3306 到 Fly.io mysql app<br>$ flyctl proxy 3306 -a [mysql-app-name]<br><br># 指定 local port<br>$ flyctl proxy 13306:3306 -a [mysql-app-name]</pre><p>MySQL 預設的 port 都是 3306，所以可以指定代理 localhost:3306。這樣我們就能使用 DBeaver、Workbench 這些可以連線 MySQL 的 GUI，直接往該位置連線 (127.0.0.1:3306 也可以)。</p><p>如果 port 3306 已被占用，可以改用第二行指令，在冒號 : 左手邊去設定 localhost 要使用的 port，右手邊是 remote 的 port，維持不變就好。</p><p>當然，GUI 連的上，Node.js ORM 當然也可以，手動去改一下 sequelize 的設定。</p><pre>// sequelize config<br>module.exports = {<br>  &quot;development&quot;: {<br>    &quot;username&quot;: process.env.MYSQL_USER,<br>    &quot;password&quot;: process.env.MYSQL_KEY,<br>    &quot;database&quot;: process.env.MYSQL_DATABASE,<br>    &quot;host&quot;: process.env.MYSQL_HOST, // 設為 localhost 或 127.0.0.1<br>    &quot;port&quot;: 13306, // 我的 3306 有被占用, 所以改 13306<br>    &quot;dialect&quot;: &quot;mysql&quot;,<br>    // ...<br>  },<br>  // ...<br>}</pre><p>改完之後，就直接在本地專案跑 migrate 跟 seed 就好了。跑完之後可以用 GUI 確認資料有沒有都上去了。</p><pre># mysql<br>$ sequelize db:migrate<br>$ sequelize db:seed:all</pre><h3>修改專案 production DB 連線設定</h3><p>MySQL 資料都上去之後，得改一下專案 sequelize production 的設定。</p><p>原本是 Heroku 的話，因為 Heroku 的 DB 會直接給一串包含許多訊息的 URI。所以 ORM 的 config 可能會這樣寫。</p><pre>// sequelize config<br>module.exports = {<br>  // ...<br>  &quot;production&quot;: {<br>    &quot;use_env_variable&quot;: &quot;JAWSDB_URL&quot;, // 自己加的 prop, value 是環境變數 name<br>    &quot;dialect&quot;: &quot;mysql&quot;,<br>    // ...<br>  }<br>}<br><br>// invoke<br>const env = process.env.NODE_ENV || &#39;development&#39;<br>const config = require(./config.js&#39;)[env]<br>const DB_HOST = process.env[config.use_env_variable]<br><br>const sequelize = new Sequelize(DB_HOST, config)</pre><p>這一段有點繞，反正就是指定說 production 的時候，MySQL 的 host 位置從環境變數 process.env.JAWSDB_URL 來拿取。JawsDB 是 Heroku 提供的其中一種 MySQL DB。這個環境變數可以自己隨便命名。</p><p>而 Fly.io 要在容器裡連接 MySQL App，不是用 URI 的方式，而是直接在 app name 屁股加一個尾綴 [mysql_app_name].internal。</p><p>所以 sequelize config 要改回一般的設定方式。</p><pre>// sequelize config<br>module.exports = {<br>  // ...<br>  &quot;production&quot;: {<br>    &quot;username&quot;: process.env.MYSQL_USER,<br>    &quot;password&quot;: process.env.MYSQL_KEY,<br>    &quot;database&quot;: process.env.MYSQL_DATABASE,<br>    &quot;host&quot;: process.env.MYSQL_HOST, // 這邊最後要拿到 &quot;my-mysql.internal&quot;<br>    &quot;dialect&quot;: &quot;mysql&quot;,<br>    // ...<br>  },<br>}</pre><p>改完之後，把網站的 App 給 deploy 上去，應該就可以在 Server 上連線到 MySQL 了。</p><p>參考:</p><p><a href="https://dev.to/zsevic/deploying-nodejs-apps-to-flyio-jl2">Deploying Node.js apps to Fly.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f9f5cdb837b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codememo/%E7%AD%86%E8%A8%98-%E5%BE%9E-heroku-%E9%81%B7%E7%A7%BB%E8%87%B3-fly-io-5f9f5cdb837b">從 Heroku 遷移至 Fly.io</a> was originally published in <a href="https://medium.com/codememo">Code 隨筆放置場</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue2 + ant-design jsx 使用案例]]></title>
            <link>https://medium.com/codememo/vue2-ant-design-jsx-%E4%BD%BF%E7%94%A8%E6%A1%88%E4%BE%8B-f0e9a24f3792?source=rss-34af170eeca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0e9a24f3792</guid>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[jsx]]></category>
            <category><![CDATA[ant-design]]></category>
            <category><![CDATA[心得]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Lastor]]></dc:creator>
            <pubDate>Sun, 16 Jul 2023 09:20:02 GMT</pubDate>
            <atom:updated>2023-07-16T10:01:11.925Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4gO7MIrYD7940BaBn1C_Q.png" /></figure><p>這篇文章大概分兩段，一個是標題的 Vue 裡面使用 jsx 會更優的案例分享。另一個是，我試著用 stackblitz codeflow 做 demo 時碰到的一些 vite + vue2 + ts + babel 相關坑點。</p><p>以前稍微研究過在 Vue 裡面使用 jsx。但始終好奇到底有甚麼樣的場景會迫切的需要 jsx，最近總算給我遇到了一個用 jsx 會更好處理的情境。</p><p>先上完成的 demo code，裡面有 ant-design-vue Tabale 使用 template API 與 columns config + jsx 兩種寫法的範例。</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fvitejs-vite-tkbt3r%3Fctl%3D1%26embed%3D1%26file%3Dsrc%252Fcomponents%252FColumns.vue&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fvitejs-vite-tkbt3r%3Fctl%3D1%26embed%3D1%26file%3Dsrc%252Fcomponents%252FColumns.vue&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fvitejs-vite-tkbt3r%2F0a42a3bd9817402422685690bbed89c3&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1f7adf83af3f06e46af122d6c381e6b/href">https://medium.com/media/f1f7adf83af3f06e46af122d6c381e6b/href</a></iframe><h3>Ant Design 的 Table</h3><p>antd 的 Table 組件有兩種設定表單 columns 的方式，一種是直接寫 html 的 template API，另一種是寫 object 的 columns config。</p><p>例如我有一組這樣的 data，要用 table 列出 ID 與 Name 欄位。</p><pre>const tableData = [<br>  { id: 1, name: &#39;productA&#39; },<br>  // ...<br>]</pre><p>用 columns 設定是這種感覺。其中，可以透過 scopedSlots 去定義 Vue 的插槽。</p><pre>&lt;script&gt;<br>const columns = [<br>  {<br>    title: &#39;ID&#39;, // thead 欄位 title<br>    dataIndex: &#39;id&#39;, // 對應 data 裡 object 的 key name<br>  },<br>  {<br>    title: &#39;Name&#39;,<br>    dataIndex: &#39;name&#39;,<br>    scopedSlots: { customRender: &#39;name&#39; }, // 定義 slot name<br>  }<br>]<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;a-table :columns=&quot;columns&quot; :data-source=&quot;tableData&quot; row-key=&quot;id&quot;&gt;<br>    &lt;!-- 可以用定義好的 slot name 去控制該欄位要 render 的內容 --&gt;<br>    &lt;template #name=&quot;val&quot;&gt;<br>      &lt;span&gt;{{ val }}&lt;/span&gt;<br>    &lt;/template&gt;<br>  &lt;/a-table&gt;<br>&lt;/template&gt;</pre><p>而 template API 則是 columns config 的語法糖，可以直接在 html 寫設定。</p><pre>&lt;a-table :data-source=&quot;tableData&quot; row-key=&quot;id&quot;&gt;<br>  &lt;a-table-column data-index=&quot;id&quot; title=&quot;ID&quot; /&gt;<br>  &lt;a-table-column data-index=&quot;name&quot; title=&quot;Name&quot;&gt;<br>    &lt;template #default=&quot;val&quot;&gt;<br>      &lt;span&gt;{{ val }}&lt;/span&gt;<br>    &lt;/template&gt;<br>  &lt;/a-table-column&gt;<br>&lt;/a-table&gt;</pre><p>這邊其實就體現出了一個差異，使用 columns 設定時，如果想要在 &lt;template&gt; 去自訂 render，就必須要定義一個 slot name 才能讓 antd 知道這段 html 對應的是哪個欄位。</p><p>但是用 template API 的時候，由於是包在 &lt;a-table-column&gt; 裡面，直接就能對應到目標欄位，所以不需要定義 slot name，直接用 default 就可以了。</p><p>這會在處理動態欄位時出現顯著的差異。</p><h3>動態欄位處理</h3><p>假設現在要做一張這樣的 table。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*fdr7OzqBb4FG9aT96qXMLg.png" /></figure><p>右段會顯示不同 product 每個月份的收入與支出。而月份的 data 數量是不固定的，每個 product 有的月份資料也會不一樣，例如有的有 1 月，有的卻沒有。</p><p>tableData 大概會是這樣：</p><pre>const tableData = [<br>  {<br>    id: 1,<br>    name: &#39;productA&#39;,<br>    monthDetail: {<br>      &#39;2023-01&#39;: { cost: 50, income: 100 },<br>      &#39;2023-02&#39;: { cost: 100, income: 150 },<br>      // ...<br>    },<br>  },<br>  // ...<br>]<br><br>// 從 data 整理出來的不重複月份 list<br>const months = [&#39;2023-01&#39;, &#39;2023-02&#39;, ...]</pre><p>ps. 這邊直覺可能會認為 monthDetail 應該是 array，但用 object 後面欄位設定會比較好抓值。</p><p>勢必月份的地方要跑迴圈來做，這時候用 template API 是很容易的。直接打一個 v-for 就能一次處理 Cost 與 Income、甚至更多欄位。<br>(以下省略上圖中的月份 ColumnGroup)</p><pre>&lt;a-table :data-source=&quot;tableData&quot; row-key=&quot;id&quot;&gt;<br>  &lt;template v-for=&quot;month in months&quot;&gt;<br>    &lt;!-- Cost 欄位 --&gt;<br>    &lt;a-table-column<br>      :key=&quot;`${month}_cost`&quot;<br>      :data-index=&quot;`monthDetail.${month}.cost`&quot;<br>      title=&quot;Cost&quot;<br>    &gt;<br>      &lt;template #default=&quot;val&quot;&gt;{{ val }}&lt;/template&gt;<br>    &lt;/a-table-column&gt;<br><br>    &lt;!-- 其他 n 個欄位... --&gt;<br>  &lt;/template&gt;<br>&lt;/a-table&gt;</pre><p>但如果是用 columns config 就會碰到問題，寫下去會發現 slot name 也是動態產生的，那要寫 slot 時就會卡住。</p><pre>&lt;script&gt;<br>const columns = [<br>  { title: &#39;ID&#39;, ... },<br>  { title: &#39;Name&#39;, ... },<br>  // 迴圈生成月份欄位<br>  ...months.map((month) =&gt; (<br>    {<br>      title: &#39;Cost&#39;,<br>      dataIndex: `monthDetail.${month}.cost`,<br>      scopedSlots: {<br>        customRender: `${month}_cost`, // slot name 也變動態的<br>      },<br>    }<br>    // ...<br>  ))<br>]<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;a-table :columns=&quot;columns&quot; :data-source=&quot;tableData&quot; row-key=&quot;id&quot;&gt;<br>    &lt;!-- 取不到 slot name --&gt;<br>    &lt;template #???=&quot;val&quot;&gt;...&lt;/template&gt;<br>  &lt;/a-table&gt;<br>&lt;/template&gt;</pre><p>slot 的機制與前面 template API 不同，帶有 slot 的 html 一定要在 a-table 底下的第一層。所以沒辦法只包一層 template v-for，就生成所有欄位。</p><pre>&lt;!-- NG --&gt;<br><br>&lt;a-table :columns=&quot;columns&quot; :data-source=&quot;tableData&quot; row-key=&quot;id&quot;&gt;<br>  &lt;template v-for=&quot;month in months&quot;&gt;<br>    &lt;!-- slot 被包在裡面, Vue 會抓不到 --&gt;<br>    &lt;template :key=&quot;`${month}_cost`&quot; #[`${month}_cost`]=&quot;val&quot;&gt;<br>      &lt;span&gt;{{ val }}&lt;/span&gt;<br>    &lt;/template&gt;<br><br>    &lt;!-- 其他欄位... --&gt;<br>  &lt;/template&gt;<br>&lt;/a-table&gt;</pre><p>所以這種情況，如果要用 slot 自訂 render 的話，就會被迫有幾欄就得寫幾個 v-for，相當的不理想。</p><pre>&lt;a-table :columns=&quot;columns&quot; :data-source=&quot;tableData&quot; row-key=&quot;id&quot;&gt;<br>  &lt;!-- 得把 v-for 與 slot 寫在同一層 --&gt;<br>  &lt;template v-for=&quot;month in months&quot; #[`${month}_cost`]=&quot;val&quot;&gt;<br>    &lt;span :key=&quot;month&quot;&gt;{{ val }}&lt;/span&gt;<br>  &lt;/template&gt;<br><br>  &lt;!-- v-for 欄位B --&gt;<br>  &lt;!-- v-for 欄位C --&gt;<br>  &lt;!-- v-for ...  --&gt;<br>&lt;/a-table&gt;</pre><p>而這就是 jsx 出場的時候了，columns config 裡面是可以不定義 slot 直接寫 customRender 的。</p><pre>const columns = [<br>  // ...<br>  ...months.map((month) =&gt; (<br>    {<br>      title: &#39;Cost&#39;,<br>      dataIndex: `monthDetail.${month}.cost`,<br>      // 直接用 jsx 去寫原本要寫在 slot 的內容<br>      customRender: (val, row) =&gt; {<br>        return &lt;span&gt;{ val }&lt;/span&gt;<br>      },<br>    },<br>  )),<br>]</pre><p>這種情況就充分體現出了使用 jsx 的好處，直接在 columns 設定的迴圈之中一次解決，就不會被迫多寫一堆 v-for 了。</p><h3>專案架設撞坑篇</h3><p>接下來是第二部分，主要是紀錄在 stackblitz codeflow 做 demo 時碰到的坑。</p><p>stackblitz codeflow 這個 Web IDE 有興趣的可以去玩玩，基本免費。這跟 codeSandbox 那類平台比起來，速度明顯快到飛起。</p><p>可以直接在 Web 上模擬終端機操作，直接執行 npm install、npm run dev 等各種操作、安裝套件、運行 Node，甚至可以直接開啟 GitHub 上的公開 repo 來運行。</p><p>但畢竟是在瀏覽器上虛擬環境，終究還是有些地方沒辦法很完美。</p><h4>typescript 支援性問題</h4><p>ts 專案很容易會有 editor 抓不到 package 的 type 定義的問題，即使用平台預設的 ts 專案也會有這問題。但是他只是 editor 會跳紅線，並不影響專案執行，就是會看得很難受。</p><p>由於 package 的型別定義檔抓不到，缺少套件的智能提示，其實很大程度也就失去使用 ts 的意義了。</p><p>研究了老半天，發現是 typescript config 有問題，可以在本機上起個 vite-ts 專案，然後把 vite 預設的 ts config 複製過去即可以解決。</p><p>最關鍵的是 moduleResolution 這個設定，stackblitz 預設的是 Bundler 將其改成 Node 就可以了。注意，不要用 NodeNext。</p><pre>{<br>  &quot;moduleResolution&quot;: &quot;Node&quot;,<br>}</pre><p>但是!! Vue SFCs 是依賴 Volar 這個編輯器套件去做 ts check 的，可是 stackblitz 的編輯器是沒法手動去裝 Volar 的，因此所有的 .vue file 都是無法偵測 type 並且沒有智能提示的。</p><p>所以最終我還是選擇用 js 就好……</p><h4>vite 無法直接使用 webpack 的 babel plugins</h4><p>由於前面的案例我是在公司的 Vue2 webpack 老專案碰到的，為了模擬環境，所以我起的是一個素的 vite 專案，自己去裝 Vue2 環境。</p><p>vite 官方有做 Vue2 的插件 @vitejs/plugin-vue2，所以問題不大。但是 jsx 以及 antd Vue2 版本的按需加載都是需要用到 babel 的。</p><p>目前去查這方面相關的 bable 插件，基本都是 for webpack 的，vite 無法直接用。嘗試用了一些 vite-plugin-babel 之類的玩意，也都不 work。</p><p>後來發現 webpack 使用的那些 babel plugins，在搜尋的時候前面加個 vite 關鍵字，就能找到包裝成 vite plugins 的版本。但由於是 Vue2 相關的插件，很多都比較舊沒有再維護了。</p><p>但這方面的問題是因為我要在 vite 上面裝舊的 Vue2 相關環境才會碰到，畢竟 vite 基本是 for Vue3 體系的，使用 Vue3 的話就不太會有這方面的問題。</p><p>Vue2 還是用 webpack 的 vue-cli 會比較完善。雖然現在起新的 Vue 專案根本不會用 vue-cli 跟 Vue2 了。 (笑)</p><p>vite 官方有個頁面，有列出幾個比較重要的，由官方維護的插件。包含 Vue2、Vue3 的 plugin，以及這兩個版本的 jsx plugin。</p><p><a href="https://cn.vitejs.dev/plugins/">Vite</a></p><h4>Vue2 使用 jsx</h4><p>要在 Vue2 要使用 jsx，打包工具是 webpack 還是 vite 會有比較大的差異。現在最新的 vue-cli 除了內建 composition-api 與 &lt;script setup&gt; 語法糖之外，jsx 的配置也是開箱即用的。</p><p>但是 Vue2 的老專案，可能不是用最新的 vue-cli 起的，多半還是得自己裝。webpack 的情況下，以前查過一次，稍微有點忘了。隱約記得 Vue + jsx 相關的 babel 插件有新版跟舊版的。</p><p>新版的可以直接在 setup 裡面寫 jsx，但舊版的限定只能寫在 Vue 的 render function 裡面。</p><p><a href="https://github.com/vuejs/jsx-vue2">GitHub - vuejs/jsx-vue2: monorepo for Babel / Vue JSX related packages</a></p><p>如果是老 Vue2 專案，途中才添加 jsx 配置的話，多半既有 code 都不是用 render function 去寫 html 的，jsx 會很難加上去。像上述 antd Table 的 columns 設定，根本沒辦法直接在 customRender() 裡面寫 jsx。</p><p>關於這問題我也是卡關卡了很久，後來去翻這個 babel jsx 插件的 GitHub 才注意到，他除了 render function 之外，也可以寫在 methods 上面。所以只要轉一手就可以了。</p><pre>defineComponent({<br>  computed: {<br>    columns() {<br>      return [<br>        // ...<br>        ...months.map((month) =&gt; (<br>          {<br>            title: &#39;Cost&#39;,<br>            dataIndex: `monthDetail.${month}.cost`,<br>            customRender: (val, row) =&gt; {<br>              return this.MyJsx({ val }) // 透過 methods 過一手<br>            },<br>          },<br>        )),<br>      ]<br>    },<br>  },<br>  methods: {<br>    MyJsx(props) {<br>      return &lt;span&gt;{props.val}&lt;/span&gt;<br>    },<br>  }<br>})</pre><p>如果是 vite 環境的話，官方有直接提供 Vue2 的 jsx 插件。這個插件對應的是 Vue2.7，所以是可以直接寫在 setup 上面的。</p><p>(Vue2.7 整合了 composition-api 以及 setup 語法糖)</p><p><a href="https://github.com/vitejs/vite-plugin-vue2-jsx">GitHub - vitejs/vite-plugin-vue2-jsx: Vite plugin for Vue 2.7 JSX support</a></p><h4>ant-design-vue 與 unplugin-vue-components 自動按需加載</h4><p>其實不想搞 babel 的話，手動按需加載也可以。官方文件有相關說明，antd 原本就有拆模塊，只要個別 import 需要的就好。但他麻煩就在 style 也要手動引入。</p><pre>import Button from &#39;ant-design-vue/lib/button&#39;<br>import &#39;ant-design-vue/lib/button/style&#39;</pre><p>而自動按需加載主要就是簡化這個操作，讓 style 可以自動引入，就不用寫到手斷掉。</p><p>老版本的文件上，都是推薦使用 babel-plugin-import 來做自動化。</p><p><a href="https://github.com/umijs/babel-plugin-import">GitHub - umijs/babel-plugin-import: Modularly import plugin for babel.</a></p><p>可是這玩意是 for webpack 的，vite 我研究了老半天，始終不 work。後來發現新版本文件，有寫說 vite 可使用 unplugin-vue-components 。</p><p><a href="https://github.com/antfu/unplugin-vue-components/tree/main">GitHub - antfu/unplugin-vue-components: 📲 On-demand components auto importing for Vue</a></p><p>這玩意似乎是讓各大 UI 庫使用按需加載的集成，概念上也只是幫你自動化。例如設定了 ant-design-vue 解析之後，他會偵測你的 template 裡面寫的 關鍵字時，有出現 antd 組件的名稱時，自動幫你 import 該組件以及 style。</p><pre>// 偵測到 antd 組件的關鍵字 a-xxx<br>&lt;a-button&gt;Click&lt;/a-button&gt;<br><br>// 自動補 import 並註冊到組件上<br>import { Button } from &#39;ant-design-vue&#39;<br>import &#39;ant-design-vue/es/date-picker/style/css&#39;<br><br>export default defineComponent({<br>  components: {<br>    AButton: Button,<br>  }<br>})</pre><p>這個是我撞到一個坑之後，去讀這插件的文檔，研究了好陣子才理解到原來是這樣 work 的。這個坑後面再細說。</p><p>由於他是這樣的註冊方式，按照 Vue 的規則，其實寫 &lt;AButton&gt; 也是可以的。</p><p>因為這玩意跟 babel 一樣，只是分析 code 去做編譯轉換，所以 antd 無論是用哪個版本，只要他的命名規則沒有變，那應該都是可以用這個插件的。</p><p>實際測試之後，antd-vue v1 也可以用 unplugin-vue-components 。而隔壁棚的 element-plus，在按需加載的部分也是推薦使用這個插件。</p><p>要注意的是，如果你手動去寫了 import 並註冊到組件上，那編譯轉換就不會執行，也就不會自動拉 style 了。</p><h4>a-table-column 按需加載的坑</h4><p>這個坑真的折騰了我很多時間才搞明白是怎麼回事。上面說明的 unplugin-vue-components 的運作方式，會跟這個 columns 語法糖起衝突。</p><p>在寫 a-table 使用 template API 時，會直接報錯。</p><pre>&lt;a-table ...&gt;<br>  &lt;a-table-column ... /&gt;<br>&lt;/a-table&gt;<br><br>// Error:<br>// The requested module &#39;/node_modules/.../ant-design-vue_es.js&#39;<br>// does not provide an export named &#39;TableColumn&#39;</pre><p>為什麼呢? 看這錯誤訊息，vite 在 antd 裡面，找不到叫做 TableColumn 的 module 有被 export 出來。</p><p>也就是說，編譯之後高概率是這樣寫 import 的。</p><pre>import { TableColumn } from &#39;ant-design-vue&#39;</pre><p>然後，去爬 antd 的文件在 <a href="https://next.antdv.com/docs/vue/getting-started">Get Started</a> 的地方舉了一個 Button 跟 ButtonGroup 的例子，他是這樣寫的啊!! 這個 ButtonGroup 不是一個獨立 export 出來的組件!!</p><pre>import { Button } from &#39;ant-design-vue&#39;<br>const ButtonGroup = Button.Group<br><br>export default {<br>  components: {<br>    AButton: Button,<br>    AButtonGroup: ButtonGroup,<br>  },<br>}<br></pre><p>實際去找 TableColumn 這個組件，果然發現他跟 ButtonGroup 一樣，只是底下的的一個屬性。</p><pre>// export 裡面不存在單獨的 TableColumn<br>import { Table } from &#39;ant-design-vue&#39;<br>const TableColumn = Table.Column</pre><p>因為這算是特規了，跟其他組件都不一樣，所以 unplugin-vue-components 寫好的編譯規則直接在這就掛了……</p><p>如果希望繼續使用 unplugin-vue-components 自動按需加載，又想使用這類特殊的 antd 子組件，該怎麼辦呢?</p><p>研究了好久才發現，我們可以這樣寫:</p><pre>&lt;script&gt;<br>import { Table } from &#39;ant-design-vue&#39;<br>export default {<br>  components: {<br>    Column: Table.Column, // 不要取名為 ATableColumn<br>  },<br>}<br>&lt;/script&gt;<br><br>&lt;script setup&gt;<br>import { ref, computed } from &#39;vue&#39;<br>// ...<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;a-table ...&gt;<br>      &lt;!-- 使用自定義的組件名 --&gt;<br>      &lt;Column ... /&gt;<br>    &lt;/a-table&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><p>概念上是把 a-table-column 的部分手動註冊，然後換個名字去規避 unplugin 的偵測。這樣 a-table-column 就不會被編譯出錯誤的 import 內容。</p><p>然後 a-table 的部分照舊，讓 unplugin 去自動註冊組件。由於 Column 是隸屬在 Table 底下的，所以是吃同一份 style。而這份 style 會在 a-table 的部分被自動載入進來。</p><p>如此，就成功解決了這該死的坑。 (灑花)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0e9a24f3792" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codememo/vue2-ant-design-jsx-%E4%BD%BF%E7%94%A8%E6%A1%88%E4%BE%8B-f0e9a24f3792">Vue2 + ant-design jsx 使用案例</a> was originally published in <a href="https://medium.com/codememo">Code 隨筆放置場</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>