DEV Community

Cover image for A love story of Svelte and JSX 💖
Rajaniraiyn R
Rajaniraiyn R

Posted on

A love story of Svelte and JSX 💖

Anyone who is a web developer has come across Svelte and JSX at some point in their life. Wait! What are they and what is the love story between them? 🤔 In this blog post, I will give you a brief introduction to them and tell you their secret affair which only very few know. 🤫

Svelte is a revolutionary technology in the web space. Unlike other popular UI libraries and frameworks like React and Vue, which use VDOM for UI, Svelte is a compiler which compiles the svelte code into highly optimized vanilla JavaScript code. 🚀

On the other hand, JSX is an extended version (syntactic sugar) of JavaScript, originally proposed and used by the React team in their React library. JSX enables us to write HTML-like markup directly into JavaScript and makes things more simple than ever before. 🙌

Despite their divergent methods, Svelte and JSX complement each other nicely. 💛

For Svelte files in your editor, the Svelte language tools and its VS Code extension offer capabilities like syntax highlighting, formatting, linting, auto-completion, type checking, and many more. 💻

How do they do that?

By using JSX! 🤯

What am I talking about now? Svelte is built completely differently from JSX, but what’s with my statement? Actually, many don’t know that Svelte secretly uses/borrows JSX features for its rich Developer Experience. We all know that currently most of the code editors and IDEs provide auto-completions and type checking out of the box. We have a very strong and reliable type checking and auto-completions in JavaScript and TypeScript, thanks to the wonderful magic done by TypeScript. ✨

In the initial stages of Svelte, when it started getting some traction, most of the developers who transitioned from other frameworks and libraries wanted to have those features in Svelte as well. To maintain and increase their retention rate, the Svelte team was cornered to make Svelte also have those features. What they decided to use is quite clever. Instead of building things from scratch, they used lots of existing independent and separate open source projects into one single project for their language server. One of such projects is halfnelson/svelte2tsx.

Projects used within svelte official language server

svelte2tsx 🤔🤔🤔

svelte2tsx is a transpiler that transpiles Svelte code into a valid TypeScript code, which is later consumed by the TypeScript language server. Then, finally, we get our fancy type-checking and auto-completions. 🎉

But how does it work? svelte2tsx converts Svelte components to TSX (TypeScript + JSX) for type checking. The TSX can be type checked using the included svelte-jsx.d.ts and svelte-shims.d.ts files. It also handles Svelte-specific syntax such as reactive declarations, stores, slots, etc.

svelte2tsx is a core part of the Svelte language tools and its VS Code extension. It enables features like syntax highlighting, formatting, linting, diagnostics, and more for Svelte files in your editor

Svelte Language Server Overview



import svelte2tsx from 'svelte2tsx';

const svelteCode = `
<script lang="ts">
export let h: boolean = false;
</script>

{#if h}
h is True
{:else}
h is False
{/if}
`;
const {code: tsxCode} = svelte2tsx(svelteCode);

console.log(tsxCode);
/*
///<reference types="svelte" />
<></>;function render() {

 let h: boolean = false;h = __sveltets_any(h);;
;
() => (<>

{(h) ? <>
h is True
</> : <>
h is False
</> }</>);
return { props: {h: h}, slots: {}, getters: {}, events: {} }}

export default class extends createSvelte2TsxComponent(__sveltets_partial(__sveltets_with_any_event(render))) {
}
*/


Enter fullscreen mode Exit fullscreen mode

Play with this Svelte → TSX here

This is a clever and inventive approach of giving Svelte IDE functionality without reinventing the wheel. It also demonstrates how, despite their seeming hostility, Svelte and JSX can coexist together. 🤝

I hope this blog post has given you some interesting and fun insights into Svelte and JSX. If you want to learn more, I recommend checking out their official websites: 🌐

Happy coding! 🎉

Top comments (7)

Collapse
 
shriji profile image
Shriji

JSX enables us to write HTML-like markup directly into JavaScript and makes things more simple than ever before.

I disagree, your IDE just knows what you are doing inside a JSX file. Browsers and IDEs know what HTML is.

Just the HTML code is lot cleaner than JSX. Svelte does it the right way.

Actually, many don’t know that Svelte secretly uses/borrows JSX features for its rich Developer Experience.

Where? Svelte's DX lies on the simplicity and its pragmatic aproach to build boilerplate-free components.

Collapse
 
rajaniraiyn profile image
Rajaniraiyn R

Thank you for your comment and for sharing your perspective. I respect your opinion, but I would like to clarify some points that you may have misunderstood. When I said that JSX makes things simpler than ever before, I was referring to the historical context of web development before frameworks like Svelte and Vue emerged. JSX was a game-changer that allowed us to write HTML-like markup directly in JavaScript and create reusable components with ease. I agree that for small projects, plain HTML may be sufficient, but for large and complex projects, JSX offers many advantages over HTML.

