简体   繁体   中英

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"}
  })
}

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}
  })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM