How to Use TypeScript with Svelte and Vite in 2022

As of the time of this writing, Svelte uses Vite for builds, and while Vite will automatically handle .ts files, it won't handle TypeScript in .svelte files.

For this to work, you need to preprocess your .svelte files using svelte-preprocess. Unfortunately their guides seem to be a bit outdated (references to Rollup abound). So I figured it out for myself (not that it was that hard) and I'm sharing it here for you and for future me.

$ npm i -D svelte-preprocess

Once you have svelte-preprocess installed, create a svelte.config.js in the root of your svelte project (e.g. same folder as your package.json) and paste this content into it:

import preprocess from 'svelte-preprocess';

const config = {
preprocess: preprocess()

export default config;

That's it. Vite builds will now preprocess your .svelte files, and svelte-preprocess has baked-in support for TypeScript, so builds should now stop throwing these errors because the Svelte compiler doesn't recognize your TypeScript:

Error [ParseError]: Unexpected token


It's like comments, but you do it on Twitter.

2 Replies

Mike Mike
@adamtuttle yeah, it's tricky. I have it in the back of my mind every time I write and try to keep it brief, but I end up thinking "what if the reader needs to know this?" Before I know it is a bloated mess
Adam Tuttle :phanatic: Adam Tuttle :phanatic:
@mikestreety I think it depends on how much nuance is necessary for any beginners that might be reading. For example, here's an article that I think rightly dives deep into nuance and here's one that is little more than the code you're reading for Global node.js Variables Are Safe to Use in AWS Lambda • Adam Tuttle
Add your comment: Tweet about this article.

Webmentions via

Discuss on TwitterEdit on GitHubContributions