Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import Typescript modules in Svelte Component

I have setup svelte-preprocess so I can do this successfully:

<script lang="typescript">
    let someConstant:string = "some constant";
    console.log({someConstant});
</script>

That works. But I don't know how to externalise that constant. If I try:

<script lang="typescript">
    import {someConstant} from './SomeTypescript.ts'
    console.log({someConstant});
</script>    

I get this error message:

error TS2691: An import path cannot end with a '.ts' extension. Consider importing './SomeTypescript' instead.

When I change it to

<script lang="typescript">
    import {someConstant} from './SomeTypescript'
    console.log({someConstant});
</script>

I get this error:

Error: Could not resolve './SomeTypescript' from src/tom/ManageAirtableModels.svelte

Whats the right way to do this?

like image 241
Mike Hogan Avatar asked Apr 25 '20 14:04

Mike Hogan


People also ask

How do you add a TypeScript in Svelte?

Once you have TypeScript configured, you can start using it from a Svelte component by just adding a <script lang='ts'> at the beginning of the script section. To use it from regular JavaScript files, just change the file extension from . js to . ts .

How do I use TypeScript modules?

A module can be created using the keyword export and a module can be used in another module using the keyword import . In TypeScript, files containing a top-level export or import are considered modules. For example, we can make the above files as modules as below. console.

How do I import a TypeScript file?

To import a class from another file in TypeScript: Export the class from file A , e.g. export class Employee {} . Import the class in file B as import { Employee } from './another-file' . Use the class in file B .

Is Svelte written in TypeScript?

Version 3 of Svelte is written in TypeScript and was released on 21 April 2019. It rethought reactivity by using the compiler to instrument assignments behind the scenes. The SvelteKit web framework was announced in October 2020 and entered beta in March 2021.


1 Answers

Install the rollup plugin for typescript to handle non-svelte files:

yarn add -D @rollup/plugin-typescript typescript tslib

Add plugin-typescript to your plugins list in rollup.config.js:

//....
import autoProcess from 'svelte-preprocess'
import typescript from '@rollup/plugin-typescript'

export default {
  ...
  plugins: [
    typescript(),

    svelte({
      preprocess: autoProcess(),
      ...
    })
    ...
  ]
}

Now import won't require a .ts extension:

<script lang="typescript">
    import {someConstant} from './SomeTypescript'
    console.log({someConstant});
</script>
like image 191
joshnuss Avatar answered Oct 09 '22 00:10

joshnuss