使用 Vue-SFC-Rollup 進行開發 npm 套件時,當你完成後正心想要來有個 Demo 頁面給使用者在安裝前瀏覽一下,會發現 vue-sfc-rollup 並沒有提供 build 出 Vue.js 的編譯檔相關設定。若為此加裝一個 vue-cli 又顯得麻煩也不好管理。這邊筆記下發佈到 github-apges 的方式和製作流程。
原理
1. 利用 Vue 本身得以用 cdn 的方式引入的方式,引入 vue3 和 vue3-sfc-loader 兩個套件
2. 額外撰寫 script ,並在 createApp 中加入 template
3. github Pages 本身可支援存取 root 或是 docs 資料夾上的 *.html 當作內容
優點
1. 不需要額外設定 rollup.config.js
2. 與原先 rollup 相關設定分離,方便日後進行額外操作和管理
缺點
程式碼
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | <!DOCTYPE html> <html lang="en"> <head>   <meta charset="UTF-8">   <meta http-equiv="X-UA-Compatible" content="IE=edge">   <meta name="viewport" content="width=device-width, initial-scale=1.0">   <title>Demo Page</title> </head> <body>   <div id="app"></div>   <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.24/vue.global.prod.min.js"></script>   <script src="https://cdn.jsdelivr.net/npm/vue3-sfc-loader/dist/vue3-sfc-loader.js"></script>   <script>     const { createApp, defineComponent, ref } = Vue     const { loadModule } = window['vue3-sfc-loader']     const options = {         moduleCache: {           vue: Vue         },         async getFile(url) {           const res = await fetch(url);           if (!res.ok)             throw Object.assign(new Error(res.statusText + ' ' + url), { res });           return {             getContentData: asBinary => asBinary ? res.arrayBuffer() : res.text(),           }         },         addStyle(textContent) {           const style = Object.assign(document.createElement('style'), { textContent });           const ref = document.head.getElementsByTagName('style')[0] || null;           document.head.insertBefore(style, ref);         },       }     createApp({       components:{         'VueTwZipCodeSelector': Vue.defineAsyncComponent(() => loadModule('./demo.vue', options))       },       setup() {         const result = ref({         })         const showSelectedZone = (selectedZone) => {           result.value = selectedZone.value         }         return {           result,           showSelectedZone         }       },       template:`         <VueTwZipCodeSelector @getSelectedZone="showSelectedZone"></VueTwZipCodeSelector>         <p>{{result}}</p>       `     }).mount('#app');   </script> </body> </html> | 
參考資料
1. Vue.js 编译
2. vue3-sfc-loader





