typescriptsvelte

can't import from svelte module from typescript


I have a fairly large project, in which we are running typescript and svelte.

In the project we are running tsc and tsc-sctrict (which uses tsc under the hood I think) as a form of validation step, to make sure we aren't pushing something that is obviously broken (the 2 commands catch a lot of errors that, for example svelte-check doesn't)

The issue is, that it seems like typescript doesn't understand module export/imports.

Assume I have a Component.svelte

<script lang="ts" module>
    export function hello() {
        console.log("world");
    }
</script>

and a index.ts

import {hello} from "$lib/Component.svelte"

hello();

that is perfectly fine and valid from a svelte perspective, but typescript doesn't really understand it and throws errors

src/lib/index.ts:2:9 - error TS2614: Module '"*.svelte"' has no exported member 'hello'. Did you mean to use 'import hello from "*.svelte"' instead?

so is it possible to make typescript understand that type of import/export, or do I have to create a ts file that acts like the module script?


Solution

  • The answer is Not at present time. As seen, Svelte provides a TypeScript module definition for all .svelte files (*.svelte) that simply has no definitions in it. Until the day that the Svelte-provided tools are able to overcome this, I'd say you're out of luck.

    What's interesting, though, is that if you export all exports of a .svelte file through a .ts file, and have TS create definition files, then you get them properly listed. This is evident when you create NPM libraries for Svelte.

    If you're willing to go through this intermediate step, you might have a workaround in your hands.