Skip to main content

Andrew Mok

Software Engineer, Frontend

在 Vue-loader 中使用 Retina.js

Available in: English

讓 Vue 也能正確提供 retina 圖片

**2020 更新:**你也可以考慮使用原生支援的 srcsetpicture/source 來處理 retina 圖片。這份文件有相關範例。

vue-loaderwebpack 用來處理 Vue component 的 loader。預設情況下,它只會處理寫在 src 中的檔案路徑。

由於 url-loaderfile-loader 並不知道 @2x@3x 這些檔案路徑,production build 時通常不會把 @2x@3x 檔案一併打包。因此,retina.js 就找不到用來替換 retina 圖片的 @2x 與 @3x 檔案。

你可以用以下方式把 @2x 圖片提供出去,並讓 Vue-loader 正確辨識它們:

  1. 在 Vue component 的 template 中,於 img 標籤加入 data-rjs 來指定 @2x 的檔案路徑。
  2. 編輯 build/vue-loader.conf.js,加入以下內容:
transformToRequire: { img: ['src', 'data-rjs'], image: 'xlink:href' }

這樣一來,Vue-loader 就會把 data-rjs 也視為需要處理的檔案,並讓 url-loaderfile-loader 在 production build 時一併打包這些資源。


參考資料: