What is the best way to transpile TypeScript within the Astro framework?

Recently, I decided to dive into exploring Astro for a couple of upcoming projects. In my research, I delved into the script and typescript sections of the documentation (), as well as (). However, I found the workflow somewhat counterintuitive and struggled with incorporating typescript into my project.

I have a basic typescript file that functions properly outside of Astro (after transpilation) by placing it in public/scripts/index.ts. The file features a class with a constructor that gets invoked, and the resulting object is logged to the console. For reference, here's my constructor:

constructor(test: string) {}

In index.astro, I included the following in the head section:

<script is:inline src="/scripts/index.ts"></script>

Additionally, I tried using index.js to trigger transpilation to JS. Unfortunately, when running the dev script, I encountered an error pointing to my constructor:

Unexpected token ':'

Upon inspecting, I noticed that the typescript file reference remained unchanged despite my attempts to force a conversion to JS. Running the build script simply resulted in copying the file, rather than transpiling and bundling it as I had hoped. While aware that editing tsconfig could potentially resolve this issue, I hesitated due to concerns about potential conflicts with Astro's internal use of typescript.

Given that storing scripts in the public folder should ideally enable Astro to handle necessary transformations for executable files, can anyone provide guidance on properly executing my typescript or suggest best practices for compiling it to JS and bundling it accordingly?

Answer №1

Astro offers compilation support for Typescript, whether it's in script blocks or when linking to a script using the src attribute. However, there are two important considerations to keep in mind:

  • The script tag should not have any additional attributes (except for src if used). The is:inline directive can be used to bypass processing and deliver the tag directly to the browser.

  • Your source file should be located within the src/ directory, as opposed to the public/ directory shown in the example.

Here are some examples to illustrate this:

  • An Astro component with a script block that imports modules and leverages Typescript syntax, which will ultimately be bundled as JavaScript.
---
// src/components/Component.astro
---

<script>
import dependency from '../scripts/file';

let x: number = dependency.use();
</script>
  • A script tag loading an external Typescript file via its src attribute. The .ts file will also be compiled into JavaScript.
---
// src/components/Component.astro
---

<script src="../scripts/my-script.ts"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Challenges in handling asynchronous data within static JSON objects in Angular2

I have a service set up with some static objects that are being utilized in my UI. fetchRulesVariables() fetchRuleVariables() { let variables = [ { name: 'Credit Funding Type', id: 1, multiple: ...

The declaration file for the module 'tailwind-scrollbar' could not be located

Currently, I am in the process of utilizing Tailwind packages for a Next.js application, however, I have encountered an issue that has proved to be quite challenging to resolve. Every time I attempt to add a "require" statement to my tailwind.config.js fil ...

The correct way to assign a value within an Angular Observable subscribe function

Having some trouble with a basic form using @angular/material (although the material aspect shouldn't make a difference) that is structured like this: <div *ngIf="user"> <form> <mat-form-field> <m ...

Having trouble invoking the "done" function in JQuery following a POST request

I am currently working on a Typescript project that utilizes JQuery, specifically for uploading a form with a file using the JQuery Form Plugin. However, after the upload process, there seems to be an issue when trying to call the "done" function from JQue ...

Steps to insert a personalized attribute into a TypeScript interface

UPDATED EXPLANATION: I'm fairly new to TypeScript, so please bear with me if this question seems basic. I'm working with an existing library (ngx-logger) that I don't want to or can't modify. My goal is to create a service that generat ...

The 'GoogleAuthProvider' property cannot be found on the 'AngularFireAuth' type

When attempting to sign in with Google using 'AngularFireAuth', I encountered an error. Here is the code snippet from my auth.service.ts file: import { Injectable } from '@angular/core'; import { first } from 'rxjs/operators'; ...

Creating a String-Helper component using Angular and TypeScript

One issue I'm facing is that when using the german ü, ä, ö characters in HTML, they are showing up as unknown symbols. To properly display them, you can write ü as "&uuml ;" and ä as "&auml ;", and so on. However, my challenge is coming f ...

Angular2/TypeScript Coding Guidelines

I am curious about the common practices and consensus among the Angular2 community when it comes to writing reusable code in TypeScript. I have gathered some information and questions related to Angular2 that I would like to discuss. Organizing Module/A ...

You cannot invoke this expression while destructuring an array of React hooks in TypeScript

Within my React TypeScript component, I have several fields that check a specific condition. If the condition is not met, the corresponding field error is set to true in order to be reflected in the component's DOM and prevent submission. However, whe ...

Getting the Full Error Message in Axios with React Native Expo

I'm encountering a network error while using Axios with React Native. Previously, when working with React JS on the web, I could console log the error or response and see all the details. However, in Expo, all I get is "Axios error: Network error" wh ...

Creating a variable as a list of string arrays in TypeScript

Currently working with Angular 2.0, I am trying to declare a variable in a Typescript file that is a list of string arrays. I attempted using yAxis_val: list, but it is not functioning correctly. If anyone knows the proper way to achieve this, please prov ...

What is the correct way to include a new property in the MUI Link component using TypeScript?

Currently, within my mui-theme.ts configuration file, I have the following setup: const theme = createTheme(globalTheme, { components: { MuiLink: { variants: [ { props: { hover: 'lightup' }, style: { ...

Struggling to make Typescript recognize the css prop (emotion) when styling Material-UI components

I'm on a mission to set up a Typescript project with Material-UI v4.11.4 and implement emotion for styling in anticipation of the MUI v5 release. The aim is to integrate emotion into the project so developers can transition to using the new styling in ...

IntelliSense in VSCode is unable to recognize the `exports` property within the package.json file

Currently, I am utilizing a library named sinuous, which contains a submodule known as "sinuous/map". Interestingly, VSCode seems to lack knowledge about the type of 'map' when using import { map } from "sinuous/map", but it recognizes the type ...

What is the reason behind the checkbox event status returning the string "on" rather than true/false?

I have implemented a custom checkbox as a child component within a parent component. I properly pass the ngModel, name, etc., and attempt to update the model with a boolean status (true/false) based on the checkbox status using an EventEmitter. However, t ...

Typescript TypeError: Unable to call function this.array[i].greet as it is not defined

When attempting to call my function, I am encountering an error. Interestingly, everything works fine when I create just one object of someClass and then utilize the greet function. This is what does not work (someArray being an array of type someClass): ...

The conversion of an array to Ljava/lang/Object is not possible

I'm currently working on a project using NativeScript app with TypeScript where I am trying to pass an array of android.net.Uri to a function. However, when attempting to do so, I encounter an error mentioning that the 'create' property does ...

A guide on exporting table data to PDF and enabling printing features in Angular 7

Can anyone provide guidance on how to export my dynamic table data into Excel, PDF, and for printing using the appropriate Angular Material components and npm plugins? I have successfully exported the data as an Excel file, but am struggling with exporti ...

Obtaining Prisma arguments by providing the table name as a string

Is there a way to retrieve the query arguments for a Prisma function by only passing the table name? Currently, I know I can obtain the table by providing the table name as a string in the following manner: function (tablename: string) { await prisma.[tab ...

Troubleshooting Socket-io Client Problem After Migrating to TypeScript

I am currently in the process of migrating my MERN stack + Socket.io template to Typescript. However, I am encountering some issues specifically when transitioning the client code to Typescript. The Problem: My socket pings from socket.io-client are faili ...