I'm trying to write some client-side js, and I know that typescript doesn't work on the browser. I'm asking if it's possible to have typescript in the <script> tag, and then the build step gets rid of it just like it would other js. I've only worked with nextjs, and that seems to be a thing there so I'm curious how it works with astro.
#Is it possible to get Typescript to work within a <script> tag inside a .astro page?
3 messages · Page 1 of 1 (latest)
Hi @timber heath. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Yes, you can write TypeScript code directly inside the <script> tags in your Astro components. Astro includes built-in support for TypeScript and any imports will be bundled, allowing you to import local files or Node modules. The processed script will be injected into your page’s <head> with type="module". If your component is used several times on a page, the script will only be included once.
Here's an example of how you can use TypeScript in your Astro component:
<script>
// Processed! Bundled! TypeScript-supported!
// Importing local scripts and Node modules works.
</script>
However, please note that Astro doesn’t perform any type checking itself. Type checking should be taken care of outside of Astro, either by your IDE or through a separate script. For type checking Astro files, the astro check command is provided.
Also, it's important to note that Astro’s default bundling behavior will be disabled in some situations. In particular, adding type="module" or any attribute other than src to a <script> tag will cause Astro to treat the tag as if it had an is:inline directive. The same will be true when the script is written in a JSX expression.