12
votes

Is it possible to write Typescript inside the script tag in a svelte component?

I came across https://github.com/pyoner/svelte-typescript/tree/master/packages/preprocess Which if I understand correctly is a typescript preprocessor for svelte which would allow to write typescript in svelte components. However I am not able to get it working

This is how my rollup config looks like

import svelte from "rollup-plugin-svelte";
import resolve from "rollup-plugin-node-resolve";
import replace from "rollup-plugin-replace";
import commonjs from "rollup-plugin-commonjs";
import serve from "rollup-plugin-serve";
import livereload from "rollup-plugin-livereload";
import copy from "rollup-plugin-copy";
import typescript from "rollup-plugin-typescript2";
import { terser } from "rollup-plugin-terser";

import {
  preprocess,
  createEnv,
  readConfigFile
} from "@pyoner/svelte-ts-preprocess";

const tsEnv = createEnv();
const compilerOptions = readConfigFile(tsEnv);
const opts = {
  env: tsEnv,
  compilerOptions: {
    ...compilerOptions,
    allowNonTsExtensions: true
  }
};

const env = process.env.NODE_ENV;

const production = env ? env === "production" : false;
const distFolder = "dist";

export default {
  input: "src/index.ts",
  output: {
    sourcemap: !production,
    format: "iife",
    name: "app",
    file: `${distFolder}/bundle.js`
  },
  plugins: [
    replace({
      "process.browser": true,
      "process.env.NODE_ENV": JSON.stringify(env)
    }),
    svelte({
      // enable run-time checks when not in production
      dev: !production,
      // we'll extract any component CSS out into
      // a separate file — better for performance
      css: css => {
        css.write(`${distFolder}/bundle.css`);
      },
      preprocess: preprocess(opts)
    }),

    // If you have external dependencies installed from
    // npm, you'll most likely need these plugins. In
    // some cases you'll need additional configuration —
    // consult the documentation for details:
    // https://github.com/rollup/rollup-plugin-commonjs
    resolve({
      browser: true,
      dedupe: importee =>
        importee === "svelte" || importee.startsWith("svelte/")
    }),
    commonjs(),
    typescript({
      tsconfig: "tsconfig.json",
      objectHashIgnoreUnknownHack: true,
      clean: production
    }),

    // Start dev server if not in production mode
    !production &&
      serve({
        open: true,
        contentBase: distFolder,
        historyApiFallback: true,
        host: "localhost",
        port: 7000
      }),

    // Watch the `dist` directory and refresh the
    // browser on changes when not in production
    !production && livereload(distFolder),

    // If we're building for production (npm run build
    // instead of npm run dev), minify
    production && terser(),
    copy({
      targets: [{ src: "public/**/*", dest: `${distFolder}` }]
    })
  ],
  watch: {
    clearScreen: false
  }
};

I am not sure If I have configured this incorrectly or if it is not possible at all to write typescript in svelte?

6
I didn't try this but give it a shot npmjs.com/package/svelte-preprocessunloco

6 Answers

8
votes

Yes. Svelte has official support for typescript! https://svelte.dev/blog/svelte-and-typescript

The starter template comes with a setupTypeScript.js utility: https://github.com/sveltejs/template#using-typescript

At this time it doesn't work in combination with eslint, but that is being worked on

5
votes

Yes you can

This is an example of svelte + typescript + rollup

And this is an exampl of svelte + typescript + parcel

4
votes

Svelte has official documentation about Typescript support.

Basically, you can add lang="ts" to your script block and svelte preprocessor will take care of compiling

<script lang="ts">
  export const hello: string = 'world';
</script>

You can start a new Svelte TypeScript project using the normal template and by running node scripts/setupTypeScript.js before you do anything else:

npx degit sveltejs/template svelte-typescript-app
cd svelte-typescript-app
node scripts/setupTypeScript.js

To add Typescript to existing projects,

npm install --save-dev @tsconfig/svelte typescript svelte-preprocess svelte-check

Add tsconfig.json at the root of your project

{
  "extends": "@tsconfig/svelte/tsconfig.json",

  "include": ["src/**/*", "src/node_modules"],
  "exclude": ["node_modules/*", "__sapper__/*", "public/*"],
}

If you're using Rollup, add the lines with + to rollup.config.js

+ import autoPreprocess from 'svelte-preprocess';
+ import typescript from '@rollup/plugin-typescript';

export default {
  ...,
  plugins: [
    svelte({
+       preprocess: autoPreprocess()
    }),
+   typescript({ sourceMap: !production })
  ]
}
1
votes
0
votes

You can try to use the next template by npx degit

https://github.com/Zimtir/ST-template

Look at README.md file

0
votes

It is possible to write ts in the svelte component's script. There are official templates available with snowpack, vite, and other build tools. You could also build it on your own with svelte-preprocess and typescript plugin/loader for the respective build tool.