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

Using external URLs with added tracking parameters in Ionic 2

I am looking to create a unique http link to an external URL, extracted from my JSON data, within the detail pages of my app. Currently, I have the inappbrowser plugin installed that functions with a static URL directing to apple.com. However, I would lik ...

Divide MUI theme into individual files

I have encountered an issue in my Next.js project. I currently have an index.ts file residing in the src/theme directory. 'use client'; // necessary for MUI to work with nextjs (SSR) import { createTheme } from '@mui/material/styles'; i ...

Determine the type of function arguments based on provided hints in TypeScript

It's common to encounter situations like this where TypeScript struggles to infer types due to lack of context. Is there a way to explicitly declare the type of function for the compiler? router.get('/get', imget); router.get('/send&a ...

Having trouble getting React app to recognize Sass properly

I have been working on developing a React app using TypeScript and the SASS preprocessor. Here is an example of my code: // Button.tsx import React from 'react'; import './Button.scss'; export default class Button extends React.Compone ...

Angular route fails to load the HTML file

In the process of developing a route within an Angular application, I have successfully implemented 3 routes. However, one particular route is giving me trouble. I have three folders that need to redirect HTML based on the option chosen. In Angular, I cre ...

Unlock the key to connecting the output of one observable to another in rxjs

I have a procedure for saving users in the database. These are the steps I take: 1) First, I validate the request. 2) Next, I hash the password. 3) Finally, I store the user details in the users collection along with the hashed password. Below is the ...

Having trouble utilizing Vue3 methods while utilizing the `<script setup lang="ts">` syntax

Looking to incorporate Vue into a non-Vue Class using the Composition API for a Chrome Extension project where having the entire thing as a Vue App doesn't make sense. The Vue Instance is being instantiated in the usual manner and then injected into ...

Discover the process of translating words within app.routing.module.ts in Angular

Having some trouble with my Angular routing module and ngx-translate languages. I'm trying to retrieve words from the languages in this module, but the code I've attempted isn't working: import { NgModule } from '@angular/core'; im ...

Angular2 webpack example error: Cannot execute function 'call' because it is undefined

As I navigate through the Angular2 webpack sample app on https://angular.io/docs/ts/latest/guide/webpack.html, I've encountered an issue. After completing the "Development Configuration" section and attempting the "try it out" by copying the app code ...

Utilize clipboard functionality in automated tests while using Selenium WebDriver in conjunction with JavaScript

How can I allow clipboard permission popups in automated tests using Selenium web driver, Javascript, and grunt? https://i.stack.imgur.com/rvIag.png The --enable-clipboard and --enable-clipboard-features arguments in the code below do not seem to have an ...

New Requirement for Angular Service: Subclass Constructor Must Be Provided or Unable to Resolve all Parameters for ClassName (?)

During a recent project, I encountered an issue while working on several services that all extend a base Service class. The base class requires a constructor parameter of HttpClient. When setting up the subclass with autocomplete, I noticed that their con ...

Transfer only designated attributes to object (TS/JS)

Is it feasible to create a custom copy function similar to Object.assign(...) that will only copy specific properties to the target? The code snippet I have is as follows: class A { foo?: string; constructor(p: any) { Object.assign(this, p ...

What is the best way to access JavaScript built-ins in Typings when faced with name conflicts?

I am currently in the process of updating the Paper.js Typings located on GitHub at this repository: github.com/clark-stevenson/paper.d.ts Within Paper.js, there exists a MouseEvent class, which is not an extension of JavaScript's MouseEvent, but ra ...

A glitch was encountered during the execution of the ionic-app-scripts subprocess

I recently started using Ionic 3 and created an application that I'm trying to convert into an APK. To generate a debug (or testing) android-debug.apk file, I used the following CLI command: ionic cordova build android --prod The pages are declared ...

"Slow loading times experienced with Nextjs Image component when integrated with a map

Why do the images load slowly on localhost when using map, but quickly when not using it? I've tried various props with the Image component, but none seem to solve this issue. However, if I refresh the page after all images have rendered once, they ...

The Typescript compiler is unable to locate the module './lib'

I'm currently integrating the winston-aws-cloudwatch library into my TypeScript server-side application. If you want to replicate the issue, I have provided a SSCCE setup on GitHub. Here are the details: index.ts import logger from './logger& ...

Using Typescript to automatically infer strongly-typed recursive index types

Commencing with an Animal interface and a detailed map of animals residing on my farm: export interface Animal { species: string; edible: boolean; } export interface FarmMap{ [key: string]: Animal; } Everything seems to be running smoothly. Here ...

Issues with typescript compiler when using React-beautiful-dnd

I recently updated react and react-beautiful-dnd to the newest versions and now I am encountering many type errors in my code: {sortedDimensions.map((dimension: any, index: number) => ( <Draggable key={index} ...

Experiencing the error message "delete(...).then(...).error is not a function" while attempting to remove a file from Firebase storage using AngularFire and TypeScript

I'm trying to implement the code snippet from Firebase documentation to delete a file and then upload a new image in the same directory on Firebase Storage. However, I keep encountering an error message saying "delete(...).then(...).error is not a fun ...

Why isn't the customer's name a part of the CFCustomerDetails class?

Currently, I am utilizing the cashfree-pg-sdk-nodejs SDK to integrate Cashfree payment gateway into my application. Upon examining their source code, I noticed that the CFCustomerDetails class does not include the customerName attribute. https://i.stack.i ...