Search code examples
javascripthtmlgsapparceljs

Parcel won't load images in my javascript file


I am using the parcel bundler for my website.

I've been trying to use gsap to change the src attribute of an <img> tag. This change happens when the user clicks on a <button onclick="changeImage()">. However, the localhost:1234 server doesn't show this change at all. Can parcel change images of my website after build time?

my html snippet:

<img class="mercury_image" src="images/mercury.png"/>
<button onclick="changeImage()"> Click here </button>

my javascript snippet

function changeImage() {
    gsap.timeline()
    .set(".mercury_image", {
       attr: {src: "images/differentImage.png"}
  })
}

Solution

  • From the Parcel docs:

    Parcel automatically analyzes the dependencies referenced in these files and includes them in the output bundle.

    Because there aren't any references to these files at compile-time Parcel doesn't know about them. You need to either add a plugin to track all of your images (like parcel-plugin-static-files-copy) or explicitly import them like this:

    import differentImage from "images/differentImage.png";
    
    function changeImage() {
        gsap.timeline()
        .set(".mercury_image", {
           attr: {src: differentImage}
      })
    }