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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014322206/article/details/84560935

开启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()
    ]
}

猜你喜欢

转载自blog.csdn.net/u014322206/article/details/84560935