<?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 nchuuu on Medium]]></title>
        <description><![CDATA[Stories by nchuuu on Medium]]></description>
        <link>https://medium.com/@nchuuu?source=rss-1be9955f20ed------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7nUmRJdj-TkvN0Q-HVQ5hw.png</url>
            <title>Stories by nchuuu on Medium</title>
            <link>https://medium.com/@nchuuu?source=rss-1be9955f20ed------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 11:38:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nchuuu/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[一言不合就改用 gRPC？要我大前端怎麼配合啊！]]></title>
            <link>https://medium.com/@nchuuu/%E4%B8%80%E8%A8%80%E4%B8%8D%E5%90%88%E5%B0%B1%E6%94%B9%E7%94%A8-grpc-%E8%A6%81%E6%88%91%E5%A4%A7%E5%89%8D%E7%AB%AF%E6%80%8E%E9%BA%BC%E9%85%8D%E5%90%88%E5%95%8A-b88e5b1265d3?source=rss-1be9955f20ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/b88e5b1265d3</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[grpc-web]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[nchuuu]]></dc:creator>
            <pubDate>Fri, 08 Nov 2019 09:28:19 GMT</pubDate>
            <atom:updated>2019-12-16T01:29:18.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zWd5JJJsbwjlLzBEnHGqUw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@hhh13?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">FuYong Hua</a> on <a href="https://unsplash.com/s/photos/angry?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>— grpc-web 串接步驟及開發經驗分享。</p><h3>前言</h3><p>前陣子因為外包團隊開發的 WebSocket 極度不穩定，主管決定在內部先嘗試將服務替換為 grpc 的解決方案。身為前端工程師的我，本來也很期待這次的技術嘗試，grpc 又是 Google 所主持的 Project，開發體驗及可靠性應該很高吧！然而實際串接後，我有了不一樣的想法…。我們還是先從技術的部分開始吧！</p><h3>gRPC</h3><blockquote>gRPC is a modern open source high performance RPC framework that can run in any environment.</blockquote><p>簡單來說 gRPC 是 Google 製作的 RPC 框架，與我們一般常串接的 REST API 有些差別。本篇將不細究其中差異，直接以前端的角度分享如何建立及串接 gRPC 服務。而我們建置的步驟主要依賴<a href="https://grpc.io/">官方文件</a>，以及針對 web 端開發的 <a href="https://github.com/grpc/grpc-web">grpc-web</a> 套件。</p><p>首先 gRPC 有個最重要的定義檔 .proto，它的功能類似於我們在使用 <strong>npm</strong> 進行套件管理的 package.json，也就是告訴 npm 該去下載什麼版本的套件；而 .proto 則是定義了你的 gRPC 會有什麼樣的功能，並透過 <strong>protocol buffer compiler</strong> (protoc)進行編譯為程式語言。</p><pre>message EchoRequest {<br>  string message = 1;<br>}<br><br>message EchoResponse {<br>  string message = 1;<br>}<br><br>service EchoService {<br>  rpc Echo(EchoRequest) returns (EchoResponse);<br>}</pre><p>上面的例子是一個呼叫訊息的 .proto ，這份檔案對前後端來說是共用的，後端要將 .proto 編譯為 Java, Golang, etc. 來提供服務；而前端當然是編譯成 Javascript ，再搭配 grpc-web 來串接囉。</p><p>不過定義檔多是靠後端提供，必竟他們才是服務的提供者，前端同學們只需要每天催他們，把 .proto 給我交出來啦！😆😆😆</p><h3>grpc-web</h3><p>有了上述的背景之後，我們就來看看<a href="https://github.com/grpc/grpc-web">文件</a>的說明吧。首先第一步當然就是安裝 grpc-web 套件在你的專案之中。以下提供官方範例的 package.json。</p><pre>{<br>  &quot;name&quot;: &quot;grpc-web-commonjs-example&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;google-protobuf&quot;: &quot;^3.6.1&quot;,<br>    &quot;grpc-web&quot;: &quot;^0.4.0&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;browserify&quot;: &quot;^16.2.2&quot;,<br>    &quot;webpack&quot;: &quot;^4.16.5&quot;,<br>    &quot;webpack-cli&quot;: &quot;^3.1.0&quot;<br>  }<br>}</pre><p>再來 .proto 是需要編譯的，故我們需要在系統層安裝一些 plug-in 讓我們能透過 terminal 下指令進行編譯。這些套件建議按照 grpc-web 的 <a href="https://github.com/grpc/grpc-web#code-generator-plugin">Readme</a> 安裝。</p><p><strong>(1) </strong><a href="https://github.com/protocolbuffers/protobuf/releases"><strong>protoc</strong></a><br>這是編譯 .proto 的核心工具，我們將 release 的檔案如 <a href="https://github.com/protocolbuffers/protobuf/releases/download/v3.10.1/protoc-3.10.1-osx-x86_64.zip">protoc-3.10.1-osx-x86_64.zip</a> 下載後進行二進制安裝。不過若是 Mac 的用戶，則推薦使用 Homebrew 安裝會比較簡單。</p><pre>brew install protobuf</pre><pre>// check if installed &amp; version<br>$ protoc --version</pre><p><strong>(2) </strong><a href="https://github.com/grpc/grpc-web/releases"><strong>protoc-gen-grpc-web</strong></a><br>這個套件可以幫助 protoc 編譯出 javascript。這邊比較方便的方式是將專案 clone 下來透過編譯安裝。</p><pre>git clone <a href="https://github.com/grpc/grpc-web.git">https://github.com/grpc/grpc-web.git</a></pre><pre>$ cd grpc-web<br>$ sudo make install-plugin</pre><p>準備好以上前置作業後，我們就可以在專案底下執行 protoc 指令，將 .proto 編譯出來並引用進我們的程式碼中。以下以 echo.proto 為例：</p><pre>$ protoc echo.proto \<br>--js_out=import_style=commonjs:$OUT_DIR \<br>--grpc-web_out=import_style=commonjs:$OUT_DIR</pre><p>$OUT_DIR 是輸出檔案的位置，可自訂路徑。指令執行完成後我們會得到 echo_pb.js echo_grpc_web_pb.js 兩支程式。接下來只要在我們的 javascript 引入即可使用囉。</p><p><strong>(3) 使用</strong><br>有了編譯完成的 js 後，我們該如何使用呢？參照<a href="https://grpc.io/docs/tutorials/basic/web/">官方文件</a>的範例，在需要串接 gRPC 的文件引入：</p><pre>const {EchoRequest, EchoResponse} = require(&#39;./echo_pb.js&#39;);<br>const {EchoServiceClient} = require(&#39;./echo_grpc_web_pb.js&#39;);</pre><pre>var echoService = new EchoServiceClient(&#39;<a href="http://localhost:8080&#39;">http://localhost:8080&#39;</a>);</pre><pre>var request = new EchoRequest();<br>request.setMessage(&#39;Hello World!&#39;);</pre><pre>echoService.echo(request, {}, function(err, response) {<br>  // ...<br>});</pre><p>呼叫連線的方法已經被包裝成 EchoServiceClient 這個 Class，給予連線的位址即可建立。而過去我們在 REST 架構下需要關注的 GET POST PUT DELETE 等 API 方法，在 gRPC 中也被包裝成 Fuction 來使用，而這些方法只要參照 .proto 檔就可以瞭解明確的定義。</p><h3>總結</h3><p>其實 gRPC 的應用通常是在處理微服務架構間的通訊，所以在後端的成熟度相對較高，以前端的角度來看會稍微有點門檻，因此下面會分享一些串接過程的負面感受 😅。</p><ol><li>環境建置成本較高。有別於過去我們只需要掌握 npm 管理套件，或 webpack 的打包設定，根據以上的步驟，相信大家也發現需要一些 compiler 套件的支援，在環境及開發上更為複雜。</li><li>gRPC 的連線於 web 的實作其實是靠 http/2 的協議達成的，雖然許多瀏覽器很早就支援，但 debug 工具卻不夠成熟(如 chrome dev tool 還沒辦法詳細檢視連線傳送的內容)，甚至需要安裝第三方 proxy 軟體攔截連線內容才能詳查。</li><li>因為前端打出的是 http/2 的連線，必須多使用一層 Proxy 來將內容轉成後端程式看得懂的 gRPC 連線。目前官方推薦 <a href="https://www.envoyproxy.io/"><strong>Envoy</strong></a> 來做 Server side Proxy，但這可能導致服務架構更複雜。<br>(可參考文章建置 Enovy Proxy：<a href="https://greddywork.gitlab.io/greddyblogs/2019/11/01/envoy/">https://greddywork.gitlab.io/greddyblogs/2019/11/01/envoy/</a>)</li><li>.proto 的共用雖然很方便前後端同步連線方法，但若有一個改動，就必須重新編譯，在開發的流程上容易造成混亂。</li></ol><p>基於以上的原因，個人其實還不建議基於 web 的服務使用 gRPC 來作為前後端的溝通；僅管很新很潮，傳輸穩定體積小，但若為了追求穩定又能保持一定的開發節奏，目前不成熟的環境似乎還不適合正式導入。</p><p>不過問題也是靠人解決的，若能將 .proto 的編譯導入 CI/CD ，從流程上下手，也許能夠更加優化 gRPC 的開發體驗。以後若有機會實作這一段，我會詳盡的記錄下來並分享給大家！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b88e5b1265d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linked list ES6 Javascript實作及Leet code題目解析]]></title>
            <link>https://medium.com/@nchuuu/linked-list-es6-javascript%E5%AF%A6%E4%BD%9C%E5%8F%8Aleet-code%E9%A1%8C%E7%9B%AE%E8%A7%A3%E6%9E%90-4afcd9a67b3d?source=rss-1be9955f20ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/4afcd9a67b3d</guid>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[singly-linked-list]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[nchuuu]]></dc:creator>
            <pubDate>Wed, 06 Nov 2019 17:36:34 GMT</pubDate>
            <atom:updated>2019-11-23T11:20:32.189Z</atom:updated>
            <content:encoded><![CDATA[<h3>Linked list Javascript實作及Leet code題目解析</h3><h3>開始之前</h3><p>因最近正在複習資料結構(基本上就是重新學習了吧😂)，希望能把一些比較重要的部分記錄下來，並在撰寫文章的過程中讓自己的記憶更加深刻。以下會盡量使用 ES6 的語法來創建資料結構的實例，當然也會有思慮不周的部分，還請大家多多留言指教！</p><h3>Intro</h3><p>Linked list 鏈結串列，是一種動態的資料結構，相對於 Array 陣列，不需連續的記憶體空間即可儲存，對於資料的操作成本較低；然而若欲取得其中某一節點 Node 上的資料，則必須從頭開始遍歷查找。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bL6wYMBSHIEZdXartATZPg.png" /><figcaption>A simple example of a linked list, <a href="https://medium.com/u/1be9955f20ed">nchuuu</a></figcaption></figure><h3>Practice</h3><p>由上圖可知，一個串列中存在多個 Node 結構，且 HEAD 會指向第一筆資料；而 Node 結構中由 Item 存儲資料，Next 負責指向下一筆 Node。故我們創建一個 Linked list 的 Class 思路為：</p><ol><li>鏈結串列有起始位置 head，亦即串列中第一筆 Node。</li><li>Node 節點以 item 存放資料。</li><li>Node 節點以 next 作為指標，指向下一個 Node。</li><li>為 List 加入一些參數如 length ，便於後續操作。</li></ol><p>節由以上整理我們可以先開始創建符合需求的 ES6 Class：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9c4dcde62e18e499a5c45bc83c328d4/href">https://medium.com/media/d9c4dcde62e18e499a5c45bc83c328d4/href</a></iframe><p>有了 Class 後必須有對應的方法來操作資料(ex: Array.push())，以下會依序實作(1)新增，(2)刪除，(3)插入。</p><p><strong>(1) 新增 (append)<br></strong>新增資料通常我們會串連至 Linked list 的尾部，也就是 append 一個節點。若為串列的第一筆資料，將串列的 head 指向新增的 Node 即可；其它則需透過遍歷找到尾部的 Node 再加入。故我們可以在 Linked list 中新增一個 method append：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51896e913286f3b30f5dfc7c4544aca4/href">https://medium.com/media/51896e913286f3b30f5dfc7c4544aca4/href</a></iframe><p>首先判斷是否為第一筆資料，將串列的 head 指向新增的 Node；若否則利用 while loop 判斷遍歷的節點找到最後一個 Node (也就是上例的tail)，再將其上的 next 欄位指向新的資料。另外也別忘記將 List 的長度往上加一(this.length++)。</p><p><strong>(2) 指定位置移除(removeAt)<br></strong>給定一個 index 移除資料，如同新增的步驟，先判斷移除的項目是否為第一筆，若是，則將 head 指向第二筆資料；若否，則遍歷找到該 index 下的 Node ，移除的操作即是將前一個節點之 next 欄位指向下一個節點。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24b83da1b754d24af50e722f7055a9d3/href">https://medium.com/media/24b83da1b754d24af50e722f7055a9d3/href</a></iframe><p>removeAt 的 method 如上例，需注意的是 current 及 prev 兩個變數的使用；透過他們我們可以對遍歷到的節點進行暫存，到達指定 index 時將 next 的指向置換即可。操作的結果如下：</p><pre>// a new linked list<br>let ln = new LinkedList(); </pre><pre>// append items<br>ln.append(&#39;1&#39;);<br>ln.append(&quot;2&quot;);<br>ln.append(&quot;3&quot;);</pre><pre>// remove item in index 1<br>ln.removeAt(1);</pre><pre>// out print of ln<br>{ <br>  &quot;length&quot;:2,<br>  &quot;head&quot;: {<br>      &quot;item&quot;:&quot;1&quot;,<br>      &quot;next&quot;:{<br>          &quot;item&quot;:&quot;3&quot;,<br>          &quot;next&quot;:null<br>      }<br>   }<br>}</pre><p><strong>(3) 指定位置插入(insert)<br></strong>插入的操作同樣和刪除很像，除了判斷是否為第一筆外，透過遍歷找到我們給定的 index 位置，並利用 prev current 等變數輔助，改變 next 指向就好囉。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d162569bc4857ad5cbdb1bac37cff7e/href">https://medium.com/media/7d162569bc4857ad5cbdb1bac37cff7e/href</a></iframe><h3>Leet code</h3><blockquote>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The digits are stored in <strong>reverse order</strong> and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.</blockquote><p>在 Leet code <strong>(</strong><a href="https://leetcode.com/problems/add-two-numbers/"><strong>2) Add Two Numbers</strong></a><strong> </strong>中，題目給予兩個不為空的串列，分別代表兩個非負整數，其數字的“<strong>位數</strong>”是反向儲存的 (2→ 4→ 3, 代表342)。最後將兩個串列中數值相加後，以同樣的型式回傳這個串列(其實這個reverse order個人覺得挺陷阱的😂，畢竟我們在處理時只要按照同樣的順序處理，也不太需要擔心👍)。</p><pre><strong>Example:</strong></pre><pre><strong>Input:</strong> (2 -&gt; 4 -&gt; 3) + (5 -&gt; 6 -&gt; 4)<br><strong>Output:</strong> 7 -&gt; 0 -&gt; 8<br><strong>Explanation:</strong> 342 + 465 = 807.</pre><p>這邊解題的思路為：</p><ol><li><strong>遍歷</strong>兩個 Input，每個位數互相加總。</li><li>注意是否有<strong>進位</strong>，需在下一筆資料加上。</li><li>兩個 input 有可能長度不同 (ex: 123, 45)，只要還遍歷的到任一 Input 存在就必須進行加總(ex: 1+4, 2+5, 3+0)。</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ff3008a3418383c07e34af7c8b108ab/href">https://medium.com/media/6ff3008a3418383c07e34af7c8b108ab/href</a></iframe><p>以上文章簡略以 ES6 Class 實作了 Linked list 物件，除了上述的方法，我們也可以增加如 getAt 或 indexOf(以節點上的資料找尋其index位置)等實用的擴充。我個人的leet code解題實例也以 Gist 附上，希望能對大家有幫助，若有任何問題也歡迎留言討論哦！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4afcd9a67b3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create components with native HTML tags’ attributes manually by using “inheritAttrs” in Vue 2.4.0+]]></title>
            <link>https://medium.com/@nchuuu/create-components-with-native-html-tags-attributes-manually-by-using-inheritattrs-in-vue-2-4-0-bbc4de37fdd8?source=rss-1be9955f20ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbc4de37fdd8</guid>
            <category><![CDATA[attributes]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vue]]></category>
            <dc:creator><![CDATA[nchuuu]]></dc:creator>
            <pubDate>Mon, 04 Nov 2019 07:06:38 GMT</pubDate>
            <atom:updated>2019-11-05T17:11:41.767Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create components with native HTML tags’ attributes by using “inheritAttrs” in Vue 2.4.0+</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aDSI0cZ3KVCzKtoIDAXwaA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@codestorm?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Safar Safarov</a> on <a href="https://unsplash.com/s/photos/code?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Scenario</h3><p>When we want to pass some custom values to other components in Vue, passing “props” would be the first chose. However, when it comes to common attributes in HTML tags like autocomplete, maxlength, etc. We also want a “native HTML like” coding experience.</p><p>For example, we create a CustomInput component which contains an input wrapped by a div with a class for styling.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/248cc38120f5d138bb72a4c5066ece9f/href">https://medium.com/media/248cc38120f5d138bb72a4c5066ece9f/href</a></iframe><p>What we want to do is that passing down attributes from parent component to CustomInput <strong>without</strong> using props.</p><h3>Practice</h3><p>By default, when attributes are passed down to a child component, the root HTML tag in child component will inherit those attributes.</p><pre>// the output HTML from the above example</pre><pre>&lt;div class=&quot;wrapper&quot;&gt;<br>    &lt;div class=&quot;myClass&quot; maxlength=&quot;5&quot; autocomplete=&quot;hello&quot;&gt;<br>        &lt;input /&gt;<br>    &lt;div/&gt;<br>&lt;div/&gt;</pre><p>However, what we expected is that attributes can be inherited by &lt;input/&gt;. Since <strong>Vue 2.4.0</strong>, there’s an option called “inheritAttrs”. <br>By setting this option inheritAttrs: false , the default action will not be executed. <br>Finaly, we can use v-bind &amp;$attrs to setup the attributes manually.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c33f8cf5e8a73fe561c0ab920a7ddb2/href">https://medium.com/media/7c33f8cf5e8a73fe561c0ab920a7ddb2/href</a></iframe><p>Besides of “Destructuring Assignment” within the $attr object and attaching it by usingv-bind , we can also replace the attribute’s value to undefined and manipulate it by ourself in data option for other usage.</p><p>It’s only a little trick for building custom components. Hope you are enjoy the article, and keep following me for the next sharing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbc4de37fdd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[超淺談 Vue 的響應式原理]]></title>
            <link>https://medium.com/@nchuuu/%E8%B6%85%E6%B7%BA%E8%AB%87-vue-%E7%9A%84%E9%9F%BF%E6%87%89%E5%BC%8F%E5%8E%9F%E7%90%86-4aa53994be22?source=rss-1be9955f20ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/4aa53994be22</guid>
            <category><![CDATA[響應式原理]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[nchuuu]]></dc:creator>
            <pubDate>Fri, 01 Nov 2019 06:40:25 GMT</pubDate>
            <atom:updated>2019-11-01T06:44:36.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eh1ju0aZiQP5Q6UJ-KdevQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@clemhlrdt?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Clément H</a> on <a href="https://unsplash.com/s/photos/code?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>— Object.defineProperty, and some notes.</p><p>Vue 組件在初始化時會將 props, data…等屬性進行綁定，並監聽他們的變化，而後在該值對應的模板上執行渲染。比如：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e63312d410908b1d7ea7bef304afd92/href">https://medium.com/media/5e63312d410908b1d7ea7bef304afd92/href</a></iframe><p>其實 Vue 是利用了ES5標準下的 <a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a> 來將 props, data… 轉變為響應式物件的。</p><pre>Object.defineProperty(object, prop, descriptor)</pre><p>其中 descriptor 的部分可以為 object 中的 prop 提供 get(getter), set(setter)的屬性方法，用於取值及賦值時的操作：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cb661afbeafb1d99e032488db21bcb0/href">https://medium.com/media/9cb661afbeafb1d99e032488db21bcb0/href</a></iframe><pre>obj.a<br>// gotcha!<br>// 10</pre><pre>obj.a = 12;<br>obj.a<br>// gotcha!<br>// 13</pre><p>以上是對範例中 obj 簡單操作的結果，透過 setter 及 getter 我們可以在取賦值時增加一些額外的操作。熟悉 Vue 開發的人應該也不難發現，這樣的操作其實跟 Vue 的 computed getter/setter <a href="https://vuejs.org/v2/guide/computed.html#Computed-Setter">寫法</a>是異曲同工的。</p><p>瞭解上述的方法後，就來看看 Vue 的原始碼中是如何將物件轉換成響應式對象的吧！我們可以從 <a href="https://github.com/vuejs/vue/tree/2.6/src">GitHub 上找到 Vue</a>，而相關檔案都會在 src/ 路徑底下。</p><p>首先來了解一下 Vue 程式的初始化流程，通常我們會在 index.js 中執行 new Vue() ，這個步驟藉由一個 Vue 的 Class 創建出 Vue 的 instance，並執行 this._init() 這個 Function。於 src/core/instance/index.js 中可以找到它：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/734cde8d7340a2f579c622eb89dc764f/href">https://medium.com/media/734cde8d7340a2f579c622eb89dc764f/href</a></iframe><p>而 _init 會處理 Vue 的生命週期、事件、data、props 等初始化的設定，相關原始碼在 src/core/instance/init.js 。其中將資料物件轉變為響應式的關鍵涵式為 initState() ，由 src/core/instance/state.js 中可以他執行了多個初始化的動作，包含 initProps initData initComputed 等等。</p><p>這次我們先專注initProps ，他在遍歷了所有的 props 後執行了涵式defineReactive ，下面節錄原始碼中比較重要的部分：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67345d19212659f77d524b26f8fd92e4/href">https://medium.com/media/67345d19212659f77d524b26f8fd92e4/href</a></iframe><p>到了這裡，總算可以在 src/core/observer/index.js 中看到 defineReactive 實際使用了 Object.defineProperty 對傳入的參數進行 getter/setter 的設置：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71c5228db5bc71b7157571b2abaa8429/href">https://medium.com/media/71c5228db5bc71b7157571b2abaa8429/href</a></iframe><p>探究原始碼的過程著實令人心累，且 vue 3.0 推出在即，但已趨成熟的 Vue 2真的很適合拿來研讀，在其中也能夠發現許多有趣的方法，以及恍然大悟的心情，甚至能夠讓自己寫 code 的能力加以提升！這次只關注在響應式的入門，有機會再來一一探索如 virtul dom 等核心的部分吧。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4aa53994be22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[利用Vue-CLI 進行多頁打包]]></title>
            <link>https://medium.com/@nchuuu/%E5%88%A9%E7%94%A8vue-cli-%E9%80%B2%E8%A1%8C%E5%A4%9A%E9%A0%81%E6%89%93%E5%8C%85-633b39bb157?source=rss-1be9955f20ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/633b39bb157</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[multiple-page]]></category>
            <category><![CDATA[vue-cli]]></category>
            <dc:creator><![CDATA[nchuuu]]></dc:creator>
            <pubDate>Wed, 30 Oct 2019 10:38:29 GMT</pubDate>
            <atom:updated>2019-11-01T08:47:04.073Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vue-CLI 製作 SPA 很方便，那需要多頁面的時候呢？</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RhIElMFCH_U4p32tqedrjA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@dollargill?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Dollar Gill</a> on <a href="https://unsplash.com/s/photos/pages?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>— 利用 Vue-CLI 進行多頁面開發與打包 / multi-page mode and the alternative solution by Webpack.</p><p>現今流行的前端開發方式不外乎是利用框架進行SPA的網站開發，而 Vue-CLI為 Vue 開發者提供了便利的初始化工具，在不需複雜的設定下我們可以很快的將專案打包成單頁面應用。</p><p>然而一個工程師需面對各式各樣的需求，比如一套 landing page 想在不同的管道進行推廣，且需要在前端頁面嵌入各自的統計代碼；又依據這些管道的性向不同，頁面的元件編排也會有些許不同。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MlqXd3hvO71u-veVlKCZfw.png" /><figcaption>元件排列組合製作多個頁面。</figcaption></figure><p>在這種情況下，雖然 Vue 可以很便利的共用元件，但若要打包成多個頁面時，總不可能將專案複製多份後，再分別組合吧。</p><blockquote>Not every app has to be an SPA. Vue CLI supports building a multi-paged app using the <a href="https://cli.vuejs.org/config/#pages">pages option in </a><a href="https://cli.vuejs.org/config/#pages">vue.config.js</a>.</blockquote><p>沒錯！其實 Vue-CLI 也有 multi-page mode 的！首先新增一個 vue.config.js 的<a href="https://cli.vuejs.org/config/#vue-config-js">設定檔</a>於專案的根目錄中（由 Vue-CLI 產生的專案預設並沒有此 config）。參照<a href="https://cli.vuejs.org/config/#vue-config-js">官方文件</a>可以看到裡面有許多的 options 屬性可作設定，接下來我們會專注在 <a href="https://cli.vuejs.org/config/#pages">pages</a> 屬性，以下是它提供的部分模板：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7f8f9118ef643258c7219ff7ccb2f8a/href">https://medium.com/media/f7f8f9118ef643258c7219ff7ccb2f8a/href</a></iframe><p>除了 entry 為必填欄位，其它為選填，以下針對幾個選項進行說明：</p><ol><li>entry ：這是頁面打包時所使用到的 js 入口，為必填欄位。通常 Vue-CLI 會以 main.js 作為預設，並由此開始將專案轉為 Vue 並進行打包。</li><li>template：頁面的HTML模板，通常為共用的 &lt;head /&gt; 及 &lt;body /&gt;內容。</li><li>filename：頁面打包後輸出的 html 檔案名稱。</li><li>title：template code 說明了 title 需使用 <a href="https://cli.vuejs.org/guide/html-and-static-assets.html#interpolation">特殊的語法</a> :<br>&lt;title&gt;&lt;%= htmlWebpackPlugin.options.title %&gt;&lt;/title&gt;<br>插入至我們的 html 中。</li><li>除了上述 template 中提到的 option ，我們也可自行新增如 subtitle tag1 tag2 ga_code 等等的自定義屬性，並使用同 title 的方式插入我們的 html 中。</li><li>而注入 html 中的值又該如何取用呢？比如我們將 subtitle 插入至&lt;meta /&gt; 這個 HTML tag ：</li></ol><pre>&lt;meta <br> attr=”subtitle” <br> content=”&lt;%= htmlWebpackPlugin.options.subtitle %&gt;” <br>/&gt;</pre><p>給予 attr 及 content 後，只需在 code 裡只要以 js 取出即可：</p><pre>document.querySelector(“META[attr=’title’]”).getAttribute(“content”)</pre><p>瞭解這些設定後，最關鍵的一步就在於 config 中 pages 物件底下的 index 物件，其實這並不是唯一的物件，而是我們可以自己創建如 index01 index02 index03等多個物件。也就是說我們可以像這樣去製作 config ：</p><pre>module.exports = {<br>  pages: {<br>    index01: {<br>      entry: &#39;src/index/main01.js&#39;,<br>      template: &#39;public/index.html&#39;,<br>      filename: &#39;index.html&#39;,<br>      title: &#39;Index Page&#39;,<br>      chunks: [&#39;chunk-vendors&#39;, &#39;chunk-common&#39;, &#39;index&#39;]<br>    },<br>    index02: {<br>      entry: &#39;src/index/main02.js&#39;,<br>      template: &#39;public/index.html&#39;,<br>      filename: &#39;index.html&#39;,<br>      title: &#39;Index Page&#39;,<br>      chunks: [&#39;chunk-vendors&#39;, &#39;chunk-common&#39;, &#39;index&#39;]<br>    },<br>    ...,<br>  }<br>}</pre><p>這樣我們就能從相同或不同之 main.js 入口，載入各自所需的 Vue components，並分別插入設定值至 html 中，最後打包輸出多個頁面。以下是 main.js 載入不同 Vue components 的範例：</p><pre>// main01.js<br>import Vue from &#39;vue&#39;;<br>import App from &#39;./App01.vue&#39;;</pre><pre>new Vue({<br>    render: h =&gt; (App),<br>}).$mount(&quot;#app&quot;)</pre><pre>// main02.js<br>import Vue from &#39;vue&#39;;<br>import App from &#39;./App02.vue&#39;;</pre><pre>new Vue({<br>    render: h =&gt; (App),<br>}).$mount(&quot;#app&quot;)</pre><p>而 vue.config.js 說到底還是一個 javascript檔，我們可以在其中撰寫一些 function 來擴展。因此在我個人的例子中，我會另寫一支設定檔data.config.js：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e1fb9be0af0f092c9a6facba5dcab28/href">https://medium.com/media/0e1fb9be0af0f092c9a6facba5dcab28/href</a></iframe><p>因為是獨立的檔案，我們可以透過協作的方式交由需求方（通常是PM）來做設定。開發者只需在 vue.config.js 中 require 並加以處理即可。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2d866cac1601d8b8987eb122dfe42bd/href">https://medium.com/media/d2d866cac1601d8b8987eb122dfe42bd/href</a></iframe><p>以上是簡略的 pseudo code ，將 data.config 迴圈處理組成 pages 導出即可。</p><p>其實在 Vue-CLI 中 pages 的選項是透過 <a href="https://github.com/jantimon/html-webpack-plugin">html-webpack-plugin</a> 這個 Webpack plugin 來實現的，所以可以根據這個套件的文檔來做更多的設定；若想自己設定 Webpack 來做專案打包而不依賴 Vue-CLI 工具也是可以的：</p><pre>const HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;)<br><br>module.exports = {<br>  entry: &#39;index.js&#39;,<br>  output: {<br>    path: __dirname + &#39;/dist&#39;,<br>    filename: &#39;index_bundle.js&#39;<br>  },<br>  plugins: [<br>    new HtmlWebpackPlugin(),<br>    new HtmlWebpackPlugin(),<br>    new HtmlWebpackPlugin()<br>  ]<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=633b39bb157" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>