Use TypeScript with Svelte / Sapper
Tags: svelte, sapper, typescript
Published: 2020-03-23 19:35:38

EDIT 2020-07-24: [Svelte now officially supports TypeScript](https://svelte.dev/blog/svelte-and-typescript)

---

It only takes a few steps to use TypeScript in your `.svelte` files within `<script lang="typescript">...</script>` blocks.

The following example shows you how to create a new project based on the [default Sapper template](https://github.com/sveltejs/sapper-template) and add support for TypeScript. Of course, the steps can also be adopted for projects that are not based on the template or for existing projects.

```sh
# Clone the repo and install dependencies, see https://sapper.svelte.dev/docs/#Getting_started
npx degit "sveltejs/sapper-template#rollup" sapper-with-ts-sample
npm i
```

To do a little testing, add the following to the top of `src/routes/index.svelte`:

```html
<script lang="typescript">
	export let title: string = "Hello TypeScript";
	// VS Code will show you an "Unexpected token" error; this is okay at this point
</script>
```

Replace

```html
<title>Sapper project template</title>
```

with

```html
<title>{title}</title>
```

Then install:

```sh
npm i svelte-preprocess typescript --save-dev
```

Create a new file `svelte.config.js` in the root folder with the following content:

```js
// See https://github.com/kaisermann/svelte-preprocess#with-svelte-vs-code
const sveltePreprocess = require('svelte-preprocess');

module.exports = {
	preprocess: sveltePreprocess({
		// ...svelte-preprocess options (optional)
	}),
	// ...other svelte options (optional)
};
```

Also create the TypeScript config file `tsconfig.json` in the root folder and copy and paste (and adapt it as you need it):

```json
{
	"include": ["src/**/*"],
	"exclude": ["node_modules/*"],
	"compilerOptions": {
		"target": "es2015",
		"module": "es2015",
		"types": ["svelte"]
	}
}
```

Edit `rollup.config.js` and make 3 insertions:

```js
// ...
import autoPreprocess from "svelte-preprocess"; // add this

export default {
	client: {
		plugins: [
			svelte({
				preprocess: autoPreprocess(), // add this

	// ...

	server: {
		plugins: [
			svelte({
				preprocess: autoPreprocess(), // add this
				// ...
			}),
	// ...
```

Restart VS Code (or which IDE you use). The "Unexpected token" error in your `src/routes/index.svelte` should have disappeared.

Run

```sh
npm run dev
```

Visit http://localhost:3000 in your browser.
Change the value of your `title` variable in `src/routes/index.svelte` to sth. else, save your file and test live reloading in your browser.

---

Maybe you already got everything you wanted. If you want to replace your `client.js`/`server.js` with its TypeScript counterpart, here are the next steps:

Install two more dependencies:

```sh
npm i rollup-plugin-typescript2 @types/node --save-dev
```

Adapt your `rollup.config.js` (3 inserted lines, 2 edited):

```js
// ...
import typescript from "rollup-plugin-typescript2"; // add

export default {
	client: {
		input: config.client.input().replace(/\.js$/, ".ts"), // edit here
      	output: config.client.output(),
      	plugins: [
       		// ...
        	commonjs(),
        	typescript(), // add after commonjs()
  	// ...
    server: {
      	input: config.server.input().server.replace(/\.js$/, ".ts"), // edit here
		output: config.server.output(),
		plugins: [
			// ...
			commonjs(),
			typescript(), // add after commonjs()
		// ...
```

Edit your `tsconfig.json`:

```json
...
"types": ["svelte", "node", "@sapper"], // add the last two to the existing types
"typeRoots": ["typings"] // add line
...
```

Create a new directory `/typings/@sapper` in the root folder and in `@sapper` create a file `index.d.ts`. Paste:

```ts
declare module '@sapper/app';
declare module '@sapper/server';
declare module '@sapper/service-worker';
```

Finally change the file suffix of the files `client.js` and `server.js` in the `/src` folder from `.js` to `.ts`. That's it, happy TypeScripting :)