最近想練習Vue的Composition API,順便重構原本的專案,但在引入CDN後發生了一些問題,想紀錄一下來龍去脈
HTML
1 | <div id="app">{{ message }}</div> |
JS
1 | import { createApp, reactive, ref } from 'vue' |
出現錯誤 Uncaught SyntaxError: Cannot use import statement outside a module
搜尋一下發現沒有在引用JS檔案的那條script標籤裡面加上type=”module”
不過加上後又冒出一個新的錯誤資訊 Uncaught TypeError: Failed to resolve module specifier "vue". Relative references must start with either "/", "./", or "../".
回去找Vue.js官方文件:
We can teach the browser where to locate the vue import by using Import Maps:
1 | <script type="importmap"> |
於是就正常了:
HTML
1 | <script type="importmap"> |
JS
1 | import { createApp, reactive, ref } from 'vue' |
後記
importmap
雖然ES6已經有import export可以模組化程式的功能,但在實際使用時
“必須要用相對路徑、絕對路徑或是URL的方式import ”
例如:
1 | import { createApp, reactive, ref } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js' |
否則console就會出現Relative references must start with either "/", "./", or "../".
importmap就是要解決這樣的問題
,只要在script標籤裡面加上importmap,並用JSON的格式將要管理的路徑和對應的名稱統一管理在這個標籤裡面
1 | <script type="importmap"> |
就可以用原本的方式引入:
1 | import { createApp, reactive, ref } from 'vue' |
對來說瀏覽器就會看起來像是:
1 | import { createApp, reactive, ref } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js' |