Svelte Won't Allow Me to Use an Exported Enum (TypeScript) in the Component Body

Viewed 1467

I have the following code...

<script lang="ts">
    import { TToken } from "./global.d";
    const value:TToken = TToken.X;
</script>
{#if value == TToken.X}
    Hi There!
{:else}
    I don't like you
{/if}

And here's global.d.ts:

/// <reference types="svelte" />
export enum TToken {
    X = 'X',
    O = 'O',
    Blank = ' '
}

When I run npx svelte-check, it finds no errors. But when I try to run svelte via npm run dev, I get the following:

rollup v2.56.2
bundles src/main.ts → public\build\bundle.js...
[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
src\global.d.ts (2:7)
1: /// <reference types="svelte" />
2: export enum TToken {
          ^
3:     X = 'X',
4:     O = 'O',
Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
    at error (C:\svelte-test\node_modules\rollup\dist\shared\rollup.js:151:30)
    at Module.error (C:\svelte-test\node_modules\rollup\dist\shared\rollup.js:10059:16)
    at Module.tryParse (C:\svelte-test\node_modules\rollup\dist\shared\rollup.js:10462:25)
    at Module.setSource (C:\svelte-test\node_modules\rollup\dist\shared\rollup.js:10365:24)
    at ModuleLoader.addModuleSource (C:\svelte-test\node_modules\rollup\dist\shared\rollup.js:19708:20)
    at ModuleLoader.fetchModule (C:\svelte-test\node_modules\rollup\dist\shared\rollup.js:19764:9)
    at async Promise.all (index 1)
    at ModuleLoader.fetchStaticDependencies (C:\svelte-test\node_modules\rollup\dist\shared\rollup.js:19790:34)
    at async Promise.all (index 0)
    at ModuleLoader.fetchModule (C:\svelte-test\node_modules\rollup\dist\shared\rollup.js:19766:9)

I googled and found people reporting similar issues, but none of the resolutions I found applied to my case. For instance, one person said the issue was that plugins and watch needed to be outside output in the rollup, but that was already the case for me.

Removing the export will of course cause svelte-check to fail.

Does anyone know the resolution to this issue? I need to be able to have my enums in separate files, so I can't declare it in the component.

Thanks!

1 Answers

Since you are already using typescript in your project you can directly use a simple .ts file. You often see a types.ts for example:

// types.ts

export enum TToken {
    X = 'X',
    O = 'O',
    Blank = ' '
}

Rollup is then able to generate for you the needed .d.ts files for the non typescript projects.

It does not work with a d.ts file because d.ts files have no runtime equivalent - they only exist at compile time for type checking. .ts files however are transpiled to .js files which your dev server/rollup will find.

Related