Hacker News new | ask | show | jobs
by RoboticWater 1686 days ago
For all the use cases I deal with on a regular basis, Svelte looks more like vanilla HTML/JS than any equivalent React code.

And the reason these things change is because that's what needed changing. One of the topline features of Svelte is that is has less boilerplate than React, and it achieves that quite handily. Unless you're criticizing particular constructs in Svelte that are unjustifiably different, I don't think unfamiliarity is that damning a criticism.

Maybe I'm just used to switching up languages on a regular basis, but the idea of having to learn different language constructs for loops and the like doesn't seem that herculean of a task.

3 comments

What how can you say that???

      <ul>{myItems.map({id, title}) => 
          <li key={id}>{title}</li>
      }</ul>
vs... svelte

     <ul>{#each myItems as item}
         <li>{item.title}</li>
     {/each}</ul>
One is literally just javascript and html the other is an entirely different template language. You might say... JSX is not HTML... well it's very very similar... If you know HTML you JSX is very intuitive.
But React isn't just JSX. It's also the entire runtime library, hooks, event handling, forms, state handling, etc. The example you shared is a bit too simple to understand where Svelte shines because it doesn't introduce any of those concerns.

By having it's own templating language, Svelte is able to compile the templates to JavaScript in a way that addresses many of those concerns in a way that I think it easier to deal with as an end user of the framework.

If Svelte were using JSX, I don't know that it'd be possible to do everything else that it does so simply because you can write anything that's valid JavaScript in JSX whereas Svelte has just a couple of basic control structures that its compiler can parse and convert to runnable code.

Not to mention it takes reactivity to new heights while adding amazingly little actual syntax.

When property changes, the fetch refires, loading appears until the fetch resolves then it displays whatever array someFetch resolved to.

I came from Vue and that plus the way Svelte does stores (literally nothing special about them) was a breath of fresh air.

    <div>
        {#await someFetch(property)}
            <div>Loading...</div>
        {:then data}
        
            {#each data as item, index}
                <div>{item}</div>
            {/each}
    
        {/await}
    </div>
But what does ‘#await someFetch’ actually do? The thing I like most about react is that it’s just executing plain Javascript most of the time.
> The thing I like most about react is that it’s just executing plain Javascript most of the time.

Then explain what hooks do ;)

Hooks are decidedly not Javascript (even if they look like Javascript), and are a much more weird construct than {#await promise}

No, they are JavaScript, it is array based programming wrapped in a reactive functional-declarative approach. Simply array of objects cascading with state. {#await promise} is more cryptic than any useHook function implementation.
His point is you don't have to read some project's documentation to know how some "await blocks" work.

With JSX you can use native JS features instead, you only need to know the language.

For example, instead of looking up how to loop in the template syntax, you use an iterator.

Not just most of the time — all of the time! JSX is converted to plain JS (react.createElement) before it gets to the browser.
Isn't it actually the opposite? Svelte code is compiled to plain JS whereas React has a large runtime.
I’m neither of (react, vue, svelte) guy, but isn’t that snippet equivalent to some:

  div
    Await promise={mypromise}
      div Loading…
      {res => res.map(…)}
      div Error: {err => err.message}
(writing in pug-like because I can’t stand closing these tags on the phone)

Isn’t it easier in both react and vue to create Await component with children=(ifwaiting, ifresolved, ifrejected) than suffering all over the code?

Edit: I messed data flow up in the error handler, wontfix but you get the idea

> If you know HTML you JSX is very intuitive.

That's a poor assumption that appears to be based on your personal preferences and what you're comfortable with. I personally find both require some learning, but prefer the svelte version.

And JSX isn't JavaScript and it isn't HTML, and if you know JavaScript and HTML you still don't know JSX, so you're still using "yet another language" in addition to JavaScript and HTML.
JSX is easy to summarize as: HTML where everything in curly brackets is a JS expression that gets evaluated. There are some additions (prop spreading) and restrictions (curly brackets apply to whole attribute values and element bodies only), but they're very simple.
And custom event handling attributes, camel casing, special cases like htmlFor and className, non-standard attributes being ignored except for custom elements, the style attribute, the special case of checked/selected properties vs attrs for form elements, key and ref properties. Plus all the semantics of component updates, memoizing and so on.

This is already far more to learn than the handful of simple control structures Svelte introduces.

Come on… If you know JavaScript and HTML you are 95% of the way to being fluent in JSX. It’s basically just JavaScript expressions.
And if you know javascript and html you are 100% fluent in any sort of hyperscript, which is just js expressions.
JSX is JS. Nested brackets are simply converted to nested function calls & objects, attributes convert to properties.

This is evident when comparing conditionals, loops, etc. Instead of learning template syntax you simply use JS syntax, albeit a declarative subset (no branches).

JSX is simply syntactical sugar for nested JS, you can use it without, but it's prettier with.

One could add this syntactical sugar natively to the language spec, in fact E4x (ECMAScript for XML) share some properties w/ JSX and was once proposed to the spec.

edit: instead of downvoting, please voice how you disagree with my assessment

Jsx is not js, it’s python!

  <div className={red}>
    {text}
  </div>

  import react
  react.create_element("div", {"className":red}, text)
By the same logic we could call any structured format “is js”, because it is homomorphic to some js expressions. Are xml, pug, plist, dbf, all js? Nope, it’s all python.
I agree 100%... Adding JSX to the language spec would be interesting. It might be too heavy to include within the language spec as many JS applications do not involve the DOM at all, so then you have to essentially bundle DOM functions into every application... or common.js would omit this subset of the language.
It's actually a fairly small change (two new PrimaryExpressions), the spec is here:

https://github.com/facebook/jsx

Example parser from Acorn:

https://github.com/acornjs/acorn-jsx/blob/master/index.js

No part of JSX uses the DOM, it doesn't share anything with HTML.

The JS engine itself would need the modification.

Also JSX doesn't have to be for the UI, it could be for dialogs for an NPC in a game, for configs, etc.

edit: I agree with @proxyon, I'm really disappointed with HN that this simple fact is downvoted without retort.

The common sentiment here is wrong, JSX is a small extension to the grammar of JS. It is JS.

One nice thing about JSX is that it is pretty straightforward to write the function (React.createElement replacement) that it transforms to, so you can use it to construct any complex tree-like structure. No DOM stuff is needed. For example writing a JSX factory to output a static html string is maybe 20 lines of code.
Mozilla Xulrunner and Rhino (a JavaScript interpreter implemented in Java) used to support E4X: ECMAScript for XML, the ISO/IEC standard 22537:2006, and it was removed in 2014.

https://en.wikipedia.org/wiki/ECMAScript_for_XML

>ECMAScript for XML (E4X) is the standard ISO/IEC 22537:2006 programming language extension that adds native XML support to ECMAScript (which includes ActionScript, JavaScript, and JScript). The goal is to provide an alternative to DOM interfaces that uses a simpler syntax for accessing XML documents. It also offers a new way of making XML visible. Before the release of E4X, XML was always accessed at an object level. E4X instead treats XML as a primitive (like characters, integers, and booleans). This implies faster access, better support, and acceptance as a building block (data structure) of a program.

>E4X is standardized by Ecma International in the ECMA-357 standard. The first edition was published in June 2004, the second edition in December 2005.

>The E4X standard was deprecated by the Mozilla Foundation in 2014.

https://bugzilla.mozilla.org/show_bug.cgi?id=695577#c1

>Mark S. Miller, 10 years ago

>"use strict" is currently our one real opt-in boundary for simplifying the language and reducing threats by dropping legacy complexity that is generally no longer needed. As Brendan said somewhere "E4X is crazyland", and FF's implementation of E4X deviates from the spec in ways that are not written down anywhere. Until we encountered this issues, it looked like SES could bring ocap security to ES5.1 without doing an accurate lex or parse. With this restriction, we could regain this economy.

>Besides, no one wants to upgrade the E4X semantics to be compatible with ES5 or ES.next, so this seems a good time to impose this opt-in restriction.

https://news.ycombinator.com/item?id=8266648

>bastawhiz on Sept 4, 2014 | parent | context | un‑favorite | on: JSX: XML-like syntax extension to ECMAScript – Dra...

>So..uh...this was a thing. And nobody wanted it. So it was deprecated and killed. See the "Prior Art" section at the bottom of the page.

http://en.wikipedia.org/wiki/ECMAScript_for_XML

>Brendan Eich was quoted as saying something along the lines of "E4X is crazyland". Parsing it is hard as hell to do right. Think of all the tooling that's out there for JavaScript right now that will either a.) not support JSX code or b.) bloat up beyond belief as it takes into account the suddenly absurd requirements necessary to deal with a similar-but-not-quite-XML-or-even-HTML-for-that-matter syntax. Oh, you want to lint that JavaScript? Bless your heart! You want to add syntax highlighting? Love will find a way. You want to use other static analysis tools, sweet.js macros, or anything else non-trivial? How cute!

>So essentially, it's a great way for Facebook to push React.js without making React.js a standard.

https://stackoverflow.com/questions/33642820/why-was-e4x-dep...

>It was deprecated and removed from the only browser that ever supported it because it was a poorly implemented language feature that was causing all sorts of problems.

>As Brendan said somewhere "E4X is crazyland", and FF's implementation of E4X deviates from the spec in ways that are not written down anywhere. — Mark S. Miller

>The only way for it to come back would be via a new edition of ECMA-357, which Adobe and Mozilla were going to work on. Until then, it's out. — Brendan Eich

>The idea behind it wasn't bad, but the way it was integrated into the language was. SpiderMonkey was the only JS engine that ever implemented it, and there were endless problems caused by that and severe complications of the engine's implementation required for this support. — Till Schneidereit

At least it's pretty much only built up of J's and html instead of something entirely different.
JSX is just JS with brackets instead of nested function calls. I expected more from this community than this kind of commentary.
I grant that it isn't Javascript and you have to get familiar with it. But at least it's not Hugo templating.
This JSX syntax is a perfect example of one of its subtleties: map() creates an array, and an array of elements is automatically expanded to single elements. I know that when I learnt JSX, this was not intuitive.

The word 'each' conveys the intent of this code way more explicitly.

And this subtlety is based on a difference in React.createElement() interface. If you pass an array among its children, it automatically requires all of its items to be keyed, and if you pass it as …array, i.e. variadic arguments, it doesn’t. But I believe you either can’t do {…array.map()} in jsx or its creators decided that it is not tasty enough.
> literally just javascript

Repeating it over and over again does not make it true.

https://linkedlist.ch/jsx_is_not_just_javascript_39/

Repeating a blog post over and over doesn't make it true.

The author is wrong. Most of his statements are about React, not JSX.

It's syntactical sugar for nested function calls, that's all. Brackets are turned into function statements, attributes are turned into object props.

The author conflates React properties with JSX, which is wrong. The author also confused JSX limitations, you cannot do statements because it's a single expression.

Please go read the JSX spec instead of some random blog post.

https://github.com/facebook/jsx

Thank you for that definitive link. Note that first boldfaced sentence in that JSX specification is as follows: "It's NOT a proposal to incorporate JSX into the ECMAScript spec itself."

That should have been the end of this discussion and fight that you picked about your incorrect statement that "JSX is JavaScript". You just unwittingly undermined and terminated your own argument by linking to the JSX spec itself, which clearly and explicitly says you are wrong, in BIG BOLD WORDS.

As JimDabel said, "They wanted to be 100% clear about it." So stop repeating something that the JSX designers so insistent is not true that they put it in bold at the top of their design specification.

You already won this argument, for the "JSX is NOT JavaScript" side. It's over.

You're arguing the wrong thing. You're arguing a semantics debate about whether an extension is JS. I'm arguing that it allows you to use JS features instead of a custom template system.

In the semantics debate you want to have I think it is JS because it all becomes JS bytecode and it's just nested function calls in the end, but that's subjective. If you want to be pedantic it's a JS extension, but in the future it could be JS if the spec is merged into engines not the compilers.

JS is an umbrella term, you're arguing it's not Ecmascript, okay, I never said that. I said it's JS, and you want to have a tussle about it instead of comparing templating systems.

Also you're very rude.

Right from the very top of your source:

> JSX is an XML-like syntax extension to ECMAScript without any defined semantics. It's NOT intended to be implemented by engines or browsers. It's NOT a proposal to incorporate JSX into the ECMAScript spec itself. It's intended to be used by various preprocessors (transpilers) to transform these tokens into standard ECMAScript.

Further down:

> Why not just use that instead of inventing a syntax that's not part of ECMAScript?

It is not JavaScript.

We're splitting hairs now. It's an extension of the JS spec. Once a parser adds this grammar it is JS.

It's syntactical sugar, unlike template syntax #if, ng-if, etc.

Your argument is it's not part of the current Ecmascript spec, I never said it was, but if a parser or engine adds these two new PrimaryExpressions and attributes, it is JS.

The entire point is JSX extends JS to allow templating via nested JS functions w/ pretty brackets instead of creating an entire templating system.

Under your reasoning nothing that isn't in the current accepted Ecmascript spec implemented by browsers is JS. Does that mean decorators aren't JS? Were async functions not JS before they were in browsers?

We’re not splitting hairs. It is, quite literally, not JavaScript in a fundamental way.

If you want to go around telling people it’s a non-standard extension to JavaScript or if you want to go around telling people it’s a superset of JavaScript, then by all means do that. But it is simply not JavaScript. Why do you insist on saying otherwise? All that does is start completely pointless arguments. What do you gain from insisting it is JavaScript when it isn’t?

and if you really want to use statements, you can, using an IIFE for example. It’s not pretty but you can because… ehm… it‘s just javascript.

At this point the "is JSX just javascript" discussion has gone on a little to long imho. It feels like "is html a programming language". We all have strong convictions about the answer but it doesn‘t matter, really.

It‘s interesting that fans all of 3 frameworks constantly claim that it’s "just“ or "closer to vanilla" html or js. Should we really care anymore?

Objectively, the Svelte example is cleaner and easier to read.
The issue is not only the syntax, but the semantics. What happens to the scope when you nest #each expressions? Does it work with iterables (like for..of), or it behaves like for..in? I don't use Svelte, and I don't know those differences by reading the code. To me the nice thing about JSX is that is straight forward with JS semantics:

    const a = <div prop={expression()} />
is a DSL for:

   const a = factory('div', {prop: expression()}) 
is only a DSL to create tree structures (React is another story, you can use JSX without React).
Subjectively, I’d say. But since I agree that it’s cleaner and easier to read- I upvote you
By what metric are you measuring it objectively?
density.
Saying it is objective but not mentioning the reason really makes your statement subjective.
Yeah, now add state management, event handling, side effects and performance optimizations and come back with your example. You're just comparing syntax. This is very naive.
Seems like svelte is superior for not needing a key.
Both Svelte[0] and React[1] are the same in this regard, the key is there as an optimization and isn't required in either framework. The only difference is that React's key is on the element whereas Svelte is as part of the each expression.

[0] https://svelte.dev/tutorial/keyed-each-blocks

[1] https://reactjs.org/docs/lists-and-keys.html

The key is used by the shadow Dom for update performance; the is no shadow Dom in svelte
List diffing is done even in svelte at runtime. Keys are used the same way as any other frameworks or frontend libraries, virtual DOM or reactive.
And yet Svelte is faster than React in pretty much every benchmark I’ve seen.
That makes sense though right? One would assume that shadow dom and dom would be slower than direct dom manipulation.
I'm not sure that's a fair assumption, one of the original sells of a shadow dom was that manipulting the dom directly is extremely slow, so doing as much work away from it is faster.
fair criticism I wonder how svelte optimizes for rerendering of long component lists. React uses keys to avoid rerendering the entire list.
Keys are also essential to retaining an element identity, which is structurally more important than performance, because 1) code may have a reference to an element and think that it relates to some data, 2) an element may have an explicit state (like focused, animating, etc).

Keys are a hugely leaking abstraction, but are inevitable when you bridge a declarative immediate mode rendering into a stateful one.

I believe you can specify a key in Svelte as well, but perhaps it's used slightly differently than react.
Yeah it's not strictly necessary, but if you are updating the list (adding/removing especially), Svelte can know how to reuse elements properly if they are keyed. You also need keys for animations to work properly.
Neither of those are JavaScript..
> but the idea of having to learn different language constructs for loops and the like doesn't seem that herculean of a task.

I agree. As long as you understand the basic concepts, it's only a matter of learning the syntax, which is really not as big of a deal as the person you replied to is making it out to be.

It's not a herculean task... I agree, until you've learned 10+ (angular, vue, svelte, wordpress/php, jade templates, laravel, underscore/lodash, handlebars/mustache, hugo, etc..) of these "super simple templating languages"! And keep them all straight. I have no problem learning a new language if there is a compelling reason. But If it's just additional shit I have to remember for no clear reason... No thanks...

We can have a debate on unidirectional data flow vs 2-way binding, how each framework manages state changes, how opinionated each framework is... How mature and vibrant each developer community is... etc. These are all another discussion though. My question is why must we reinvent the wheel again and again.

You need to stop insisting that a wheel has been reinvented with Svelte. It shares 95% of the same DNA as other frameworks, with multiple improvements over them. So with that in mind, what you're actually suggesting is that the existing offerings were somehow perfect, and we don't ever need to improve on anything again. That is an absurd notion, especially given that the other frameworks have gone through MASSIVE changes since launch -- sometimes even complete rewrites, because they acknowledged they got it wrong the first time.
100% agree !
>It's not a herculean task... I agree, until you've learned 10+ (angular, vue, svelte, wordpress/php, jade templates, laravel, underscore/lodash, handlebars/mustache, hugo, etc..)

So you want all of these to be a universal-template-language - (D)HTML ?

100% - Common guys we are programmers in a field that is know for changing consistently (probably a lot faster than other careers). If you see learning new "syntax" for the basics (loops,conditionals etc) then you going to have problems down the road. Weather you use svelte, or some other new tech. If you really never want to learn another syntax.. learn LISP and be done with it.

You are a programmer, you will need to learn new syntax a few times in your career.

If some of the "biggest" complaints are "oh no I have to learn how to write for-loops again" - I guess svelte is doing the important stuff right.

Wayyyy back in the day(ok not that long ago - 80/90's) when I was learning a new lang (Pascal,C, C++) I used to tell myself If I can get an working example of:

1) "user-input (readline,scanf etc)"

2) "printing input/output"

3) "calling functions/procedures"

4) "Do the loops + conditionals"

5) "file I/O"

6) "Memory schematics"

You basically mastered the "building blocks/mrk(min-req-knowledge)" of the new lang and like maths you only need now practice or a good project.

TL;DR If you are a professional-career-programmer, learning "new syntax (we used to call them keywords)" is a requirement.

Oh but it‘s not just about the syntax, it‘s also about the semantics, scope rules etc. This is the reason I still like JSX best, because I have a fairly deep understanding of that stuff in javascript while vue templates still leave me scratching my head sometimes. But I can see the appeal either way.
What boilerplate does React have? Do you mean Babel?
I know...

This comment had no context...

You don't have to even

    import React from 'react';
anymore
useMemo and useCallback do feel a little boilerplate-y. Something is slow, I wrap it in the thing, I let eslint fill the dependencies and there‘s no big downside to doing it all the time anyway. Feels like something I maybe don‘t need to be typing?

useState is also something svelte eliminates, though I personally prefer to keep that explicit.