Reputation: 143
I have been experimenting with Astro, reviewing it for a couple of projects that I will be working on. I have read the script section of the docs (https://docs.astro.build/en/guides/client-side-scripts/#using-script-in-astro) as well as the typescript section (https://docs.astro.build/en/guides/typescript/) The workflow seems counterintuitive to me though and I don't follow how I should either work with typescript in the project or compile it to js as part of the build.
I have a simple typescript file that works as is outside of Astro (once it has been transpiled).I have placed this in public/scripts/index.ts), it has a class with a constructor which is called, and the resulting object is console logged. My constructor is as below for reference:
constructor(test: string) {}
In index.astro I have the following in my head section
<script is:inline src="/scripts/index.ts"></script>
I have also tried with index.js in case this would force a transpile to js. However, when I run the dev script I get the below error which points to my constructor
Unexpected token ':'
When I inspect, I see that the typescript file reference is still as above (so no 'magic' changing of the extension to js etc). I have also ran the build script to see what would happen. I hoped that in the build process it would transpile and bundle my ts file but it just copies it. I know I could change this by editing the tsconfig but I'm concerned that this may interfere with Astro as I know it uses typescript internally. My understanding that part of the point of storing scripts in the public folder was so that Astro could do what was needed to get the file to be runnable. Can anyone advise on how I can make my ts run correctly or the best practice for building it into ts and bundling it?
Upvotes: 1
Views: 3333
Reputation: 2069
Astro will compile Typescript for you. It supports this in script blocks as well as when linking to a script with a src
attribute. But with two important notes:
The script tag should contain no additional attributes (other than src
if using it). The is:inline
directive in your example disables this processing, shipping the tag as-is to the browser.
The source file is inside your src/
directory (not in public/
as in your example).
Some examples:
---
// src/components/Component.astro
---
<script>
import dependency from '../scripts/file';
let x: number = dependency.use();
</script>
src
attribute. The .ts
file will also be bundled as JavaScript.---
// src/components/Component.astro
---
<script src="../scripts/my-script.ts"></script>
Upvotes: 3