1. 程式人生 > >【採坑之路】You may need an appropriate loader to handle this file type.

【採坑之路】You may need an appropriate loader to handle this file type.

開啟vue之旅,也是開始採坑之旅了。

這是一個京東購物車小案例,採用元件化開發,將html靜態頁面拆分成一個個元件,採用webpack打包時,引用的圖片明明存在但報錯如下:

ERROR in ./jd-shopcarts/assets/images/icon-kin.png 1:0
Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
 @ ./jd-shopcarts/assets/basic.css (./node_modules/css-loader!./jd-shopcarts/assets/basic.css) 7:908-948
 @ ./node_modules/css-loader!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/vue-loader/lib??vue-loader-options!./jd-shopcarts/App.vue?vue&type=style&index=0&lang=css&
 @ ./node_modules/style-loader!./node_modules/css-loader!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/vue-loader/lib??vue-loader-options!./jd-shopcarts/App.vue?vue&type=style&index=0&lang=css&
 @ ./jd-shopcarts/App.vue?vue&type=style&index=0&lang=css&
 @ ./jd-shopcarts/App.vue
 @ ./jd-shopcarts/main.js

開始坎坷的debug之旅:

針對這個報錯百度到的問題大都與vue-loader有關,但我vue-loader安裝成功且在webpack.config中配置過了;

然後查到url-loader和fil-loader與圖片打包有關,進行安裝,安裝命令如下:

 npm install --save-dev url-loader

 npm install file-loader --save-dev

然後在webpack.config.js檔案中進行配置:

    module:{
        rules:[
            {test:/\.css$/,loader:"style-loader!css-loader"},
            {test:/\.vue$/,loader:"vue-loader"},
            {test:/\.(jpg|png|jpeg|gif)$/,loader:"url-loader"}
        ]
    },

注意樣式中的url路徑是相對入口html頁面的,而非相對於原始css檔案所在的路徑,這可能導致圖片引入失敗。

針對該問題,採用file-loader解決,file-loader可以解析專案中的url引入(不僅限於css),根據配置將圖片拷貝到相應的路徑,再根據配置修改打包後文件引用路徑,使之指向正確的檔案。

當圖片較多傳送多個http請求,頁面效能降低。可以通過url-loader將引入的圖片編碼,生成dataURl。相當於把圖片資料翻譯成一串字元。再把這串字元打包到檔案中,最終只需要引入這個檔案就能訪問圖片了。當然,如果圖片較大,編碼會消耗效能。因此url-loader提供了一個limit引數,小於limit位元組的檔案會被轉為DataURl,大於limit的還會使用file-loader進行copy。

那麼url-loader與file-loader的關係是:url-loader封裝了file-loader,其內建有file-loader。
 

webpack配置命令迷迷糊糊的,附上全部的webpack.config.js配置檔案。

const path = require("path")
const {VueLoaderPlugin} = require("vue-loader")


module.exports = {
    mode:"development",
    entry:{
        app:path.resolve(__dirname,"jd-shopcarts/main.js")
    },
    output:{
        path:path.resolve(__dirname,"jd-shopcarts/dist"),
        filename:"[name].bundle.js"
    },
    resolve:{
        extensions:[".js",".css",".vue"]
    },
    module:{
        rules:[
            {test:/\.css$/,loader:"style-loader!css-loader"},
            {test:/\.vue$/,loader:"vue-loader"},
            {test:/\.(jpg|png|jpeg|gif)$/,loader:"url-loader"}
        ]
    },
    plugins:[
       new VueLoaderPlugin()
    ]
}