Search code examples
vue.jsvuejs2vue-componentvue-cli-3

img srcset in vue-cli project results in compile error


I have an image for a vue-cli project, and it works fine with the following path:

<img src="../assets/images/banner/hero_2x_w4eyw5_c_scale,w_2086.jpg" alt="">

But when I insert image URLs with srcset for responsive image breakpoints, I see a compile error.

Here is the generated image code:

<img sizes="(max-width: 3840px) 100vw, 3840px" 
    srcset="../assets/images/banner/hero_2x_w4eyw5_c_scale,w_320.jpg 
    320w,../assets/images/banner/hero_2x_w4eyw5_c_scale,w_1099.jpg 
    1099w,../assets/images/banner/hero_2x_w4eyw5_c_scale,w_1647.jpg 
    1647w,../assets/images/banner/hero_2x_w4eyw5_c_scale,w_2086.jpg 
    2086w,../assets/images/banner/hero_2x_w4eyw5_c_scale,w_2460.jpg 
    2460w,../assets/images/banner/hero_2x_w4eyw5_c_scale,w_2848.jpg 2848w, 
    ../assets/images/banner/hero_2x_w4eyw5_c_scale,w_3214.jpg 
    3214w,../assets/images/banner/hero_2x_w4eyw5_c_scale,w_3556.jpg 
    3556w,../assets/images/banner/hero_2x_w4eyw5_c_scale,w_3805.jpg 
    3805w,../assets/images/banner/hero_2x_w4eyw5_c_scale,w_3840.jpg 3840w"
    src="../assets/images/banner/hero_2x_w4eyw5_c_scale,w_3840.jpg" alt="">

Error!

screenshot of console error


Solution

  • The error occurs because vue-loader does not handle commas in srcset filenames/URLs. It simply splits the srcset string by ,, so the first srcset value of ../assets/images/banner/hero_2x_w4eyw5_c_scale,w_320.jpg is parsed as ../assets/images/banner/hero_2x_w4eyw5_c_scale, leading to the Module not found error in your screenshot.

    MDN docs indicate that the srcset values are comma-delimited, and it's unclear whether the commas are permitted within the filenames/URLs. In any case, you could resolve the build errors by renaming your files to remove the commas, and updating the references in your srcset to match.