Astro JS - Scripts



Scripts in Astro

Scripts are used to add interactivity to the components in a web page. Astro supports JavaScript and TypeScript for adding scripts to the components. Also, you can use other UI frameworks like, React, Vue, and Svelte in Astro to implement client side interactivity. This allows you to send JavaScript to run in the browser and add functionality to your Astro components. In this chapter, we will discuss how to add scripts to Astro components using JavaScript and TypeScript.

Astro Client Side Scripts

Astro uses HTML <script> tag to include client side scripts in the Astro components. This script tag can be used in .astro or .html files to include JavaScript or TypeScript code. The scripts can add event listeners, send analytics data, play animations, and everything else JavaScript can do on the web.

Script Processing

By default, <script> tags are processed by Astro.

  • Any imports will be bundled, allowing you to import local files or Node modules.
  • The processed script will be injected at where its declared with type="module".
  • TypeScript is fully supported, including importing TypeScript files.
  • If your component is used several times on a page, the script will only be included once.

Example Client Side Scripting

The following example shows how to use client side scripts in Astro. The script adds an event listener to the document object that appends an h2 element to the body when the DOM content is loaded.

<!--File: /src/pages/index.astro-->

<h1>Welcome, world!</h1>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        document.body.innerHTML += '<h2>Welcome, From Script....!</h2>';
    });
</script>

Output

In the output, you can see that the h2 element is appended to the body when the DOM content is loaded.

Astro Script Example

React Scripts in Astro

Astro allows you to use React components in your Astro project. Follow the steps below to integrate React with Astro:

Step 1: Integrate React to Astro

First, you need to add React to your Astro project. Astro includes an astro add command to automate the setup of official integrations. Run the following command to add React to your Astro project:

>> npx astro add react

Step 2: Create a React Component

The code below, create a counter React component at 'src/' directory. The component will have a button that will increase the count by 1. This counter component will become an island of Astro page.

// File: src/components/Counter.jsx

import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(count + 1)}>
        Count: {count}
    </button>
  );
}

Step 3: Use the Component in Astro Page

The code below defines an Astro page at 'src/pages/index.astro'. The page imports the Counter component and renders it in the page. The Counter component loads JavaScript only when it is visible in viewport, because we are using the 'client:visible' directive.

<!-- File: src/pages/index.astro -->

---
    import Welcome from '../components/Welcome.astro';
    import Layout from '../layouts/Layout.astro';
    import Counter from "../components/Counter.jsx";
---

<Layout>
    <Welcome />
    <h1>Welcome to Astro</h1>
    <p>This content is static.</p>
    
    <!-- Interactive Island -->
    <Counter client:visible />
</Layout>

Step 4: Output

In the output image below, you can see that we successfully setup the react script in Astro page. React scripts will be treated as islands in Astro.

Astro JS Island Example

Include External Scripts in Astro

Sometime, You may want to write your scripts as separate .js/.ts files or need to reference an external script on another server. You can do this by referencing these in a <script> tags src attribute.

Include Local Scripts

You can load any local script file in Astro by using the <script> tag with the src attribute. The src attribute should point to the location of the script file.

<!-- relative path to script at `src/scripts/local.js` -->
<script src="../scripts/local.js"></script>

<!-- also works for local TypeScript files -->
<script src="./script-with-types.ts"></script>

Include External Scripts

You can also load external scripts in Astro by using the <script> tag with the src attribute. while loading scripts outside of your projects src/ folder, include the is:inline directive.

<!-- external script from a CDN -->
<script is:inline src="https://cdn.jsdelivr.net/npm/vue@3.0.0/dist/vue.global.prod.js"></script>
Advertisements