typescriptimportsveltedeclaration

Why do I need to use the "type" keyword when importing types in Svelte?


I'm coming from the React world, and I'm trying to learn Svelte 5.

Suppose I have the following file:

// types.ts

export interface Person {
    name: string;
}

In React, I can import the Person declaration as:

// Component.tsx

import {Person} from './types';

function Component() {
    return <></>;
}

But in Svelte, I need to use the type keyword in the declaration:

// Component.svelte

<script lang="ts">
import type {Person} from './types';
</script>

If I don't use type I see an error:

// Component.svelte

<script lang="ts">
import {Person} from './types';
</script>
The requested module 'http://localhost:8080/src/types.ts'
  doesn't provide an export named: 'Person'

Why is type needed?

Is there any configuration I can do to lift this requirement?


Solution

  • Why is type needed?

    So the pre-processor can tell that this an import that needs to be removed. If the import is not removed, it will not be valid since the types just don't exist at runtime.

    There used to be a TS config option to easily enforce this: "importsNotUsedAsValues": "error"

    This could be combined with various other flags which was hard to understand, so those have been replaced with verbatimModuleSyntax, the documentation of this option also explains the problems with processing of imports in great detail.

    Is there any configuration I can do to lift this requirement?

    No.

    Svelte files are currently processed in isolation and the types are only stripped not analyzed, so the tools need to be told what is a value and what is a type.