410 points · by rich_harris · 8y ago · 209 comments
> 2. As a corollary, your app's codebase should be universal — write once for server and client
This is a mistake a lot of developers make. The server and client are not the same. As far as rendering HTML goes, the client does a superset of what the server does.
This means either the framework has to be without leaks; meaning you never need raw DOM access at all, OR it means once you do need lower-level access (for doing animations, for example) you are in trouble. You now have a problem where you have some code that needs to only run in the client. So you have to special case that code to check if running on the server. And you need a strategy for what to do in the server (do you just omit this part, or do you try to do something more basic or what?)
In my experience you run into more pain trying to plug the leaks in these "universal" apps than you would if you just had separate server and client templates. Remember that the rule of 3 is the rule of 3, not the rule of 2.
https://en.wikipedia.org/wiki/Rule_of_three_(computer_progra...
For example, you can't trust client-side code for security/authentication purposes. You almost certainly don't want client code to connect directly to your database and run arbitrary queries/look-ups. So some kind of server-side-only wrapper around your DB, at least, is required.
But the reason you'd run "client" code on the server is to have a layer of universal HTML-rendering code. The server needs to do it for fast initial page loads (and SEO), and the client needs to do it for fast, offline page loads.
At the same time, there's a bunch of code that will run on the client side only, e.g. click handlers, animations, etc. There's essentially nothing for that code to do on the server, but I think it's still basically correct to call it "universal" when you mean "client code that can also run on the server" which is what Sapper provides.
I think it does take some time to think universally, but it's not all confusion and hair pulling.
In fact, it kinda reminds me of writing testable code. You need to separate some concerns, but ultimately, it's a set of conventions that help you get there.
I can tell you, there are plenty of times when even a rule of two isn't worth the maintenance effort that's caused by rendering HTML in two different places.
It is an issue, but one that is really easy to handle.
The universalness I want is that I want one language, package manager, toolchain, IDE etc for all the code I’m working on. Worst case would be to have the two platforms being slightly different. Say two IDE’s with slightly different shortcuts, two curly brace languages with slightly different syntax, two different build systems you need to integrate in the CI etc.
Server response, do you mean in the context of a server that does server side rendering? I was thinking in the context of a normal app: api backend and (possibly multiple) front end rendering apps
You might be able to write all your app code in Javascript, but the inputs and outputs are so different that you never really avoid "if(isServer()) {...} else {...}". You can't contain that in a single file, either. It surfaces in the most unexpected places and gradually erodes the illusion of "universal," until you're never sure in which order or what environment your code is executed. You'll have pieces of code written and rewritten again and again and executed several times just to make sure it gets called in the exact moment, with the exact arguments you need, at least once.
I spent many years in search of "universal" JS, and worked with many people who were convinced they had found El Dorado, yet always ended up in situations like I described, so maybe I'm jaded.
This is the basic value premise of frameworks. Write less code with uniform conventions and make it easy by hiding the complexity. Unfortunately, the premise is faulty.
You can only lie to yourself for so long that your ignorance of how things really work is fine because of (name your favorite abstraction). This is a very direct example of tech debt. By ignoring how things really work the application will gradually get bigger and slower until it is an incompetent mess like paying off credit cards with other credit cards.
The reason for this snowball effect is largely due to a lack of confidence that feeds upon convenience as opposed to examination of why technical problems exist in the first place.
I find this a great answer.
Much time is spent these days on taping over problems at the high level on the top of broken stacks, instead of fixing the underlying issues.
Building on broken foundations will only get you so far and yield diminishing returns, even if it initially looks easy and convenient to just build on top.
But, to quote from your link:
> and may or may not if there are two copies.
HTML is close to this ideal. If you haven't encountered it yet, I strongly recommend going through the tutorials at https://www.w3schools.com/html/. HTML introduced a brilliant idea: all the pages of your app are files in a your-project/pages directory, and each of those files is just an HTML page.
Everything else flows from that breakthrough design decision. Finding the code responsible for a given page is easy, because you can just look at the filesystem rather than playing 'guess the component name'. Project structure bikeshedding is a thing of the past. And the combination of SSR (server-side rendering) and code-splitting — something the React Router team gave up on, declaring 'Godspeed those who attempt the server-rendered, code-split apps' — is trivial.
Because then aren't you suggesting that after that, all the other pages can be slow?
The worst sites I visit now are React.js like sites, instead of the page load being slow, _everything_ is slow. Ugh. I can't wait until web 3.0 and this silly balogna with the "make a browser with React and run it inside a browser" fades out...
(note, Netflix _removed_ their js rendering from their home page cause it was slow)
This comment is a prime example.
HTML is anything but ideal. In fact, it's the core of the problem where Web applications are concerned. HTML and its kin (particularly CSS) were designed for content-oriented Web pages, not Web applications.
Continuing to devise Web-app frameworks that are predicated upon developers wrangling HTML for controls and CSS for layout will lead to more iterations of frustration; only to perhaps slightly lesser degrees. It doesn't matter if you write JS that renders it or templates. It's the same problem.
What's needed is a component-framework with proper tooling (including IDEs) for layout and design. We've solved this with Swing and even Visual Basic. So, for the life of me, I still can't figure out why we haven't moved in this direction full-on for Web frameworks. If the issue is that HTML and CSS are standards with broad support, then I concur: but compose the app via a proper GUI and let the tooling generate the HTML/CSS.
It's odd: we use Webpack, Browserify, etc. for full on Web-app builds, along with various cross-compilers for JS. But, at the end of the day, we're still writing HTML-based templates (or JS) and CSS.
This is generally an unpopular view on HN. But, I can nearly guarantee that the next truly meaningful advancement in frameworks will be via a component-oriented approach that abandons direct manipulation of Web standards like HTML/CSS altogether.
- every time it was attempted, the generated html/css was terrible (think old ASP Net for example), and maintenance hard. Abstractions only work when they are not leaky
- designers, devs and users in general expect to have custom design for everything, rather than standard controls. Something to do with “have a unique brand and not look like everyone’s else app”.
We've come a long way in tooling, libraries, and in the underlying standards. Technologies like ASP also pre-dated SPAs and were targeted for server-side development; hence make for a poor analogy. Swing would be a more apt comparison, and even Visual Basic.
In general, poor execution in the past is no reason to drop the objective. We've tolerated plenty of bad HTML-based frameworks and years of CSS-quirkiness, yet we keep plugging away at it.
>and maintenance hard
But the actual objective is that you wouldn't hand-maintain the generated code. We're currently so bound to HTML-thinking that it's hard to embrace that notion.
>designers, devs and users in general expect to have custom design for everything
I've heard this. Interestingly, though, we look to tools like Bootstrap and design-motifs like Material, etc., which emphasize uniformity. Also, there's no reason branding can't be applied without directly manipulated CSS. A good component-based library would allow for that and would also allow for the construction of extensible custom components.
1. SSR must support streaming
2. SSR must work in a service worker (so in fact you have 3 targets: server, client/hydration, client/service worker)
3. All work that can be offloaded to a WebWorker must be offloaded
4. Navigating to subsequent pages must support prefetching, including dynamic data (Next.js doesn’t even tell you how to do it)
5. Navigating to subsequent pages SHOULD support prerendering (offscreen) where it makes sense, but…
6. MUST support FLIP-style transitions[1].
Which does mean prerendering anyway for about 100ms at least so the layout can stabilize and cached images load into memory.
For long pages you need to split them into chunks/sections and only animate the part that gets shown (usually above fold).
[1] http://www.pocketjavascript.com/blog/2015/11/23/introducing-...
Sapper supports partial streaming of server-rendered HTML (typically you'll get most of the <head> while it's fetching data for your page, unless there's no dynamic data in which case you get the whole lot instantly).
I'm not convinced there's actually a benefit to 'server' rendering in a service worker as opposed to serving a shell page. We have an issue for it though! (https://github.com/sveltejs/sapper/issues/22)
Sapper supports prefetching (including of dynamic data) of subsequent pages — just add rel=prefetch to <a> elements (we'll add a programmatic way to do this in future as well).
As for the rest, some of it is app-specific, some of it is stuff the framework could help with. We're not at version 1 yet, so bear with us :)
However, it’s only a win on first page load on a subsequent visit. So definitely not a priority for an actual implementation.
BTW one easy way to implement this would be to flip the usual model:
1) Have service worker/server as main renderers
2) On navigation do a fetch to service worker and patch the page
So you’re on /main, do fetch to /page2?from=state and get patching instructions.
If you could give the service worker readonly access to DOM without copying this wouldn’t actually be that stupid.
It might be possible some day:
That aside, the idea of svelte is cool, and i'm happy they're continuing to build on that. Excited to see what comes out of this!
When look at fiber and react-reconciler, it seems to me react is already contemplating the future. The reconciler especially.
Ok, I'll level with you — that's not actually doing the same thing as the Fiber version. But that's it's basically impossible to accidentally slow down your Svelte app in the same way as the Fiber demo depends on. Fiber doesn't really speed things up so much as it prevents bad code slowing things down.
The innovation isn't templates (though these aren't your grandad's templates), it's compiling those templates to lean, memory-efficient JS code that doesn't depend on virtual DOM reconciliation or anything like that.
Who would intentionally use an older version of a framework, where the upgrade path breaks compatibility?
Angular 1.x is in essence, dead. It's just going to take a long time to go away.
At the same time, if I were designing something like this, I'd use a tool like Flow or TypeScript in a heartbeat. Doing AOT optimization is so much easier when you have type guarantees, I'm sure that once you go deep enough you get into all kinds of little issues that are only issues because JS is both dynamic and very quirky.
Rich, if you're reading this, did you consider this and if so, why not?
Svelte itself is written in TypeScript so I'm a believer. I'd like to get first-class support for TypeScript in components at some point. Adding .ts support for the non-component parts of a Sapper app should be fairly straightforward (it's just a webpack config after all) — will add that to the TODO list.
I completely missed this as I looked at the sample project and saw js files - this has me going back and taking a second look, so you might want to mention it.
Granted, you'd loose a large number of JS-only potential users, but seems like it'd be very differentiating (and unique?) to be TS-first, and market/specialize within the large niche of TS developers/teams.
Vs. the usual TS-last/TS-kinda-sorta approach that, again AFAICT, all the other JS frameworks take.
There are TS-first frameworks, such as Angular, and they're off-putting to people who just want to build something.
Yet the article makes clear that React is working on implementing some similar technologies. Is there anything in svelte / sapper that cannot eventually be implemented in React / next.js too? I'm more than willing to wait a year for it to show up in React rather than live on the bleeding edge...
It's far from clear that it'll ever be possible to compile a React app to something that doesn't need virtual DOM reconciliation, with all that entails.
I disagree! Code-splitting is arguably an architectural dead-end for SPAs:
1) It adds a non-trivial layer of complexity to both your application logic and your tooling. SPAs (and the JS ecosystem in general) are already complicated enough without this extra layer of indirection, and that complexity carries a higher cost than most people realize, especially when it's blindly accepted across the industry as best practice.
2) It's based on the conflation of apps with collections of hypertext documents, whereas in reality these are different architectures with different trade-offs. We're under no such delusions for apps in the app store for example, and thus nobody bats an eye if one takes a full minute to download.
I guess this isn't what people want to hear, but the web is more than apps, and we need to stop pushing SPA as the default way to build every new website. Code-splitting is merely the by-product of choosing the wrong architecture. In cases where SPA is the right tool for the job, we need to make users aware that they're downloading an actual app. I.e. a one-time install screen implemented via some kind of service-worker-driven bootstrapper: "Just a moment while we install your app..."
SocketStream, Derby, and even MeteorJS which had massive funding and marketing just couldn't do it. NextJS is just the next generation of fools who didn't research the market... Surely we can at least wait for NextJS to go belly up before launching yet another project that's going to waste several more lifetimes of human effort.
There was nothing wrong with the implementation of the MeteorJS project by the way... The problem was the idea itself. All the marketing and funding it received only served to delay its inevitable demise.
This really does sound like we're slowly reinventing lisp
I’m excited to try this more but I have mixed feelings about Svelte. The concept is brilliant but I feel like there’s too much API and some weird gotchas. I hope there’ll be an effort to simplify it if possible.
I think the 'too much API' feelings might be more unfamiliarity than anything. The API surface area is much smaller than anything like Angular, Vue etc, and although it's a fundamentally different approach to React I'd argue Svelte has a much shallower learning curve there as well. We're very open to feedback and suggestions though!
For example, what exactly does a tag starting with colon mean? Is it just arbitrary syntax for things that don't fit in? What does a colon in an attribute mean? (i.e., why on:click rather than onclick or onClick or even something simpler like :onClick?) Why is there both {{#if condition}}<p>Content</p>{{/if}} and {{{condition && '<p>Content</p>'}}}? I feel like all these different concepts break the "it's just HTML" promise, when it seems like it could be simplified a lot.
Yes, JSX has similar gotchas, but at least it has references and specifications.
And what's up with the crazy semantics of computed properties?
Sorry if this sounds negative, but these have been genuine problems for me in getting a hang of Svelte.
{{#if condition}}...{{/if}} tells Svelte something about the structure of your app. {{{condition && '<p>Content</p>'}}} doesn't, and you can't add interactivity to the <p> if it's just a string. Moreover, if `condition` is `undefined`, then that's the string that will get rendered to the DOM. Generally, {{{triples}}} should be used for blobs of HTML you get from data sources, such as a blog post.
If you can overcome your distaste for the computed property dependency injection, you'll hopefully find it's an extremely easy and compact syntax for declaring arbitrarily complex graphs of properties. The advantage of doing it this way is that Svelte can generate, at compile time, very efficient code for updating computed properties without any wasteful runtime dependency tracking. I realise it's slightly controversial (because it's a Svelte idiom, rather than something in JS itself), but for those who have embraced them, computed properties are one of the best features of Svelte!
Just look at Svelte's templates: https://svelte.technology/guide#template-syntax
Not only it's some custom implementation, it also breaks all assumptions about javascript code
const counter = new Counter({
data: {
count: 99
}
});
...then {{count}}, or counter.get('count')
Why is it `counter.get('count')`? WTF?Or just the section on computed properties[1]: oh, it's no longer even Javascript. It's some magic Javascript-like scripting language that gets injected with properties based on what you write.
Much like in Vue data, properties, and methods are magically hoisted up to the object breaking everything you learned about Javascript:
export default {
methods: {
say: function ( message ) {
alert( message ); // again, please don't do this
}
}
};
// and then
import MyComponent from './MyComponent.html';
var component = new MyComponent({
target: document.querySelector( 'main' )
});
component.say( '' );
Why the hell is `.say` a top-level method now?And so on and so forth.
The server should send down parts of the page as soon as their data becomes available. Typically, pages have a "header" section that requires no data at all, and the server should render it instantly and stream it to the client. Then there's typically some fast-loading "above-the-fold" data; the server should render and stream that as soon as it's ready. Beyond that, there's other below-the-fold components, which may load/render more slowly. The server should render those as they come in.
Then, the magic technique is to progressively attach event listeners to components as they stream in, so you don't have to wait for the whole page to load to be able to interact with above-the-fold components.
> 1. It should do server-side rendering, for fast initial loads and no caveats around SEO
Is server-side rendering still an issue for SEO? Don't major search engines evaluate pages now so that SPAs can be indexed?
This also applies for AdWords, it drove me mad when Google kept insisting my site was not reachable, even though it was.
Only after installing a client-side exception tracking tool (like raygun or errorception) I found out the page was not rendering on the 'old' browser Goolge uses internally.
The bigger problem is Facebook, Twitter, and the like are not going to run JavaScript to read your meta tags. It's not an issue for everyone, but if you're a publisher of articles then you're still going to have to render something from the server. Of course one can come halfway by only rendering the head tag contents and not producing a body, which is where most of the complication comes from.
https://testmysite.io/5a4c2cdf819876444fa127b5/hn.svelte.tec...
I really like Svelte! But I don't even serve my content from Express middleware anymore due to the above problem.
I just feel like you're under-estimating a developer's resourcefulness to make the content that actually is static a static page, and also over-estimating the number of new, traditional client/server web apps (at least by people who are probably in your target audience).
Static performance is hard to beat especially globally and there's a clear performance degradation once you get away from the epicenter. Believe it or not Svelte.technology's landing page actually performs noticeably more poorly coast to coast in the US (>2x worse to load in California than NY--150ms vs 500ms).
I'm not saying give up or anything, just saying it might be a good idea to talk to more JAMStack people :)
Having said that, we will eventually add the ability to 'export' a purely static site that can be deployed to services like Netlify. Next.js has this, but they didn't launch with it either. Bear with us!
We're not reinventing HTML, we're using HTML. And CSS. ('Reinventing HTML' is a far more fitting description of JSX, and then there's CSS-in-JS...)
Doing so is what allows us to statically analyse your app and compile it to a) a tiny client-side JS payload, and b) an incredibly efficient server-side renderer.
This attitude is why we have a hundred different relevant frameworks right now. How about instead of a building a new framework, you contribute to an existing one? You even say that Next is close to what you want... why not help to make it better?
Relevant song about this issue: https://www.youtube.com/watch?v=Wm2h0cbvsw8
[0] https://medium.freecodecamp.org/a-real-world-comparison-of-f...
1. I think this point is trying to say that we don't have special "mask files" inside `pages/`, which is an idea worth exploring. Right now, Next.js instead gives you full flexibility on how you want to match the routes on your server (as it should be). For example, `your-domain.com/xyz` can even first perform a database query before deciding what page to render it with (if any).
2. What the author points out as a weakness here is that you can handle server things directly in your server code (`server.js` using micro or express for example). That sounds like the right thing to do to me, and if you don't want that, you still can do something like:
// pages/my-server-page-only.js
export default ({ req, res }) => res.end('hi')
3. "To use the client-side router, links can't be standard <a> tags." This is by design. Magically overloading `<a>` to add client-specific behavior sounds like the days of jQuery or TurboLinks. If you want client-side behavior, wrap `<a>` in the higher-order `<Link>` component. There also very important properties of the `<Link>` like `<Link prefetch>` that are simply not part of the `<a>` standard definition.Also noteworthy: the entire ZEIT Documentation is written in Markdown with React components. It's open source: https://github.com/zeit/docs
On size: the Next.js and React teams are both working towards really interesting solutions to ship only the code that's necessary, without resorting to templating as the main strategy. Our team actually spends more time on the 'compiler' parts of Next.js than the 'framework API' parts. (the API has barely changed since the initial 0.1 release in fact).
Additionally, since Next.js uses React as peer dependencies, you'll also get to do `yarn add next react react-dom-lite` https://github.com/jquense/react-dom-lite in the future.
Overall, I think Sapper is an excellent framework for Svelte users. I'm looking forward to seeing more Next.js-like frameworks.
For Vue users: check out https://nuxtjs.org/!
My criticisms aren't based on misunderstandings, however. Route masking provides flexibility but it really does undermine the ability to navigate a complex app structure — Nuxt.js evidently reached the same conclusion, because they too have dynamic route parameters encoded in filenames.
The my-server-page-only.js results in a 'Cannot read property 'end' of undefined' error for me, because it seems Next can't distinguish between universal and server-only routes. If you have any examples of this working, please do share them!
The Markdown ZEIT documentation is cool, but doesn't really address the problem I was getting at with <Link>, which is that your content is likely to come from a database. (Incidentally, Sapper does provide support for <a rel=prefetch>, which works exactly the same as <Link prefetch>.)
> On size: the Next.js and React teams are both working towards really interesting solutions to ship only the code that's necessary, without resorting to templating as the main strategy.
I'm excited to see where that takes us. My conviction remains that templates will always provide more and deeper optimisation possibilities than JSX, but this is a competition in which ultimately we're all winners.
nuxt.js applications don't need to rely on filenames for routing. there's a handy nuxt module for this -- https://github.com/nuxt-community/router-module
hmm, I don't even see a mention of how to integrate any datastore with Sapper or did I miss something?
Or serve your data from a different app altogether. There are so many possibilities here, depending on the requirements of your app, that it would be folly for a framework like Sapper to dictate how you solve this problem — instead, it gives you the tools to easily solve it yourself.
Yes, because these are frontend frameworks and that is a backend concern.
Because I don't know of any. Except maybe the new Rust framework, Yew. Which seems very interesting.
For examples of JavaScript's shitty-ness, I'd point to its various function declaration styles and their disparate effects on the code you write, its wishy-washy scoping, namespacing, the number type's precision problem, NaN being a number type, the ambiguity of this, just to name a few.
I think Kotlin is becoming a good choice for these criteria. If you want to follow Mr. Harris's framework as compiler approach, Scala may also be a good choice, because of all the compile-time metaprogramming facilities it has. I don't know how Scala Native stacks up beside Kotlin Native, though, and I've read that Scala 2.12 requires Java 8, so that's probably not a good choice for downlevel Android support.
The file size problem is underrated. Not everybody walks around with 5G like in South Korea. Not everybody has the latest and greatest Samsung or Apple phone.
It's a big problem when you advertise PWA as quick and fast but then in tiny letters mention its using the best case on best network and best phone. If you design without worst case in mind, you've discriminated people based on whether they can afford the best or not.
The vast majority of users don't. It's only recently that Android phones have gotten cheap that its seeing widespread usage. These people are not going to wait around for the React/Redux stack to load AND still wait on more data coming through their 2g/3g connection. Oh, and there's slow rendering on older Android phones and now you have a laggy Javascript app experience that Lighthouse tells you everything is okay.
Let's not be so quick to judge. It's not as if Sapper has deviated from the trend that even React team is acknowledging. This is a fresh approach to a quickly monopolizing space, from an organization that has other agendas in seeing their tech stack flourish.
I'm gonna definitely be watching Sapper.js in 2018 and if they deliver on most of the 11 criterias, I know my customers and their customers will be happy.
As for laggy experience, Fiber is the only feasible attempt at the moment to actually tackle it. Microbenchmarks will not help and neither Svelte nor anything else will make a webapp fast on a slow phone as baseline diffing has never been the problem in the first place. The problem is and has been the dom and the single threaded handling of it.
Fiber will allow apps to schedule. Imagine an app with 100.015 rows that Svelte renders in, say, 500ms, let it be 10ms faster than React 15's 510ms. It would still eat into your frame budget and cause heavy jank like all web apps do. Fiber just wouldn't render the 100.000 rows that don't fit your phones screen finishing the whole op under a single ms. It culls and prioritizes similar to how virtual lists operate in general, but you get that as a first class primitive being able to defer any render call of lesser importance without causing visual distortion or code complexity.
Not to mention that with React you could actually produce a real native app, while redux would allow you to share most of your code. With something like react-native-web you could even write a universal app being able to render both in the web and natively.
i can imagine an app like this. and such an app would have been designed with 0 thought given to the actual usability by humans. the proper solution is to provide sorting, grouping, filtering and pagination. your UIs should be small enough to remain fast without insane optimization tricks. mobile and even desktop browsers are plenty slow at rendering/reflowing 100k DOM nodes; the fastest way to render this is simply not to.
it's not as if suddenly you don't have to worry about the shitty UX and performance of your app's architecture "because fiber".
I don't even know where the scepticism comes from, culling and priotization is normal on the desktop. You've been offloading UI related tasks that could interrupt animations or interactions in C# forever - it is a great tool to have and getting it for the web is a major step. Microbenchmarks that measure baseline deletes/adds/changes will simply not result in apps that feel native. Thinking framework xyz will just feel acceptable to mobile users because Krausest says it takes 1ms less adding 100.000 rows, that is just silly.
So it's not really an improvement for me, your component tree becomes harder to reason about (when does this component renders??), you may see very unwanted progressive rendering where you didn't want to, etc. Many vdom implementations are faster than React, synchronous perfs matter a lot too.
Even the core React maintainers acknowledge this is kind of like an experiment.