#How to connect a script with a name depending on the page?

3 messages · Page 1 of 1 (latest)

worthy delta
#

I'm passing the filename of a specific page through the pageName variable, but it gives me an error. <script src=/src/scripts/${pageName}.js></script>

coarse gustBOT
#

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

#

Astro does not support dynamic script imports in the way you're trying to do. However, you can import scripts in Astro in a few ways:

  1. Importing a .js file: You can move the contents of your <script> tag into its own .js file in your project and then import it in your Astro file. For example:
<script>
  import "../scripts/menu.js";
</script>

This is described in the Astro tutorial (https://docs.astro.build/en/tutorial/3-components/4#importing-a-js-file).

  1. Including JavaScript files on your page: You can reference .js/.ts files or external scripts in a <script> tag’s src attribute. For example:
<!-- relative path to script at `src/scripts/local.js` -->
<script src="../scripts/local.js"></script>

This is described in the Astro guide on client-side scripts (https://docs.astro.build/en/guides/client-side-scripts#include-javascript-files-on-your-page).

If you need to use different scripts for different pages, you might need to manually import the correct script for each page. If you're trying to dynamically import scripts based on a variable, this is not currently supported in Astro. You might want to consider restructuring your code or using a different approach to achieve your desired functionality.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: