Is TypeScript capable of comprehending Svelte components?

When it comes to Svelte, the final output is native JavaScript classes, which TypeScript can understand. However, before TypeScript can recognize Svelte components, they must first be compiled from their initial .html form. This can lead to a 'cannot find module' error in TypeScript, even though the import works at runtime. Is there a way for TypeScript to better understand Svelte components?

One potential solution could involve creating type definitions for .html modules that mimic the standard Svelte component interface. But ideally, using the actual output of the component class would provide the most accurate type information for each individual component.

It's worth noting that popular tools like Webpack or Rollup typically handle the compilation process for Svelte. It's unclear if these tools play a role in addressing this specific issue.

Update 1: Upon further investigation, it appears that plugins can be developed for TypeScript according to official documentation. However, the limitations of these plugins may hinder their usefulness in this context.

Update 2: Discussions have emerged regarding custom module loaders in TypeScript, as seen in threads here and here.

Answer №1

Absolutely. Utilize rollup-plugin-svelte along with rollup-plugin-typescript and it should function properly. I currently have it set up in a rollup file that appears like this:

import commonjs from 'rollup-plugin-commonjs'
import replace from 'rollup-plugin-replace'
import resolve from 'rollup-plugin-node-resolve'
import svelte from 'rollup-plugin-svelte'
import typescript from 'rollup-plugin-typescript'

const path = require('path')
const fs = require('fs')

export default {
  input: 'src/index.ts',
  plugins: [
    typescript(),
    commonjs({
      include: 'node_modules/**'
    }),
    resolve({
      browser: true,
      preferBuiltins: false // for url npm module; otherwise rollup assumes node
    }),
    // Replace is to shut up redux
    replace({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    }),
    svelte({
      // By default, all .html and .svelte files are compiled
      extensions: ['.my-custom-extension', '.html', '.svelte'],

      // You can restrict which files are compiled
      // using `include` and `exclude`
      // include: 'src/components/**/*.html',

      // By default, the client-side compiler is used. You
      // can also use the server-side rendering compiler
      // generate: 'ssr',

      // Extract CSS into a separate file (recommended).
      css: function (css) {
        fs.writeFileSync('./dist/svelte.css', css)
      }
    })
  ],
  output: {
    format: 'iife',
    file: path.join(__dirname, './dist/index_dist.js') // equivalent to --output
  }
}

Answer №2

Absolutely. Svelte fully embraces TypeScript! Learn more about using TypeScript with Svelte here.

When initiating a new project,
consider using Vite by running npm create vite@latest
or opt for SvelteKit and run npm create svelte@latest
Make sure to select the TypeScript option when prompted.

The Svelte ESLint plugin is also compatible with TypeScript, find installation instructions in the Readme.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When an empty array is returned from a catch statement in an async/await method, TypeScript infers it as never

Function getData() returns a Promise<Output[]>. When used without a catch statement, the inferred data type is Output[]. However, adding a catch statement in front of the getData() method changes the inferred data type to Output[] | void. This sugge ...

How do I implement branch code using TypeScript types in Svelte?

Looking for a solution similar to the one mentioned in Typescript: How to branch based on type, but tailored for Svelte. Despite implementing run-time type guards as suggested, Svelte continues to throw errors. I am dealing with an array called collectabl ...

The NGINX reverse proxy fails to forward requests to an Express application

I am currently in the process of setting up a dedicated API backend for a website that operates on /mypath, but I am encountering issues with NGINX not properly proxying requests. Below is the nginx configuration located within the sites-enabled directory ...

Creating TypeScript modules for npm

I have been working on creating my first npm module. In the past, when I used TypeScript, I encountered a challenge where many modules lacked definition files. This led me to the decision of developing my module in TypeScript. However, I am struggling to ...

Encountering difficulties in loading my personal components within angular2 framework

I encountered an issue while trying to load the component located at 'app/shared/lookup/lookup.component.ts' from 'app/associate/abc.component.ts' Folder Structure https://i.stack.imgur.com/sZwvK.jpg Error Message https://i.stack.img ...

