It isn't Javascript that we're trying to avoid - it's having to learn whatever the framework du jour that is being used - and CSS.
I mean, a few years back, Angular was all the rage, currently React seems to be queen of the hill, even as Vue is making a charge for the top. And now there some skinny new weirdo on the scene.
Nobody fears node, what people fear is framework churn and having to redo a lot of work for reasons - that and having to learn CSS.
To anyone disappointed by the new syntax check Svelte.
It has single file components much like .vue
files. It is way faster than Vue and one of the most lightweight frameworks available.
WebAssembly is very limited. It cannot access the DOM for example, so it needs JS glue code. You can do computations with WebAssembly which can be faster than JavaScript in some circumstances. Also, you can use WebAssembly to bring libraries that are written in C/C++ and aren't available in JS to a frontend web app.
The reason Svelte is a compiler isn't purely to save the end-user some computational work, though that is a benefit. It's also to provide developers with neat abstractions and better syntax around for example reactivity, app-wide state, and of course the primary one: Being able to split your web app into reusable components (same as Vue, React, etc.).
The two don't really solve the same problems at all.
>The reduction in boilerplate
Are you using Function Components in React? There's not a whole lot of boiler plate from my experience and the hooks architecture has been a huge boon for re-usability and simplicity in our large applications.
Looking at https://svelte.dev/, there is probably >= custom boilerplate due to the templating DSL / binding compared to JSX + using native JS array / object functions to generate content. I'm also curious what the unit testing story is like for Svelte.
I've really appreciated React not trying to be opinionated about styling. I've migrated our large applications from Sass, to Styled JSX, and most recently to Styled Components which are pretty awesome.
I'm cautiously optimistic about Svelte, but I'm not convinced that it's currently a better or more scalable solution even with Svelte Kit compared to Next and it's giant ecosystem of plugins as well as the giant React package ecosystem.
Yes.
Assuming that all you know is HTML+CSS+vanilla js, Svelte is the second easier framework to learn after jQuery, and way simpler than React, Vue, etc.
It also has best docs of any js framework ever. It's like on a whole other level.
> I am aware that svelte is not ideal from a job market perspective
It's fairly medium. According to State of JS survey, it's already quite popular, and has been growing like crazy so I wouldn't worry too much.
It's also not a huge conceptual leap to go from Svelte to React or Vue.
There's a lot other far more exotic frameworks (like Imba or Opal.rb) you'd struggle more with in job market. Svelte is fine.
I think you’ll need to run this code in the onMount lifecycle. Otherwise it may try to initiate the websocket when that code is run serverside before the client gets it.
https://svelte.dev/tutorial/onmount
I also see you don’t have an import for the WebSocket object. I haven’t used WebSockets in js so I’m not sure if that object is available without import.
April 2020, I graduated a boot camp that focused on React. 2020 summer, winter, 2021 spring, I did a bunch of freelance work using React.
Mid July, 2021, I was hired to a company that used Svelte. I did the tutorial and a demo in a couple days.
Late July, 2021, forever sworn off React.
I was immediately productive using Svelte. I understood JS to an "Alright" level before the bootcamp. I also know that learning React exposed me to concepts and patterns that made learning Svelte that much easier.
But Svelte does all those things that a modern web app needs using concise, understandable code.
The "click to count" demo says it all.
I'll be looking in on this conference.
No VDOM (actually fast!!!), batteries included (state management, actions/transitions), better declarative syntax for things like conditional rendering and awaiting on promises... The list goes on. https://svelte.dev/tutorial/basics
So what your doing is probably not the best way to go about it, as onMount wont take advantage of reactivity, and if the window size was to change after mounting then you would not adjust the styles accordingly.
I think you should create a reactive variable that contains the width, by binding to a containers clientWidth, or passing it as a prop from a parent component. And use this reactive variable to directly control the style on the button itself. This will get you reactivity on window resize.
<a style={`display: ${width < 400 ? 'none;' : 'default;'}`} ...
Sticking with how you are already doing it, you should probably use an action instead of onMount. This can act basically like an onMount, but gives you a reference to the mounted element, and is generally more powerful and composable. See this tutorial page for more https://svelte.dev/tutorial/actions
IMO, there isn't a lot about Svelte that makes it easier/harder to make an accessible app than the other big frameworks. It does have built in compiler warnings when you write inaccessible markup, but those only cover a small subset of a11y issues. Other frameworks have similar tools as linting plugins, e.g. React has eslint-plugin-jsx-a11y.
The one part that would be harder with Svelte is that there aren't as many battle-tested component libraries. When building with something like React, there's already a standard (likely) accessible dropdown or other complex component you can pull in. Since the Svelte community is smaller, those libraries don't exist. But if your app doesn't need those widgets, that isn't a factor.
Then I would use grid instead of flex, you don't need to nest since it's made for layouts like this and it's nicely responsive thanks to the fr unit.
Here's an example of how I would solve it with grid.
You can use scrollIntoView
with bind:this
directive. official doc
<script> let element; </script>
<div bind:this={element}></div> <button on:click={() => element.scrollIntoView()}> Scroll To Top </button>
element
will be the Element Object
(like document.querySelector("div")
). so element.scrollIntoView
works.
I think the problem is that you're directly mutating the object from the store, when you should be assigning a new value to it.
Try this: https://svelte.dev/repl/df071ef9502448f2953570dde305c5a7?version=3.42.2
I'd also suggest wrapping the increaseCount
logic in a custom store rather than defining it in the component.
This is the part i found in their extension which defines a svelte app:
>"Svelte": {
"cats": [
12
],
"html": "<[^>]+class=\\\"[^\\\"]+\\ssvelte-[\\w]*\\\"",
"icon": "Svelte.svg",
"website": "https://svelte.dev"
},
So you would probably have to make sure that the generated classes don't have svelte in them
Yes, correct. However, VDOM is referenced here a bit, too: https://svelte.dev/blog/virtual-dom-is-pure-overhead#So_is_the_virtual_DOM_slow
What do you mean by " I don't see any reason it would be waiting for IO to complete or anything like that?"
"res.json() is an Asyncfunction" > I'd say that calling res.json() returns a Promise and Promises are asynchronous and the data is not immediately awailable. Using 'await' to wait for a Promise to be fulfilled, can only be done inside an async function (which then again returns a Promise)
Sending fetch to the server first gives back a response. Then you only have the response and can specify the data you want, which will probably take some time to load, so it's handled by a Promise.
You can use either an async function with the 'async await' syntax or chaining '.then()' to 'get to' the data.
These two options confused me in the beginning... this is a repl with both ways and logs of the different steps, which might help for understanding -> async await - .then() example
So genuinely curious, what about the example Svelte gives here for a component that multiplies two numbers. Is Svelte making the React code more complicated than it needs to be just to "prove" a point?
Check out https://svelte.dev/examples#debug. You can't just use a `debugger` statement like you can in a block of JSX because your code isn't *running*, as such (this is a feature, not a bug).
​
Anecdotally people have found the debugging experience ok — for one thing, even if sourcemaps fail you the generated code is designed to be readable, and you don't have to step through KLOCs of library code to see your errors. But it's always an area that's open for improvement.
​
More philosophically, as compiler techniques get more and more widespread (hello Prepack!), the JS community is arguably going to need to rethink breakpoint-based debugging altogether.
I think you want something like this:
https://svelte.dev/repl/cb89d4a00bce4735bc9f21e3e986e5b0?version=3.23.1
In brief, you shouldn't be referencing input.value, but rather you should bind that value to a variable. Then mess around with variables. Harness the power of svelte. Let it figure out your dom. You should just manipulate variable values.
have you tried this tutorial page? not just read, but also do?
https://svelte.dev/tutorial/reactive-statements
It really needs to click in your head what $: does, other then 'understanding'. And when it does, it's awesome.
Impossible question - no frontend could be recommended specifically "for Go".
But Svelte is a great SPA/data-binding framework for any backend https://svelte.dev/
Try those react/angular monsters first and have fun later. ;-)
Hey I'm doing exactly this with Svelte/Sapper today using Sapper export.
Just use Svelte-only features on your dynamic pages (e.g. no sapper preload
, no dynamic sapper routes) and you should be good. For example await blocks work great for the use-case of logged-in user data.
Thanks a lot for putting together this Svelte version!
Since I'm not familiar with typescript yet and wasn't sure how to use the npm version, I had a look at the code and converted it to plain js inside this REPL
When linking https://svelte.dev/
the description
is set to null
which is probably due to the uppercase letter in the meta tag? <meta name="Description" content="Cybernetically enhanced web apps">
Is this something the proxy could/should take into account so the description is read nevertheless? Or how could this be solved?
Very cool! Saw that in another demo earlier, I'm going to dig into it :)
My understanding is that the virtual-dom was more of a means to end when it came to writing declarative UIs. Svelte has a great article on it https://svelte.dev/blog/virtual-dom-is-pure-overhead and is also virtual-dom-less.
From personal experience the performance is a ton faster simply because less components update when state changes. It's common in React (but really anything using VDOM) to worry about the grouping of state and components and it's easy to not catch some expensive re-render until it's too late. e.g. A list of 1000 objects in state, where each object is expressed as it's own component, what happens when that data structure is updated? Does the parent re-render every single component in the list?
I say this all as a huge champion of the virtual DOM, it's history, and everything the general abstraction has given to the front-end community. What Svelte and the new vdom-less libraries give us is a natural evolution where we can apply hindsight and re-engineer it in a more efficient manner :)
Here's an example
https://svelte.dev/repl/72d24ccb46264ea7b85aea7cacc0581c?version=3.44.1
--edit - the refreshThings
shows you that the ThingElement update changed your array (if you open the console)
bind a variable to its value then in a reactive function scan for URLs that are not wrapped in anchor tags and change to links.
The function might be a bit of a challenge, but the instructions for contentEditable divs in svelte are here:
You actually can call the lifecycle hooks wherever you want, it doesn't have to be in a Svelte component. They'll be scheduled appropriately when you call the exported function inside the component. For example:
import { writable } from 'svelte/store'; import { afterUpdate } from 'svelte';
export default function useRenderCount() { const count = writable(0);
afterUpdate(() => { count.update(c => c + 1); })
return count; }
Then the function can be used like so:
<script> export let name = 'test';
import useRenderCount from './useRenderCount'; const count = useRenderCount(); </script>
<p>Hello {name}! Re-rendered {$count} times</p> <input bind:value={name}>
Each instance of the component will create its own store, and that store will only update when that component re-renders (in this example, when the bound input is updated).
REPL: https://svelte.dev/repl/7a88abc02a444e44b80682ca8c32ef63?version=3.43.2
do you face the prettier bug where it appends the last line twice at the end?
Also regarding stack-overflow support, I think its mostly unnecessary. Just hop in to https://svelte.dev/docs and press Ctrl+F to get what you want.
If you have a variable named "files" and you use shorthand syntax like it seems you do, you would need to get rid of shorthand syntax. Maybe take a look at this: https://svelte.dev/repl/81e75b2ca6a4485ea1a5cb81966d5a2b?version=3.14.1
You don't have to put the if inside the function, you can do this directly:
$: if (value === 5) {
message();
}
REPL: https://svelte.dev/repl/07559a68ab7541e9b7b0f37b558699e6?version=3.38.2
Looks like they changed the template syntax and added some new features like computed properties and lifecycle methods
https://github.com/sveltejs/svelte-upgrade#svelte-v2-syntax-changes
Changed in v2: https://svelte.dev/blog/version-2
https://svelte.dev/repl/26eb44932920421da01e2e21539494cd
These are the fancy css stuff supported.
https://github.com/sveltejs/svelte-preprocess
I personally use tail wind css. (Css in the html) Never used limaria.
Yes, use whatever for data fetching.
Similar to u/rickt3420, I went ahead and separated my apps as well. In my case, it's Ruby on Rails as an API only, and a separate Sapper application.
FYI, you may not want to use Sapper, and may want to try jumping in with SvelteKit, which is replacing Sapper: https://svelte.dev/blog/whats-the-deal-with-sveltekit
I make web games! See here, no email required:
www.theorbium.com and install Bean Grower to see how I was able to use a few assets from around the 'net and a bundle.
And I've got a whole browser-based game engine I've been working on since 2013. Refactoring it in Svelte at the moment.
Try wrapping your code in an onMount
I got it working here: https://svelte.dev/repl/b25d97d8b92649aa841dd22fb0a9e676?version=3.19.1
I don't understand "why" you want to do that, and why the "normal" way don't suit you (ie create your component clientside and inject it where you want in your html)
But you can invoke the compiler yourself with the option "generate:ssr". The compiler will then return an object with a render function. calling this function will generate a html fragment for the component. You should then "rehydrate" the component clientside if you have logic inside.
Not the best example but I wanted to explore the question. Here is a REPL that allows you to manually increment count, and increments when a user clicks "Login". https://svelte.dev/repl/86b39dc602ea4300b1ee78923cf55600?version=3.6.1
React + Your page is heavier my friend. You want this sort of feeling without the bloat? svelte.dev
HTML + nothing else gzipped is MUCH faster. You don't get the fancy animations? I get it. You have a few more lines on each page (the head) seciton to transmit? I get it. Still not matching the native preformance. It's dumb to say that. And btw; with server push and preloads you can even get much better performance.
I felt like React was actually surprisingly easy (if you are comfortable with Javascript) even though it looked messy when I first looked at it. I avoided redux and other unnecessary parts at first.
I would certainly spend a day playing with create-react-app
, looking at some react projects on github, watch some videos, take the tour, etc.
React is the biggest player right now with an extensive ecosystem (bootstrap or material design, native mobile support, good performance, and so on).
As an aside, I think Angular/Vue/React could eventually move (or be replaced with) the ideas found in the new https://svelte.dev/ system.
See those $? Those are labeled statements. Compiler recognizes them and just inserts appropriate code for invalidating/recomputing them.
After looking into this a bit myself, I think my best bet might be to combine Svelte (a lighter-weight competitor to React) with Pollen.
Svelte uses a syntax that is very similar to HTML with custom tags. One example from the Svelte home page has this code in an App.svelte
file:
<script> import Nested from './Nested.svelte'; </script>
<style> p { color: purple; font-family: 'Comic Sans MS'; font-size: 2em; } </style>
<p>These styles...</p> <Nested/>
And this code in a Nested.svelte
file:
<p>...don't affect this element</p>
All of that looks like it would be easy to generate with Pollen. So I could have something like:
(script "import Nested from './Nested.svelte';") (style " p{ color: purple; font-family: 'Comic Sans MS'; font-size: 2em; }) (p "These styles...) (Nested)
This would get the Racket syntax that I love, but compile down to Svelte code (which would then compile down to vanilla JavaScript).
Are there issues with this that I'm missing?
btw here is the tut - https://svelte.dev/tutorial/updating-arrays-and-objects
​
I had the same prob and I think I fixed it with this
You would use the update method of the store, returning a new object made up of the old one and any new properties.
Here's an example REPL: https://svelte.dev/repl/927f64a665ad445995d547c7036f4bbe?version=3.44.0
From svelte docs https://svelte.dev/docs#Accessibility_warnings
Accessibility (shortened to a11y) isn't always easy to get right, but Svelte will help by warning you at compile time if you write inaccessible markup. However, keep in mind that many accessibility issues can only be identified at runtime using other automated tools and by manually testing your application.
Ember is not considered "hot" right now by any measure. So, I can't recommend it against react.
however, if you are really looking for React's alternative, then you should consider other popular alternatives.
Most popular react alternatives are Vue and Angular.
If you are willing to go for less popular but newer tech, then Svelte is also an option.
That being said, React is not a perfect js framework, nor are any others. they all have their warts and gotchas. You should make atleast a PoC in them before committing long term
Yeah if I'm following you correctly, what you're describing sounds like how I would do it in React. I'm not great at explaining so I went ahead and put together a REPL that shows the way I approach it in Svelte.
https://svelte.dev/repl/cf11aa196b0c4092bd5ff93986e8959b?version=3.43.0
Hopefully you find this approach as useful as I have.
Sure, here's a pretty basic example I knocked up binding to the window width and changing the text color, resize your window to see the color change.
https://svelte.dev/repl/33ea41c9eb4a49a180c83b302d0a38cc?version=3.43.0
Although I dont entirely understand what you're trying to do here, why not import the browser store provided by SvelteKit and use it in a function?
Example:
<script> import { browser } from '$app/stores';
const doTheThing = (event) => { // stops the server from seeing this code if (!browser) return;
// do this if the event modifier still doesn't work e.preventDefault();
// do the thing
let target = e.currentTarget.pathname;
goto(/?path=${target}
);
}
</script>
<a href="example" on:click|preventDefault={doTheThing}>Click Me</a>
​
or a 'hacky' implementation example without jquery: REPL
A bit late to the party, but sometime last year I got started on the listbox component
[repl](https://svelte.dev/repl/cd88322e8b864d06bf4d0d1b4730de4c)
If I understand your question youre looking to identify each of the items on an array, I think you should check this: https://svelte.dev/docs#each
The each block can received an ID between parenthesis in order to identify each of the items and that helps svelte to animate them:
{#each items as item (item.id)}
<li>{item.name} x {item.qty}</li>
{/each}
nice pieces of code you did there! I figure that you want feedback so I come up with two: 1. why use get(store) in script but $store in HTML. Why not just stick with $store in both? 1. in addition to preventDefault modifer, you may want to add trusted which has been recently documented here.
yeah. by default in svelte, everything is reactive. I've never worked with angular so maybe someone who has could step in for a better explanation but, when a value is mutated in svelte, it will automatically react to that change everywhere. Svelte builds a dependency graph to keep track of what DOM elements rely on what values. whenever you mutate a value that is depended on in the DOM, svelte uses an "invalidate" command to tell the runtime that that value has changed and to update the DOM wherever it is referenced at the end of the event loop.
what I take from what you say is that you have to specify when a variable is reactive or not in angular which just isn't something you'll have to think about in svelte.
however, if you mean a variable that relies on another variable's value, that's a little different and we have some syntax to tell the compiler to recompute a variables value when it changes.
Using a custom svelte store like the one in this example: https://svelte.dev/tutorial/custom-stores
That way all you state changes are in the file you defined. At the end of the day in the component it's not any different then defining all those through the reducer.
Oof we have like a 400 line case statement that makes me want to shoot myself and I was told that was standard practice :( though each case in it's own file is far far far worse. I'd rather a 400 line case statement than 100 files that clutter the entire file tree.
I definitely think our platform has enough data flowing through it that needs to be shared in certain ways that having a store is useful, and I would say we actually underuse it
That's a hard question to answer, I think. As a non modern web-developer, I've looked at Svelte, and I would argue that it's not the speed that's so important (although it is a selling point), but that it's supposed to be easier to develop in for beginners. I think the main Svelte site has a blog entry about this:
https://svelte.dev/blog/svelte-for-new-developers
Most newcomers (I've heard) find React hard to learn, so starting with Svelte might be better just to get a feel.
It's hard to predict how things will go, to be honest. Google introduced Dart a while ago, and it never did replace Javascript, but it's associated with Flutter, so I think it's still around. React could have enough active developers that this will keep it around for a while. However, web frameworks seem to change like every 5-7 years. Compare how web development is today vs. 2010.
Could mean things are likely to continue to change.
All the above you mentioned would be a good fit. It comes mostly down to preference.
Even though I personally would use React since that's what I use the most it might make sense to look into https://svelte.dev/ It's very easy to get started and has a lot of features like animations already built in.
>Svelte
It does look good. Just watched this presentation.
https://svelte.dev/blog/svelte-3-rethinking-reactivity
​
I think the problem with svelte is only its exposure because to be honest this is the first time I have heard of it.
I am planning on making the tutorial in an online editor (like the one for svelte) to help make it more easily adoptable. Other than that, is there anything else you recommend to help make it more easily adoptable?
Sorry about that, my notifications were off- I got it working though
https://svelte.dev/repl/e3c7ab7c6ac2416991ae0e9efb8470a5?version=3.32.0
It's better to skip Sapper if you haven't started any development yet and wait for SvelteKit: https://svelte.dev/blog/whats-the-deal-with-sveltekit
As for how they compare. I don't have any experience with Sapper so couldn't say.
Local variables only react to reassignments. If one of the values they depend on (for example, your store) changes, they won’t trigger a re-render. You can use the $ label like so:
$: hoursNeeded = 36 - $user[1]
That way, the whole statement is re-run whenever one of the values involves changes
More about that here
I used D3 - here's a Svelte Repl with the d3 code for the graph in! The placeholder data is different of course (it's not my messages!)
https://svelte.dev/repl/c23b43904005457981e78ca5042f7dd4?version=3.29.7
Check this out - you can just replace the data with the data you want visualised, happy to answer any questions, but just play around with it and change numbers and see what happens.
https://svelte.dev/repl/c23b43904005457981e78ca5042f7dd4?version=3.29.7
Not that much related to this particular implementation...
Just want to note that Virtual DOM is far not the panacea for DOM update problems...
I suspect that the main purpose of VDOM in ReactJS is to have componentDidMount/DidUnMount calls - core of componentization. But these can be achieved by other means in modern web stack. At least in Sciter, where VDOM and reconciliation were implemented natively, there are other and effective means to achieve that.
Something tells me that the "next big thing" will not use VDOM at all. As in Svelte for example.
Looks pretty good.
I would personally change the on:click in the modal backdrops to on:mousedown so that when people highlight text fields and extend into the backdrop it doesn't close.
Also a nitpick - the shrink animation is a little jarring, you could probably smooth it out a little more https://svelte.dev/tutorial/animate
Just assign a default value to each prop that is optional in your second example and make sure you're conditionally rendering them in the markup or you'll get a warning.
For your specific example it would look like this REPL. I changed the furniture object into an array of objects so the variations can be seen but the concept works the same if you're passing data to a component as you've shown as well.
Looking good!
A thought, you’re using the name “use” for your hooks, I think this might be a bit confusing for people - ‘use’ is an actual directive in Svelte (https://svelte.dev/tutorial/actions). Unless they actually are actions you might want to re-consider their naming
node.js fixes that problem by having each module and it's dependencies separate from each other
The downside is that node_modules for things like React have 300MB+ these days
This is neat. Three small suggestions:
nav
element or an article
, how could the library support that?
.flex
class already. Libraries like this should user something more unique to ensure that there isn't an unintended inheritance.
[data-*]
selectors, but a scoped class like svelte-flex__flex
would work.id
, aria-label
)
Developer experience that doesn't compromise on the user experience! There's a ton of content in the article that's linked and not written out. Rich Harris' videos are a fun introduction, and an hour with the official tutorials should be enough to decide for yourself.
> Svelte is no different it is just smaller.
Smaller on "hello world" demos. As soon as we start using conditional rendering, transclusion, dynamic lists and subscriptions, application will have roughly the same size as apps built with ~3KB(minigzipped) vdom libraries. It is more important how much code it produces when using different composition primitives, for example if you take a look conditional rendering, you'll see that it generates an insane amount of code, so its size overhead will grow really fast in a big application.
> I feel awful that I’m in my early 20s and now I’m unemployed
I got laid off when I was 22, illegally got talked into signing a lay-off contract which kept me from asking for settling payment money. I was naiv back then but it went straight up from there.
​
Keep up teaching yourself current frameworks like React, Vue, heck even Angular (also Svelte looks promising). And get familiar with concepts like async/await and stuff like that. If you really want to stay with JavaScript of course. There are so many ways you could go from here and most when not all of them are good!
​
Don't be hard on yourself. These things are just part of your whole career.
It's really promising. I'll be using it on my next personal project, first for fun then to gauge how it performs on a real projet. The part I like the most about Svelte: https://svelte.dev/blog/write-less-code .
These are valid concerns! I'd argue that the lock-in situation isn't that much different from React (or Vue, Ember, Angular, whatever), but I hear where you're coming from. You certainly can use CSS-in-JS with Svelte (https://svelte.dev/blog/svelte-css-in-js), but a compiler that is aware of the structure of your markup as well as your CSS has the opportunity to get a lot smarter about things. (We're not taking full advantage of that yet though, just doing basic dead code removal etc.) And Svelte stores are very simple and portable, and work well with Redux, Immer, etc.
If you're not hitting performance issues today with React, that's great — I wouldn't advocate that someone rewrite an app that's working well. I do believe that there are some important trends we all need to be aware of: firstly, people aren't buying faster phones, they're buying cheaper phones. Secondly, user expectations are getting higher all the time. Thirdly, front end development is going to shift towards even lower-powered devices as the IoT market continues to boom (for better or worse).
> Is there something fundamentally different happening with svelte that I am missing?
In JSX, it's extremely hard — impossible, in some cases! — to know what's inside this expression: <p>{literallyAnything}</p>
. Does that expression evaluate to a component? An element? Text? A fragment? An array, containing... what? Because Svelte is more structured, the compiler can generate code that's highly optimised for each situation; it knows the possible states of your app ahead of time. With JSX, you just can't do that. Prepack gets you part of the way there, by literally 'running' your code, but it's not yet clear whether it'll be able to shift work to the compile step to the same extent. It's a much, much harder problem.
Svelte feels like JavaScript, HTML, and CSS all suddenly became really good friends and now share all their awesome stuff with eachother.
It legitimately feels like writing vanilla code. Everything is dead simple yet just as powerful as React, and because of this simplicity it’s super quick to learn. Try the <strong>interactive tutorial</strong> if you’d like to get started quick!
Regarding my previous comments, I've got an idea of two other, imho simpler solutions to this problem - not sure, whether it's what you're looking for.
await tick()
seems to make a difference REPL
<script>
import {tick} from 'svelte'
let elem
const customEv = new CustomEvent('customEv', {});
async function actionTest(node) {
await tick()
console.log('action runs', elem)
node.dispatchEvent(customEv)
}
function handleEvent(event) {
console.log('handleEvent', event)
}
</script>
<div bind:this={elem} use:actionTest on:customEv={handleEvent}>Test Action</div>
If I understand correctly the problem is about the way you dispatch the custom event. You probably shouldn't ever import anything from "Svelte/internal". Take a look at the docs and their way of dispatching events from action. https://svelte.dev/tutorial/actions
https://svelte.dev/repl/876a84c41d024301bdedc720e59652da?version=3.46.3
I checked on chrome. can you verify if you are also testing on the same version of repl.
You seem to know more about this topic than me. What approach/design pattern would you suggest when coming up against this particular issue?
Summary: How to bind to an input that will be slotted in by the parent?
Minimal reproduction: https://svelte.dev/repl/aaec6b04631447c7a6d7039ac654529f?version=3.46.3
I was wondering the same since I had some difficulty with this topic yesterday. Eventually, I arrived to the conclusion that two way binding is not supported on slot props- but I hope someone can prove me wrong.
Check this repl example. The second input will not update the displayed text because it's not "two way bound". Perhaps /u/KahChigguh can shed some light.
You can use the <script context="module"> tag at the top of your component to export a function.
I put together a quick REPL. Is this what you're looking for?
I used Svelte, made a cursed regex to split the code into words or (single) characters, assigned them a random color (with hsl(${Math.random()*360}, 100%, 50%)
), and put them back together in a pre
HTML block. Its like 20 lines of code lol
Passing data to a child is instinctual in Svelte. Passing the data from child to parent is less so. There are many ways to take care of this. Here are two examples using a store and bind. You can also use createEventDispatcher(), or throw pointers around.
I prefer using stores for more complex data, though I tend to declare them as separate entities in a JS file to be imported by the components that care about them.
For some advice: I'd recommend learning a framework like Svelte, it has loops in HTML and is super easy to learn & to use. For example, I built this table in a few minutes with 23 lines (not counting some not strictly necessary styling). Been using Svelte for a while now, and I wish someone told me about it earlier lol
In some cases, I've found that the <code>|local</code> modifier has prevented the out animation/transition from occuring.
>I'm wondering if it's worth trying Svelte out and how it plus SvelteKit compares with Next.js
You should definitely try it out! The official tutorial is a great place to start.
Just learn HTML and basic CSS to start, that has not changed in decades (and is the first two parts of the course)
Then you can learn some basic JavaScript and then learn the Svelte framework for JS because they have, bar none, the <em>best</em> tutorial I have seen
And then you’re off to the races really.
Here is the first one: https://svelte.dev/repl/e14fda16959d4ba3a20de821e2e80f97?version=3.46.2
Here is the second one: https://svelte.dev/repl/890daf703a294223b315c7343966f369?version=3.46.2
I put together this quickly, this is how I structure complex stores. It has an error I couldnt identify where the problem was, but that's basically the pattern I use.
https://svelte.dev/repl/25bb69c7a5264d1ea3de634c2658ee3b?version=3.46.2
Try creating a <strong>custom store</strong> that fetches and updates the data automatically! This way, you don’t even have to think about it at all. Every time you update your $tasks store for example, the getting and posting is automatically handled. This is the beauty of svelte’s reactivity.
James Quick has a great svelte tutorial ** where he’s created a todo app** and is bringing in the todos from Supabase.
Im actually also starting in my job a svelte project and I was thinking to kind of use an MVC model, something like this:
/views
/components: As the name indicates contains components
/pages: This would contain the page that will render all of the componentes and will have
a link in the router
/controllers: this will act like your store folder, Im planning to use this design pattern dont remember the name, where you have your store as private and you export a custom object with custome methods that will control the store, this is where the data will be validated also if necessary, eg:
https://svelte.dev/repl/25bb69c7a5264d1ea3de634c2658ee3b?version=3.46.2
/userController.js:
/model: will contained the calls to the endpoint getting information and formating it the way the application its needed, aslo will contained save functionality, eg:
https://svelte.dev/repl/25bb69c7a5264d1ea3de634c2658ee3b?version=3.46.2
/userModel.js
The use directive is not explained well by the Svelte tutorial. Basically, it just lets you run some code when a native DOM element is created/destroyed. So, let's say you have a simple HTML element (like an input or button) and you want to do something simple HTML element when it's created and destroyed. And this simple thing you want to do, you want to do to a lot of HTML elements. You could do this by creating a component to wrap the HTML element then you'd get the onMount/onDestroy message. But that seems heavy weight since the component would literally just be a single HTML element and all you really want is onMount/onDestroy. Also, you'd have to create a component wrapper for all HTML element types you want to support. Instead, you use the use directive to which lets you run some code when the HTML element is created and when it is destroyed. I have only used the use directive rarely (for small things like how input handling works.) For most things, I can just use normal component logic and use the component's onMount/onDestroy.
bind:X is just shorthand for: bind:X={X}. I don't like shorthands that rely on two variables having the same name, especially between a parent component and a child, but it's a concept in JavaScript so Svelte also uses it.
Other than "@html" there is "@debug" and that's all I can think of off the top of my head. See: https://svelte.dev/tutorial/debug
I would try to avoid adding divs and use the new style:directive
to pass the settings to the Child something like this > REPL
```
<script>
import Child from './Child.svelte'
let childSettings = { description: 'Some overlay description.', bottom: '100px', left: '70px', color: 'white', }
</script>
<div class="parent"> <Child {...childSettings}/> </div>
<div class="parent" style:background='teal'> <Child bottom="30px" left="30px" color="#afd6df">overlay filled via slot</Child> </div>
<style>
.parent {
position: relative;
width: 500px;
height: 300px;
background-color: black;
}
</style>
<script>
export let description = ''
export let bottom, left, color
</script>
<div class="child" style:bottom style:left style:color>
{description} <slot></slot>
</div>
<style> .child { position: absolute; } </style> ```
You can pass css variables to child component using --top="{top}px" --left="{left}px"
See docs https://svelte.dev/docs#template-syntax-component-directives---style-props
This repl for an example https://svelte.dev/repl/ccdb128d448c4b92babeaccb4be35567?version=3.46.2
Can this be used outside of the Svelte context? In a more complex app where data needs to be shared across many components, it's recommended to extract functionality into dedicated JS/TS store files. Most Svelte GraphQL libraries can only be used inside components, though.
So here’s the long and short about svelte stores: From the tutorial:
> As long as an object correctly implements the subscribe method, it's a store
As that suggests, the subscribe method is literally that only thing that matters, and the subscribe method needs to return an unsubscribe function. You could literally do this:
const store = { subscribe: () => () => ({}) }
In your .svelte file and you’ll be able to use the $ prefix throughout it, because that’s all the $ prefix is looking for.
So the short bit is: as long as you return an object with a subscribe method from your custom store, you’re good. Take a couple more seconds to gander at the examples in the tutorial and docs and just try to mimic those for starters. Then once you start to feel you understand those, read this article a couple dozen times cuz it’s way advanced while at the same time really dead simple and has some freaking awesome examples of custom stores even though that’s not the aim of the article. THEN study the bit about about store contracts in the docs for a good while.
At that point, you should have a good understanding of how stores work in svelte, and you’ll already have created some really nifty thing along the way. 😁
Fortunately, they themselves call out in their docs that headless/in-browser automated testing will be required, as will manual testing.
As far as solutions out there go claiming to be "accessible forward", I don't really mind this one... at least it isn't like AccessiBe claiming to solve all of your accessibility woes with the click of a button.
I would like to point out that there are packages within other frameworks that will nag at you if you do something bad - packages such as Ember A11Y.
Apologies, I don't speak Danish, so I'm slightly guessing at what you want.
I think you just need to add: $: {} around your "if (planet=="earth") {}" statement.
Here's an example that works if you type in "earth":
https://svelte.dev/repl/abd6fae7b6dd487bb1db5462bfb1094a?version=3.46.0
(I replaced tyngdekraft with acceleration, since gravity is a form of acceleration and you used acceleration as the variable name elsewhere in your code.)
Without the $:{} the if statement will only run once. The $:{} makes the statement run whenever one of the reactive variables inside of it changes.