'Sveltekit Greensock Scrolltrigger breaking in production
I have a Green Sock animation that is working fine in development, but breaks in yarn run preview
and production: ScrollTrigger-4a410f45.js:9 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'name')
. The result is that the the point I'm trying to animate along the path is not positioned on the path and does not move.
import { gsap } from 'gsap';
import { MotionPathPlugin } from 'gsap/dist/MotionPathPlugin.js';
let reference, path, ico;
onMount(async () => {
gsap.registerPlugin(ScrollTrigger, MotionPathPlugin);
gsap.timeline({
defaults: { duration: 1 },
scrollTrigger: {
trigger: reference,
}
})
.to(ico, { duration: 0.01, autoAlpha: 1 })
.to(ico, {motionPath: {path: path, align: path, alignOrigin: [0.5, 0.5]}}, 0);
});
I have no issues with this locally, the error only shows in the production build. I'm not sure if this is something with my Green Sock code or my Svelte config. Any tips or a solution would be greatly appreciated.
Solution 1:[1]
It turns out it has something to do with the way SvelteKit or Vite is handling the Greensock import across multiple components. Full details here (all credit for this answer from that post by Blake Bowen).
The work around is to import Greensock and Scrolltrigger into a script and then require that script wherever you need it. So you are only importing the Greensock library once rather than in every component where it is needed.
gsap.js
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/dist/ScrollTrigger.js';
import { MotionPathPlugin } from 'gsap/dist/MotionPathPlugin.js';
if (typeof window !== "undefined") {
gsap.registerPlugin(ScrollTrigger, MotionPathPlugin);
}
export * from "gsap";
export { MotionPathPlugin, ScrollTrigger };
Then in components just import the script: import { gsap, ScrollTrigger } from "../scripts/gsap";
This is a bit of a workaround but I think it's actually more concise.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | tfantina |