Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we write typescript inside a svelte component?

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?

like image 278
Imraan Khan Avatar asked Jul 15 '19 06:07

Imraan Khan


People also ask

Should I use TypeScript with SvelteKit?

You probably don't need TypeScript directly to profit from a strong type-checking experience inside your Svelte and SvelteKit applications. VS Code and the Svelte extension can also offer help if you annotate your components with JSDoc comments.

What is $$ in Svelte?

Svelte will generate the code to automatically update them whenever data they depend on is changed. Note: Svelte uses the $: JavaScript label statement syntax to mark reactive statements. Just like the export keyword being used to declare props, this may look a little alien.

What is the Svelte compiler written in?

The compiler itself is written in TypeScript. Its source code is licensed under MIT License and hosted on GitHub.


1 Answers

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 })
  ]
}
like image 55
sudo bangbang Avatar answered Oct 28 '22 11:10

sudo bangbang