Creating a regular expression to capture a numerical value enclosed by different characters:

export interface ValueParserResult { value: number, error: string } interface subParseResult { result: (string | number) [], error: string } class ValueParser { parse(eq: string, values: {[key: string] : number}, level?: number) : ValueParse ...

To properly display a URL on a webpage using Angular, it is necessary to decode

After my console.log in Angular 5 service call to the component, I can see the correct data URL being displayed http://localhost:4200/inquiry?UserID=645 However, when it is inside an Angular for loop in the HTML template, it displays http://localhost:42 ...

The React Native blob or file seems to be encountering trouble in reaching the server

I'm in a tough spot here. I can't figure out what's going wrong. My goal is to send a file using the expo-image-picker component to the server. The form gets sent, but the image doesn't. When I use the fetch command, I immediately get a ...

Angular typed controls allowing for a seamless user experience without the need to

Currently, I am in the process of updating some older forms to include stronger typing in order to address eslint errors. One recurring issue I have encountered is when using the .value operator on abstract controls, it causes an error in my IDE stating "U ...

How to implement a custom pipe for dynamically changing image URLs in Ionic 3's image tag

I am trying to set authentication headers for images called from an image tag (<img>). To achieve this, I have created a custom pipe named secureimages using the command ionic g pipe secureimages. This pipe intercepts the HTTP requests in an interce ...

Unit testing for Angular service involving a mock Http GET request is essential for ensuring the

I am seeking guidance on how to test my service function that involves http get and post calls. I attempted to configure the spec file by creating an instance of the service, and also consulted several sources on creating a mockhttp service. However, I enc ...

Issue encountered: NPM error, unable to find solution for resolving dependency and addressing conflicting peer dependency

I am facing difficulties deploying my project on netlify due to NPM errors. Below are the dependencies: "dependencies": { "@angular/animations": "~15.1.1", ... (list of dependencies continues) ...

Exploring Typescript for Efficient Data Fetching

My main objective is to develop an application that can retrieve relevant data from a mySQL database, parse it properly, and display it on the page. To achieve this, I am leveraging Typescript and React. Here is a breakdown of the issue with the code: I h ...

An error should not be thrown if the object is potentially 'undefined', as there is a filter in place from rxjs

During my service refactoring process, I encountered a frustrating issue. The API I am working with returns an object with various optional properties. To work with these properties, I need to check if they are undefined or not using an if statement, other ...

What methods are available to pass a variable value between two components in Angular 2?

I've been experimenting with Angular2 and recently created a component called appmenu using angular cli. The code in appmenu.html looks like this: <ul> <li (click)="menuitem1()">Menu Item 1</li> <li>Menu Item 2</li> ...

Utilize SCSS values within TypeScript by applying them on a class level

let changeClassDisplay = document.getElementsByClassName('sidebar'); for (var i = 0; i < changeClassDisplay.length; i += 1) { changeClassDisplay[i].style.display = 'block'; } I encountered an issue with this code whe ...

"What are the benefits of utilizing Dependency Injection tokens within Angular 4 and when is the ideal time to implement

I have been exploring the concept of using InjectionToken for injecting environment variables (plain objects) into a service. I find myself puzzled as to the reasons and methods for incorporating tokens in Dependency Injection. Despite my efforts to resear ...

Defining types for functions that retrieve values with a specified default

My method aims to fetch a value asynchronously and return it, providing a default value if the value does not exist. async get(key: string, def_value?: any): Promise<any> { const v = await redisInstance.get(key); return v ? v : def_value; } W ...

Having trouble with React Hook Form controlled input and typing

My application utilizes the react-hook-forms library along with the office-ui-fabric-react framework. To integrate the framework inputs, I wrap the 3rd party component using the <Controller> element. The current setup is functional as shown below: ...

Angular 6 and the intricacies of nested ternary conditions

I need help with a ternary condition in an HTML template file: <div *ngFor="let $m of $layer.child; let $childIndex=index" [Latitude]="$m.latitude" [Longitude]="$m.longitude" [IconInfo]="$childIndex== 0 ? _iconInfo1:$c ...