Svelte and TS + comlink

Domenik Reitzner - Aug 10 '20 - - Dev Community

The project

I have been trying stuff with svelte and doing some projects with it for a little over a year now. I have liked it from the start and still do and enjoy the simplicity and speed of it.

3 weeks ago I had the idea to do another little side project and build a guitar tuner with svelte (a svelte tuner if you'd like). I wanted it to look similar to my physical tuner that I use when I play live with my guitar.

Typescript

It was right around the time svelte started supporting typescript out of the box. So I thought to myself: "That is a nice project to start learning typescript". And I must tell you the transition was really easy (and even saved me from some bugs along the way).

Some problems that I encountered

  • share my interfaces among files
  • import svgs

Share interfaces

As a total beginner in ts I started out with exporting my interfaces instead of having them in my @types folder. I thought it might be worth mentioning for all those who start out with typescript 😉

import svgs

another thing that I encountered (in a different project) was when I tried importing svgs it gave me a ts error. The solution that I found, is to have an index.d.ts inside ./@types with the following:

declare module "*.svg" {
    const content: any;
    export default content;
}
Enter fullscreen mode Exit fullscreen mode

Using comlink

I have heard about comlink in some js youtube tutorial and wanted to try it out for the longest time. With raw audio processing this seemed to be the perfect fit to run the task off the main thread.
It was really easy to integrate (also with typescript).

MyComponent.svelte => script

import * as Comlink from "comlink";

const worker = new Worker("/myWorker.js");
const instance: Comlink.Remote<IWorkerConstructor> = Comlink.wrap(
  worker
);
const localInstance = await new instance();

...

const result: number = await localInstance.calculateNumber()

Enter fullscreen mode Exit fullscreen mode

myWorker.js

import * as Comlink from "comlink";

class Worker implements IWorker{
    calculateNumber() {
        return Math.random();
    } 
}

Comlink.expose(Worker);

Enter fullscreen mode Exit fullscreen mode

The syntax is really easy and provides a powerful enhancement to apps that run expensive calculations.

Conclusion

Integrating workers with comlink into apps, that do some calculations keeps the main thread healthy especially on low end devices (which more and more people are using these days).
Also using ts with svelte seems a really powerful combination, without loosing its simplicity. I guess this will further cement svelte's position in it's approach to an awesome development experience.

So, try stuff out, have fun and enjoy web deving 🎉

Links:

My music:

. . . . . . . . . . . . . . . .
Terabox Video Player