Furthermore, you mentioned that Svelte’s DX relies on the simplicity and its pragmatic approach to build boilerplate-free components. That is true, but it is not the whole story. Svelte also benefits from the features that JSX provides, such as autocompletion, syntax highlighting, type checking, etc. These features are essential for a good DX, and they are not exclusive to JSX. Svelte uses a custom syntax that is similar to JSX, but not exactly the same. JSX is not a new language, but an extension of JavaScript that can be easily understood by IDEs, browsers and runtimes. In fact, TypeScript, which is a superset of JavaScript, has native support for JSX as TSX. This means that many tools and software can work with JSX seamlessly. Svelte leverages these existing solutions to provide IDE features and autocompletion.

So, in conclusion, I am not saying that Svelte is bad or inferior to JSX. I am just saying that Svelte owes some of its success to JSX and that JSX is still a relevant and useful technology for web development. I hope this clarifies my point of view and I appreciate your feedback.

Collapse
 
sirajulm profile image
Sirajul Muneer

I agree that for small projects, plain HTML may be sufficient, but for large and complex projects, JSX offers many advantages over HTML.

What are those advantages over HTML?

Svelte also benefits from the features that JSX provides, such as autocompletion, syntax highlighting, type checking, etc.

So you claim these are the features that came with JSX? 🤷🏽‍♂️

Thread Thread
 
rajaniraiyn profile image
Rajaniraiyn R

Thank you for your comment. I appreciate your feedback and your interest in Svelte and JSX. Some of the advantages of JSX over plain HTML that I mentioned in my blog post are:

  • JSX allows you to write HTML and JavaScript together, which makes it easier to create dynamic and interactive UI elements.
  • JSX is transpiled into plain JavaScript by tools like Babel or Webpack, which means it can run on any browser and benefit from the performance and optimization features of these tools.
  • JSX is not a template engine, but a syntax for creating virtual DOM elements, which means you have more control over the rendering process and can use components, hooks, and other React features.

As for the features that came with JSX, I did not claim that they are exclusive to JSX. I only said that Svelte also benefits from them, as it uses a similar syntax. These features are:

Autocompletion: This is a feature of the code editor or IDE that you use, which helps you write code faster and avoid errors by suggesting possible completions based on the context.
Syntax highlighting: This is also a feature of the code editor or IDE that you use, which helps you read and understand code better by using different colors for different parts of the code, such as keywords, variables, strings, etc.
**Type checking: **This is a feature of TypeScript, which is a superset of JavaScript that adds optional static typing. This helps you catch errors and bugs at compile time by checking the types of the variables and expressions in your code.

And this all are not only with the help of JSX but also with many other existing solutions. You can learn more about it

GitHub logo sveltejs / language-tools

The Svelte Language Server, and official extensions which use it

Cybernetically enhanced web apps: Svelte npm version license

IDE docs and troubleshooting

What is Svelte Language Tools?

Svelte Language Tools contains a library implementing the Language Server Protocol (LSP). LSP powers the VSCode extension, which is also hosted in this repository. Additionally, LSP is capable of powering plugins for numerous other IDEs.

A .svelte file would look something like this:

<script>
    let count = 1;

    // the `$:` means 're-run whenever these values change'
    $: doubled = count * 2;
    $: quadrupled = doubled * 2;

    function handleClick() {
        count += 1;
    }
</script>

<button on:click="{handleClick}">Count: {count}</button>

<p>{count} * 2 = {doubled}</p>
<p>{doubled} * 2 = {quadrupled}</p>
Enter fullscreen mode Exit fullscreen mode

Which is a mix of HTMLx and vanilla JavaScript (but with additional runtime behavior coming from the svelte…

I hope this clarifies some of the points that I made in my blog post. If you have any further questions or comments, please feel free to share them.

A real life funny example that you can use to illustrate the difference between JSX and plain HTML is:

Imagine that you want to make a sandwich. Plain HTML is like having pre-made slices of bread and cheese that you can only put together in one way. JSX is like having a toaster, a knife, a cheese grater, and some butter that you can use to make your sandwich however you like. You can toast the bread or not, cut it into different shapes, grate the cheese or slice it, spread some butter or not, etc. You have more freedom and flexibility with JSX than with plain HTML. Of course, this also means that you have to do more work and clean up more mess with JSX than with plain HTML. But hey, that’s the price of creativity!

Collapse
 
iamhectorsosa profile image
Hector Sosa

Huge congrats on hitting top posts of the week! A chef's kiss would've been to frame some of these screenshots. I've built a simple OSS tool for this. Check it out and let me know what you think: github.com/ekqt/screenshot I'd appreciate a star if you find it helpful! Cheers!

Collapse
 
fruntend profile image
fruntend

Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍

Collapse
 
rajaniraiyn profile image
Rajaniraiyn R

Thank you so much 😊
But the brief about my article is completely different from what it is. So please make sure it is correct