24 ms·
Svelte and TypeScript
- swyx 6y agothis has been eagerly anticipated for so long and is probably the #1 stated reason why people haven't tried out Svelte yet. so glad this is out!
- outime 6y agoIt definitely was my #1 reason and I'm happy to see this announcement. I'll check Svelte out soon as it already looked quite promising to me.
- untog 6y agoVery happy about this. I tried to combine the two a few months ago and it was not a fun experience. Great to know I can give it another go now.
- fb03 6y agoI was literally searching for this like, a week ago. Glad to finally see it land in a stable, first-class manner.
- nickreese 6y agoHaving talked to a ton of friends about Svelte, Typescript support has always been the biggest push-back for adoption. Stoked for Svelte to support it. We've been using Svelte in production and I can't speak highly enough about the developer experience. Absolute game changer for our ssite that use it.
- The_rationalist 6y agoWhat would it bring in ergonomics and expressivity versus Vue ?
- kjksf 6y agoThose things really need to be experienced to be understood, so just try Svelte in a toy project. Or go through the interactive tutorial https://svelte.dev/tutorial/basics https://svelte.dev/tutorial/basics I used both React and Vue and am now only using Svelte. You type less. Significantly less. The thing you type is simpler. I tend to get lost in Vue's object structure. What you type is closer to HTML/CSS/JavaScript than what you type in React/Vue. It's therefore easier to understand what gets generated. The seamless reactivity is awesome. Scoped CSS support is built-in so you don't need css-in-js hacks. Built-in support for data (stores) is excellent. The final bundle is smaller and faster. There's more but the above are the major points. The only downside is smaller ecosystem. But I don't care because I'm in the camp of minimizing my dependencies.
- preommr 6y ago> Scoped CSS support is built-in so you don't need css-in-js hacks. vue/react also have scoped css, but built into the building process using loaders rather than being a feature of the frameworks.
- buzzerbetrayed 6y agoLess time setting up build processes is another win you git with Svelte, in my experience.
- nickreese 6y agoI haven't used Vue extensively since what was probably v1 so I'm likely the wrong person to comment on this. That said, I find that Svelte aligns more with my/our team's mental model about how the web should work and that is why went with it for our sites. Just like with Vue you can write your JS/CSS/HTML in a single file, but the reactivity and state management is much easier to reason about than what we've seen elsewhere. - `$:` is great. - Stores and derived stores are amazing. - Data binding / rerendering is really intuitive. That said, the biggest headache in building our own SSG was getting SSR/Hydration working well, but that was mainly fighting Webpack and got easier when we went with Rollup. edit: formatting.
- G4BB3R 6y agoDo you use pure svelte or with sapper? how is it compared to react?
- nickreese 6y agoWe wrote our own SSG for https://elderguide.com https://elderguide.com. We tried Sapper but our data flow and routing needs were to complex and not a fit. Svelte is a dream compared to React. That said, I've never felt like React was the right solution for the problem. I've extensively used Gatsby and for static sites, React is absolutely overkill. For apps it can be nice. In both cases my go-to these days is Svelte.
- uxcolumbo 6y agoNice site and real snappy. I haven't used Svelte yet - but am interested. Can you explain a bit more about what you mean with your data flow and routing needs were too complex for Sapper. And what makes Svelte a dream compared to React?
- nickreese 6y agoSapper's data flow uses a file based routing system similar to /blog/[id].svelte becomes /blog/:id/. If you are familiar with Next.js then you'll recognize this. Our primary problem with Sapper is that we wanted our URL structure to be such that you can't tightly route a template/view by just looking at their URL. /senior-living/blog-post/ and /senior-living/nursing-home-name/ need to live side-by-side. This forced us to build our own custom routing system, what we call an "inverted router" for our SSG. Also we found it less than elegant to use DB queries with Sapper and had a lot of concerns about what was actually on the client and what wasn't. As for why we swear by Svelte: * Bundle size. For SEO focused sites React is overkill. * Stores compared to Mobx or other state management * $: reactivity * No css-in-js hacks required. Css is automatically scoped, but can be easily globally scoped. * Single file components are just beautiful. * We've built in the ability to SSR our entire site, but only hydrate the parts that need to be. This is a game changer for page size and not pushing your data twice to the client.
- rawoke083600 6y agoI LOVEE Svelte, if your any sort of dev... try it out. It's a super small API, you can learn in a few hours. I'm not a frontend dev by trade, but compared to Angular(prev fav) it's soo much simpler.
- Vinnl 6y agoIt's really telling that, for every big project that does not support TypeScript, the number 1 feature request is TypeScript support. (And consequently, that there are fewer and fewer such projects.)
- swyx 6y agoindeed we are in a new age of javascript now. one where TS support is (in practice) not optional. https://www.swyx.io/writing/js-third-age/ https://www.swyx.io/writing/js-third-age/
- novok 6y agoMight as well make it part of the language officially and get rid of the need for transcompliers.
- kylemh 6y agolaughs in browser compat
- mekster 6y agoNot going to happen anytime soon as people will take forever to upgrade to browsers that may support TS natively. Stick with transpilers and you're good to go from today. There's also deno for node.js alternative that supports TS natively but not sure of its future.
- hajile 6y agoWe really need a "use types" mode. Instead of trying to support all the super-dynamic parts of JS, those parts should just go away in typed mode. Unlike TS, the type system should be sound. Hindley-Milner with immutable by default and options instead of null with structural typing everywhere and typeclass module definitions. I guess that's just StandardML with JS syntax, but that would be an amazing language to work with -- far better than either TS or ReasonML.
- 6y ago
- The_rationalist 6y agoHow is Webstorm support with Svelte ?
- mrath 6y agoI believe there is no official plugin for Svelte. So it may not be as good as the support for React/Angular/Vue. But once Svelte is a bit more popular, I think JetBrains will release a plugin.
- lurker42 6y agoyou can use the LSP and get most things working.
- BMorearty 6y agoNot bad. I’ve been using the Svelte plugin by Tomasz Błachut. But I don’t think the plugin supports TypeScript yet.
- wirahx 6y agoEasier, due to the language-server Svelte uses to support TypeScript. It should be relatively trivial for somebody to implement now.
- drol3 6y agoGreat news! Was my only blocker :)
- dboreham 6y agoSwitching from JS to Typescript was like moving from machine code to C. Note: machine code (hex) not assembler.
- DaiPlusPlus 6y agoJavaScript is getting more “typed” anyway - what with Promises and other objects/interfaces in the DOM being conceptually statically typed - where JavaScript’s type-juggling simply can’t help you - so writing JavaScript today against modern browser/NodeJS APIs feels like writing VBScript against ActiveX instead of writing in VBA/VB6: you can do essentially the same things, but you have no idea if your program will actually work or not. It would not surprise me if the ECMAScript folks just throw in the towel and adopt TypeScript into ECMAScript as its official type-annotation feature - like how Python is doing - except without the duplication of effort.
- zamalek 6y agoI've been using Svelte TS for a pet project for maybe 2 weeks now. It's fantastic. The VSCode plugin is also doing a great job. I tried, and failed, to use Babel as the TS compiler - but TSC then Babel works just fine.
- zeroc8 6y agoWould love to use it, but I need something comparable to PrimeNG. Are there any comprehensive UI toolkits out there already?
- widgetic 6y agoSome - https://awesomeopensource.com/project/ryanatkn/awesome-svelte-resources#ui-component-sets https://awesomeopensource.com/project/ryanatkn/awesome-svelt...
- seanwilson 6y agoAre the HTML templates type checked as well? I'm playing with Vue version 3 with TypeScript using JSX instead of the usual HTML templates and pretty happy that it's all type checked. I have a similar project without JSX and the vast majority of the bugs are related to the logic in the HTML templates not being type checked.
- dlbucci 6y agoThis has been my experience with AngularJS 1 and TypeScript as well. Looks like there's at least some support for it (Quote the link: You get autocompletion hints and type-checking as you're writing components, even in expressions inside markup). Not sure if it does things like restrict `value` to `input` elements or anything, or if it's just the expressions in the template.
- smt88 6y agoTry using Vue in WebStorm with their Vue plugin enabled, or use TSX with any IDE. Your "HTML" will be type-checked.
- joshstrange 6y agoHmm, I'm going to have to take another look at this then because I get auto-complete of variable properties in my html (IDEA + Vue plugin) but I don't get warnings about a variable possibly being null or undefined. But that may be outside the realm of possibility to check easily.
- smt88 6y ago> But that may be outside the realm of possibility to check easily. It depends. If you type-check your runtime input (e.g. form fields) then it works well.
- raihansaputra 6y agoVue with TS, on VSCode and Vetur, with Vetur Template Interpolation enabled (VTI) also typechecks the template.
- swyx 6y agoHere are some tutorials from community members who knew this was coming: - 3 min youtube demo: https://www.youtube.com/watch?v=djRkyyBoIKs&feature=youtu.be https://www.youtube.com/watch?v=djRkyyBoIKs&feature=youtu.be - 3 min eggheadio lesson: https://egghead.io/lessons/svelte-create-a-new-svelte-project-with-typescript-support https://egghead.io/lessons/svelte-create-a-new-svelte-projec... - TS + Sapper: https://mrsauravsahu.github.io/blog/38/ https://mrsauravsahu.github.io/blog/38/
- vosper 6y agoLack of Typescript support was the main reason I didn't switch to Svelte for my personal projects. Other than that it was a joy to use, and a breath of fresh air in it's approach. I'd recommend any front-end dev to give Svelte a try, even just spending an hour or two messing around, to experience a way of developing web apps that's likely a bit different to what you're used to, but feels familiar enough that it doesn't require a big mental leap.
- wry_discontent 6y agoI feel like the odd man out in discussions like these. I don't like Typescript and I regret pushing to integrate it into a project at work. I've found it vastly increases incidental complexity and affords little to no benefit to me. The IDE completions are nice, but ultimately not worth the price, in my humble and honest opinion.
- ipnon 6y agoHow large is your TypeScript project? What were your type issues before you integrated? My work has benefited from TypeScript because we can now propagate changes to our unstable API throughout our medium sized application using the compiler. We are fairly certain that all of our components are integrated if the compiler is silent. Before this certainty, we would frequently push broken API integrations to production. The complexity of TypeScript doesn't seem to benefit projects that are already clean and tested. TypeScript gave us some confidence of correctness when we had disorganized code and inadequate test coverage.
- wry_discontent 6y agoIt's about 20kloc. I encounter seemingly nonstop opaque type errors that come usually when I upgrade TS versions. I'll stipulate this was mostly written when we decided to add TS, and I was new to TS when I added it, but I tried really hard. As an example, it took me a full week to properly add type definitions to a HOC, and I had to rope in a couple other engineers across that time who had more TS experience. Eventually I got it working, but decided to deprecate the HOC cause the file exploded from being about 50loc to well over 250.
- treve 6y agoThe last large project I added Typescript, it took several weeks to add types. It took another year to learn how to write code in a way that is more likely to be successful in Typescript. If you have a ton of state, classes, high coupling and a lot of variance in your data structures (which Javascript really easily allows), Typescript is not an instant game-changer. This is not that different from having good test coverage is easier during development than adding it later, as you will end up writing your code in a way that makes things more decoupled and testable. It was way easier to get to that sweet spot with our Node.js code vs. our React code. React code is still more of a battle than non-React code, although functional components has made this better. Class based components suck the most and we just opt for using "any" instead of fighting it. Don't get me started about HoC.
- jedimastert 6y agoI am a (very) hobbyist web dev, almost always working with vanilla HTML+JS. I seeing a while lot of people here who are saying that Typescript is an absolute must. As someone who has no clue, and with all do respect, why would TypeScript be worth moving from just hitting save to introducing a build system and dependencies?
- gameswithgo 6y agoin your use case it probably isn’t worth it. if you get a bigger project where you are using webpack and npm already, maybe it would be.
- xupybd 6y agoHobby projects are served very well by js. Commercial ones not so much. Big teams with a mix of Personalities mean you get lots of errors and problems organising code. Typescript makes that a little more manageable.
- acemarke 6y agoI talked extensively about the pros, cons, and tradeoffs in my post "Learning TypeScript as an App Dev and Library Maintainer": https://blog.isquaredsoftware.com/2019/11/blogged-answers-learning-and-using-typescript/ https://blog.isquaredsoftware.com/2019/11/blogged-answers-le...
- runarberg 6y agoI have been using TypeScript in JS[1] mostly seamlessly. Types are annotated using doc comments above the thing your annotating. It is a bit hard to define complex types. E.g. I couldn’t for the life of me annotate the return value of the pipe function: function pipe(init, ...ops) { return ops.reduce((acc, op) => op(acc), init) } For these instances they suggest writing a declaration file[2]. However I have found the documentation isn’t really clear on this usecase (in fact I find the documentation of TypeScript somewhat lacking in general). But overall getting these typehints into my editor environment has been worth it. And I haven’t had to sacrifice the save → run workflow. 1: https://www.typescriptlang.org/docs/handbook/type-checking-javascript-files.html https://www.typescriptlang.org/docs/handbook/type-checking-j... 2: https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html https://www.typescriptlang.org/docs/handbook/declaration-fil... EDIT: An example annotated JS file for typescript: https://github.com/runarberg/strawberry-router/blob/master/src/elements/router-view.js https://github.com/runarberg/strawberry-router/blob/master/s... `npm run check` just runs typescript’s type checker, there is no compile step.
- leejoramo 6y agoUnlike many who have not used Svelte due to lack of Typescript support, this may give my team reason to consider Typescript.
- kylemh 6y agoNow I'm just waiting for some company to actually make an app with Sapper and Svelte and I'll give this a go.
- rawoke083600 6y agoLol I've made two :) [0]https://www.fibretiger.co.za https://www.fibretiger.co.za The above was previously coded in angular 9. I've seen faster loads in CoreWebVitals, and strangely... more of our post got featured in Google-Discover(could just be coincidence) [1]https://www.wepickflix.com https://www.wepickflix.com
- wirahx 6y agohttps://beyonk.com https://beyonk.com Everything we do is written in Svelte + Sapper, not just our site, but all the backend apps as well that we use for admin + providers.
- aabbcc1241 6y agoIn my previous experience of "Svelte with Typescript", it merely remove the typings, no type checking at all. Try in below example, it print out '12' without type related error message. <script lang="ts"> let a: number = '1'; let b: number = 2; </script> <p> c = {a + b} </p>
- aabbcc1241 6y agoAnother direction of using typescript based DSL languages that compiles to svelte code seems more maintainable. Checkout https://github.com/mistlog/svelte-draft https://github.com/mistlog/svelte-draft
- cetra3 6y agoI've just tried this using the starter project they provide in the blog post, and it does catch the error: The error returned is `Type '"1"' is not assignable to type 'number'.`
- aabbcc1241 6y agoThanks for pointing out. It's getting better overtime! I missed the existence of "svelte-check". I expected to see errors on the webpage like we usually see from angular/react/stencil. On svelte, the typescript error doesn't show up until you manually run svelte-check.
- benmccann 6y agoThe VS Code extension will surface type checking errors for you or if you want to surface them on the command line you can run https://www.npmjs.com/package/svelte-check https://www.npmjs.com/package/svelte-check
- aryonoco 6y agoRich Harris (the creator of Svelte) just released a short 5 hour video course on Svelte on Frontend Masters as well. It's great intro and touches most common usecases and briefly introduces Sapper as well. If you already have a FEM subscription, this is a great time to get into Svelte.
- nXqd 6y agoYes, finally.
- JadoJodo 6y agoSlightly off-topic but I'm curious anyway: Has the tooling for JavaScript improved with TypeScript's adoption? As a back-end developer, I feel like each time I've tried to dig in and start a JavaScript project from scratch has ended with me weeping after spending four hours fighting the tooling. Is there a better way?
- tmpz22 6y agoIMO the issue has to do with linting and editors i.e. "how do I make the yellow squigglies go away" or silent compiler warnings in the console due to several layers of default linting rules again applied by your editor, or your React CLI, or your operating systems package manager. These are very unsexy problems that nobody has been able to solve over the past 5 years because ultimately they are opinionated.
- symlinkk 6y agoJust use create-react-app, it’s not hard.
- crooked-v 6y agoI'd personally recommend Next.js instead. It's even more painless, seamlessly handles a lot of other concerns (like routing), and can be used both as an SSR server and to generate purely static HTML bundles.
- qudat 6y agoIt's about the same as any other service, the only difference is every web app needs js. Try jumping into a python web service and talk to me about weeping from terrible tooling.
- hath995 6y agoI start all my server side projects in TypeScript lately. There is enough support that it is actually very easy to get started. ts-node, npm @types, and many packages natively supporting ts help. The browser is a crazy environment and adds difficulty, but I find my server code can very strictly typed. The nodejs type definitions are good and if you pick an ORM library with good typescript support then both the in memory data structures and database objects can be well typed. The build step with typescript is basically negated by ts-node for the server. Alternatively, by using tsc --watch and some clever indirection I've enabled hot reloading for most of my server code. So just to be clear, I have types helping me code using vs-code, I save and immediately see changes on the server. If you know the tools well and how to set things up then TS + node can provide a better developer environment than many languages.
- orange8 6y ago> I get almost as much benefit from the rigorous null checking in TS as I do from the typing. I would use it for that alone. [1] This. I suspect there is a certain way those who rave about TS like yourself write and structure their code (all code, regardless of language) in a way that naturally lends itself to strict typing. The "rigorous null checking" comment struck me as odd, as someone who has written JS for almost 20 years, I've just never had to think about, or use null values. I probably just use the good parts of the language and avoid the bad [2] [1] https://news.ycombinator.com/item?id=23913294 https://news.ycombinator.com/item?id=23913294 [2] https://www.oreilly.com/library/view/javascript-the-good/9780596517748/ https://www.oreilly.com/library/view/javascript-the-good/978...
- spion 6y agoYou can't avoid null and undefined in your code unless you avoid almost every language feature. Two particularly common ones: * Accessing a missing property or method results with undefined. Hope you remember the exact method names and field names of all objects in your codebase! * Using "str".match(regex) results with null if there are no matches.
- orange8 6y ago> You can't avoid null and undefined We are speaking about just null, not "null and undefined". Believe it or not, I simply do not use null in JS. Study the concept of "truthy and falsy" in JS. > Accessing a missing property or method results with undefined. Hope you remember the exact method names and field names of all objects in your codebase! I don't. I do however structure my code predictably, using consistent naming conventions and patterns. I hope you do realize JS existed for over 20 years before TS, and complex apps like gmaps and google docx were built entirely in JS. > Using "str".match(regex) results with null if there are no matches. const match = /bar/.exec("str"); if( match ){ // am only interested in what happens if foo returns a *truthy* result. // The exact type of a falsy result is irrelevant, it either matches (truthy) or it doesn't (falsey) }
- Vinnl 6y ago
- nojvek 6y agoTS really shines when you have to work with other people’s code. This week I probably touched about 2000+ files and changes various apis. TS was really great in giving that confidence that what I am calling actually existed. I had ~2000 errors and slowly worked to 0. tsc —watch is so good for iterative development. And LSP (Language Server Protocol) really is a boon for the industry. So many tools can work together. Thank you VSCode for paving the way to an open protocol.
- nojvek 6y agoSvelte is nice, but man I just want to use JSX. Don’t make me learn another templating language.
- wirahx 6y agoSvelte will never have JSX, not natively anyway. It's completely against the philosophy. Not all of us think JSX is a great thing. The "templating" language in Svelte isn't really a templating language at all, it's just Javascript with some (unavoidable) helpers. It takes about 2 minutes to learn since there are really only maybe 5 helpers.
- ric2b 6y agoSvelte templates aren't really a new language, it's just HTML where you can sprinkle in some curly braces to insert variables or js code.
- aabbcc1241 6y agoYou can dev Svelte in TSX with svelte-draft
- heapslip 6y agoJust so you know svelte + typescript + eslint is currently not working.