#Why gsap is not defined

4 messages · Page 1 of 1 (latest)

median maple
#

Now I put "import { gsap } from 'gsap'" in main.js and introduce it in layout.astro with
···
<script>
import '~/assets/js/main.js'
</script>
···
Then I use GSAP in a component and get the error:
Uncaught ReferenceError: gsap is not defined.

acoustic wyvernBOT
#

Hi @median maple. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

The error message "Uncaught ReferenceError: gsap is not defined" suggests that the GSAP library is not being recognized in the scope where you're trying to use it. This could be due to how Astro handles scripts and imports.

Astro processes and optimizes <script> tags by default, bundling them into external files. However, when you add any attribute to your <script> tag (like src in your case), this default behavior is removed. This is because the is:inline directive is implied whenever any attribute other than src is used on a <script> tag. The is:inline directive tells Astro to leave the <script> tag as-is in the final output HTML, without processing, optimizing, or bundling its contents (source (https://docs.astro.build/en/reference/directives-reference/#isinline)).

To ensure that your import statement works as expected, you should add the type="module" attribute to your <script> tag. This allows you to use import statements in your script. Here's how you can modify your script tag:

<script type="module">
   import '~/assets/js/main.js'
</script>

Also, remember that Astro components run on the server, so if the GSAP library relies on a browser environment, importing it in the frontmatter may lead to errors (source (https://docs.astro.build/en/guides/imports/)). If you're trying to use GSAP within an Astro component, you might need to move the relevant code to a <script> tag outside of the frontmatter, or use a client-side hydration directive like client:load or client:only (source (https://docs.astro.build/en/guides/troubleshooting/)).