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?
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 .
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.
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 .
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With