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.
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
I had this same question sort of question not that long ago. You can do this using NPM to publish packages. Here is a tutorial (not mine) I used to make my first one.
Once you understand how that works you can see how packaging up reusable components can be really helpful. Just dive in, make mistakes, learn. :)
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
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
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.
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.
Here's a working example for you:https://codesandbox.io/s/distracted-kowalevski-78pev?file=/App.svelte
All vanilla CSS, not even SCSS. Nevertheless I'd highly advise you go with SCSS if and when possible. Svelte transitions are cool but I usually try to differentiate interactions and visuals as much as I can. For example I'd always opt-in for Svelte transitions where CSS transitions are simply not possible (e.g. route change). This example is far too simple for anything else than basic CSS.
I believe you are thinking of a svelte component template for deno. As of yet I am not familiar with anything of that sort. There exists a compiler for Deno so you could create your own template and use that as a base (or search github to see if someone else has done it). The compiler for Deno is called Snel: https://deno.land/x/[email protected]
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?
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)
Sure. Normally the giant CSS file is generated via the PostCSS macros that Tailwind implements: https://tailwindcss.com/docs/installation#include-tailwind-in-your-css
/* ./your-css-folder/styles.css */ @tailwind base; @tailwind components; @tailwind utilities;
Now that we're inlining the styles in the components on demand, all we need are the preflight styles so we can change the above to:
/* ./your-css-folder/styles.css */ @tailwind base; And end up with a much smaller file.
I am a back end developer primarily writing APIs in Go so I only have a limited exposure to the frameworks. That being said I really miss https://buefy.org but it still requires Vue 2.6 and same with https://vuetifyjs.com/en/ for different projects. Beyond that I actually find svelte easier for including legacy js code and frameworks. The latest version including Svelte Kit has what seems to me great typescript support.
Also I really wish the documentation was geared more towards non-node devopers and went into more detail of deploying static sites on S3 or comparable solutions.
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
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
The official strapi blog has a tutorial for Strapi + SvelteKit + Tailwindcss
https://strapi.io/blog/how-to-create-a-blog-with-svelte-kit-strapi
It has some mistakes, e.g. it's npx create-strapi-app instead of create-strapi-project , but I found it a good enough starting place when I tried playing with svelte with headless cms for the first time.
>When you set a listener, Cloud Firestore sends your listener an initial snapshot of the data, and then another snapshot each time the document changes.
https://firebase.google.com/docs/firestore/query-data/get-data
Are you, by any chance, modifying the Firestore document somewhere else?
Yep that's what I meant.
In Angular you can get that sort of reactive behavior, but you have to make a devil's bargain, either:
Get it for free with default ChangeDetectionStrategy, but pay an ever growing performance penalty as your app grows (since this runs change detection across everything pretty much anytime anything happens).
Use OnPush strategy and Observables via the async
pipe (similar to the $ in svelte). This is the best practice and leads experienced Angular devs to peruse components for that "OnPush" setting. In addition to being extra work, this means if you do use a regular template variable its behavior will be inconsistent, randomly updating when things like user clicks happen (which force change detection anyway) but otherwise often sitting out of date.
Thanks!
TL;DR Svelte is cool.
I personally like Vercel but the steps are similar on Netlify.
(Using Git - Recommended) Simply push your code to GitHub, GitLab or Bitbucket. In Vercel you can connect your GitHub, GitLab or Bitbucket account and code. Vercel will auto detect that it's a Svelte project and build it. Afterwards it will give you a URL to see your code live.
(Non Git) When you are done with your code, run "npm run build" and a folder with your compiled code will be generated. You can then copy/upload the code in the Build folder to whatever hosting provider you like.
Here is a link to Vercel so you can connect your Git repo if you want to go that route.
https://vercel.com/guides/deploying-svelte-with-vercel
Like others have said, you don't need Sveltekit, especially if you just have a simple landing page.
Hope this helps.
If you don’t mind running a separate backend, I love Directus (https://directus.io/open-source/#install) - super easy to use with your existing SQL databases, doesn’t pollute whatever data you have but can build powerful relations quickly, and gives you an easy to use admin interface for setting up your data models without needing to do anything more complicated than answering a few questions.
They provide a JS SDK which is pretty full featured (although there are a few things you might need to fall back to vanilla JS methods for, such as uploading files), and is as simple to import into whichever component you need to fetch data for (either using onMount or as part of an exported `load` function for routes).
Also can be uninstalled easily and leaves your data pure if you decide to code your own endpoints to talk directly to the database from SvelteKit, or swap out for a different back end.
Has the additional big benefit that your frontend can be deployed to static hosting like GH pages, Netlify, Vercel, Cloudflare Pages, or any other server you have that can serve static sites.
Not sure if it would interest you but the mobile framework: Framework7 has an option to use svelte! Looks good and runs really fast. Even now uses Vite instead of Webpack for the minification and bundling.
I don’t know why almost no online list of Svelte UX components doesn’t include Framework7. Have not used it, but it seems very complete and the number and detail of components appears to be top notch.
We use auth0 for our current SPA— their front end library is really easy and their tutorials are pretty great. I’ve been quite impressed how well they’ve been able to serve us as our auth needs have grown.
It’s nice because there are a lot of considerations for auth you need to make for a SPA since so much is handled on the client.
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.
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
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.
Sorry about that, my notifications were off- I got it working though
https://svelte.dev/repl/e3c7ab7c6ac2416991ae0e9efb8470a5?version=3.32.0
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
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
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
)
When I started web development, the lack of such of such low-code tools really surprised me. It feels natural to drag and drop components and place them visually instead of trying to find the right aesthetics by manipulating code.
I have not done any iOS development but something like SwiftUI seems to be right kind of tool for developing GUI to me. However, it would only be possible with a component based framework instead of CSS which is too low level for this kind of work.
> In most benchmarks, Svelte is slower
Nah.
These are some of the most exhaustive benchmarks and Svelte is considerably faster than React and even Preact (you can filter the frameworks):
https://rawgit.com/krausest/js-framework-benchmark/master/webdriver-ts-results/table.html
Also this real world app (not a MVC todo) with performance and other metrics:
Yeah it is strange. You can always technically debug the mobile browser from your desktop if you enable some Android Chrome flags and see.
OpenBoard doesn't work: https://play.google.com/store/apps/details?id=org.dslul.openboard.inputmethod.latin
FlorisBoard does: https://www.f-droid.org/packages/dev.patrickgold.florisboard/
AOSP does not
GBoard does not
Do you mean (a) deploying a sveltekit app as a docker container or (b) developing your sveltekit app in a docker container?
If it's the latter, I've tried it and highly recommend it. The vscode + docker integration is nothing short of amazing. This is especially true if you're learning or like to tinker around. You can run any command on the command line and install whatever you like. Whenever you finally manage to break your project lol, you can just reset your devcontainer. Also, if you ever want to work on that project after a while, the devcontainer can rebuild itself to the exact same state it was in, including any vscode extensions, settings, etc.
If you mean the former, I've never tried myself. I'd also be interested to know about the pros/cons. The question that immediately comes to mind is whether deploying a sveltekit app as a docker image would interfere with the caching & optimizations done by the cdn hosting providers. AKA, if you deploy your sveltekit app as a docker container, would you be be able to take advantage of things like vercel edge functions (or whatever the cloudflare or netlify equivalents) are?
Looks neat but how is it different from services such as PO Editor (or its alternatives) which offers managed translations accessible from an API?
I had great success converting a snowpack based svelte project to vite based using the following tutorial: https://www.section.io/engineering-education/svelte-with-vite-typescript-and-tailwind-css/. O
Caveat: Obviously you have to be careful to use git to make sure you don't blow away any of your existing changes which have not yet been committed prior to carrying out the conversion.
The result is much nicer. In particular using environment variables in the vite environment just worked out of the box unlike snowpack (recently) both in vite development and production modes.
It looks like a CMS would work great for this situation. I personally enjoy using Sanity CMS (https://www.sanity.io) and works great with SvelteKit. Their free your is more than reasonable but a paid plan isn't outages either.
const valid = 'prose-h1:text-red-600 prose-h1:m-14' === prose_h1CSS;
that's explicit enough for tailwind.
You can add prose-h1:*
to your safelist I think. Checkout out https://tailwindcss.com/docs/content-configuration#safelisting-classes
Tailwind scan files and extract classes to land in CSS file. It can't extract dynamically joined strings. There you can read docs chapter related to how does Tailwind create final CSS file https://tailwindcss.com/docs/content-configuration
You can customize tailwind to pretty much anything. What are you specifically looking to do?
https://tailwindcss.com/docs/adding-custom-styles
You can change, add, extend colours, class names, values, etc
Honestly, I've never used tailwind before. And I know it's not a regular css framework. You've intrigued me.
I followed https://tailwindcss.com/docs/guides/vite with the lessons learnt repo and... seemed to have worked surprisingly. But I had to replace instances of vue with svelte and replaced the h1 example with h2 (since vite's template styles up the h1 in App.svelte).
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?
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.
In some cases, I've found that the <code>|local</code> modifier has prevented the out animation/transition from occuring.
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.
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. 😁
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.
Here's an example of where "export const" is use~~ful~~d:
https://svelte.dev/repl/cf7cf882b767447296138a5a054287c1?version=3.46.0
App.svelte binds to the exported const prop "name" in TestComponent and displays the value.
Where is that useful? That's an exercise left up to the developer.
Just experimenting with a store, but I run into the same issue (REPL):
Cannot reference store value inside <script context="module">
But I need the store within context="module"
to be able to add an export function, right?
<script context="module"> import Item from './Item.svelte' import ItemStore from './ItemStore.svelte' $ItemStore = [ {name:'Item 1'}, ] export function addItem(item) { console.log('add item') // place some business logic here $ItemStore = [...ItemStore, item] } addItem( {name:'Item 2'} ) // just for testing </script>
{#each $ItemStore as item} <Item name={item.name}/> {/each}
No, I did not think about using a store.
I just found the official Nested components and Module context / Exports tutorials and tried to put a solution together.
Because the logic to populate "todos" reactive variable is being done in "onMount" that counts as a deferred variable change so the transition will play. If you just assign "todos" where the variable is being defined, it will not play the transition:
https://svelte.dev/repl/ed302b772eaf47bc8ead02179cca5760?version=3.45.0
However, I assume that your REPL is a simplified version? You might be able to achieve what you want by either using a store that's populated by another component or just pass the "todos" value as a prop into the component from the parent component that loads the "todos".
The transition animation page specifically states that animations should not play on first render. Are you loading the Todo list in some kind of delayed manner?
Seeing a repl would really help: https://svelte.dev/repl
I found this version. (I think it was SpinSpire)
https://svelte.dev/repl/88cee60b03f448cf90d7706fae235cdc?version=3.45.0
​
It is based on W3C Schools example. Link in the REPL
This is related to how svelte transitions work
quote from docs > A transition is triggered by an element entering or leaving the DOM as a result of a state change.
to use svelte/transition
element needs to be recreated, if you want to use ternary operator and not if/else you still need to recreate the element on state change, svelte also provides {#key darkModeValue}
{#key darkModeValue} <img src={darkModeValue ? "darkLogo.png" : "lightLogo.png"} alt="logo" in:fade={{ delay: 5000 }} on:click={toggleDarkMode} /> {/key}
but I think that's not what you are after. Other approach is using css for this effect, but you need two different element with absolute position overlapping each other, one fades out and other fades in depending on the state:
<div class="relative" on:click={toggleDarkMode} > <img src="darkLogo.png" alt="logo" class="transition opacity-0" class:opacity-100={darkModeValue}/> <img src="lightLogo.png" alt="logo" class="transition opacity-0" class:opacity-100={!darkModeValue}/> </div>
Something like that, this has a problem though, both elements exist at the same time in dom, both images are loaded.
In the end if else block is best you got for this use case.
Use takes an action is a function which takes an instance of the html element and any arbitrary properties and does something with the element you can find the docs on it here in our case our action renders a tippy.js tooltip on the element and accepts any arbitrary props you can also create your own reusable tooltips with the createTippy
function check the readme for more info
It's not a good practice to set this for every person who requests your page. If you are doing development and need the latest code use the dev tools to do a hard reload in the browser.
Cache invalidation is the other topic you need to know about
https://firebase.google.com/docs/hosting/manage-cache
https://fabricdigital.co.nz/blog/how-to-hard-refresh-your-browser-and-clear-cache
Maybe take a look at D3: https://d3js.org/
This library handles large dataset animation efficiently.
To find more info talking about D3 and Svelte, try "amelia wattenberger svelte". Just an idea
"the moment u include a bigger framework, the smaller framework is dwarfed in your bundle"
ckeditor has virtual dom and seems to be more of a component framework than a component (sure u can use it as a component)
heres some benchmarks for bundle sizes: https://www.freecodecamp.org/news/a-realworld-comparison-of-front-end-frameworks-with-benchmarks-2019-update-4be0d3c78075/
frameworks/components that use virtual dom are bloat. another huge advantage of figuring out/compiling ur apps reactivity ahead of time - no unnecessary virtual dom comparisons.
You can check out AceEditor. It has multi-language support and you can define your own languages.
Even if you dont use it, it might give you some ideas how to approach this.
It's pretty advanced though and even uses web workers (I think) to allow faster parsing and syntax highlighting.
https://ace.c9.io/ I think they have a GitHub page too.
You're going to want to rewrite that to not use DOM methods. There are a lot of pitfalls with your current implementation. It could look something like this: https://svelte.dev/repl/bc747eb8b0324ae69fe2160a218590d6?version=3.44.3
There’s some good ideas here. Another one might be to use the $$restProps here.
You could pass $$restProps into a style wrapper element.
u/CoqeCas3 tagging you as you may find this useful as well
Are you familiar with the :global() modifier? I find that the :global() modifier takes care of any need to pass in props that are only used for styling, which is nice as it keeps styling responsibilities within the style tags and application logic within the script tags.
I had a similar misconception for quite a while. What I recently discovered is the script context=‘module’ thing is actually not exclusive to svelte kit, it’s part of svelte core, kit just takes advantage of it.
But yeah with SSR enabled, the components html gets rendered on the server first, and it tries to include any variables you have in the markup.
I had a similar misconception for quite a while. What I recently discovered is the script context=‘module’ thing is actually not exclusive to svelte kit, it’s part of svelte core, kit just takes advantage of it.
But yeah with SSR enabled, the components html gets rendered on the server first, and it tries to include any variables you have in the markup.
Looks awesome. One thing that would look smoother in my opinion would be the radar icon sliding to the position you click rather than instantly appearing.
It’s easy to do in Svelte they even have it in the intro docs - https://svelte.dev/tutorial/deferred-transitions
Can you please provide a REPL that reproduces this? It seems to work fine for me: https://svelte.dev/repl/55eff669d2194f948af198437a16f0d0?version=3.18.2
In general, a REPL will save time for anyone who's trying to help you and it may help you narrow down exactly what's going wrong.