DEV Community

Discussion on: Use TypeScript with Svelte / Sapper

Collapse
 
justinmoon profile image
Justin Moon

Is it possible to move the hello variable declaration to another typescript file?

I tried putting this in src/hello.ts:

export let title: string = "Hello, Typescript!"

But importing from index.svelte:

import { title } from "../hello"

Produces an error:

Could not resolve '../hello' from src/routes/index.svelte

But it works fine if I don't use .ts file ...

Collapse
 
mhaecker profile image
Markus Häcker

What you can do if you want to write your TypeScript code to an extra file:

Add this to your index.svelte:

<script src="src/hello.ts">
</script>

And in your src/hello.ts:

export let title = "Hello, Typescript!"
Collapse
 
kanmii profile image
Adekanmi Ademiiju • Edited

Hi Markus,
It did not work for me. I keep getting:

• client
/home/kanmii/projects/sapper-with-ts-sample/src/routes/index.svelte
'title' is not defined
38:
39: <svelte:head>
40:   <title>{title}</title>
              ^
41: </svelte:head>
42:
• server
/home/kanmii/projects/sapper-with-ts-sample/src/routes/index.svelte
'title' is not defined
38:
39: <svelte:head>
40:   <title>{title}</title>
              ^
41: </svelte:head>

Do you have a github repo I can clone demonstrating how to use typescript with svelte?

Collapse
 
j05j4 profile image
Josja Heerema • Edited

You can create a src/components/hello.ts file

export default "Hello dev";

And import it in src/routes/index.svelte with

<script>
    import title from '../components/title.ts';
</script>

Or in src/components/hello.ts:

export const title: string = "Hello developer";

with in src/routes/index.svelte:

<script>
    import {title} from '../components/title.ts';
</script>