657 Matching Annotations
  1. Jan 2021
    1. beforeUpdate(async () => { console.log('the component is about to update'); await tick(); console.log('the component just updated'); });
    1. But Svelte doesn't work like that - all css is statically compiled, and changing myCSS doesn't update the head component.
    1. And this way also fits more with data down, actions up.
    2. So you might ask what is the benefit of using the event dispatcher over just passing a prop down? In some scenarios, you will need to add an action to a button that is 3 or more components down and passing a prop all that way is considered prop drilling (it is frowned upon by some, meh each to their own). However in the case of using an event dispatcher, even though these events don’t bubble, we can easily pass them up using a shortcut that Svelte has.
    3. Depending on what other component libraries you’ve used, you may be used to handling events by passing callback functions to component properties, or using a special event syntax – Svelte supports both, though one is usually more appropriate than the other depending on your situation. This post explains both ways.
    1. It’s something that we’re already used to do naturally with HTML elements. Let’s demonstrate how using the <slot> component works by building a simple Card component
    1. If it's behaviour that you can imagine needing to reuse among multiple components, or if it's something that you can imagine applying to an element inside an {#if ...} block (for example), then it probably belongs in an action. It it's something that 'belongs' to the component itself, rather than a specific element, then it's probably more of a lifecycle thing.
    2. The use:action method seems cleaner, but aside from that, are there any underlying differences between these two methods that would make one preferred over the other in certain situations?
    1. A Svelte component that monitors an element enters or leaves the viewport/parent element. Performant and efficient thanks to using Intersection Observer under the hood. Can be used in multiple projects including lazy loading images, infinite scrolling, playing/pausing the video when in the viewport, tracking user behaviour firing link pre-fetching and animations and many many more.
    1. // super-simple CSS Object to string serializer const css = obj => Object.entries(obj || {}) .map(x => x.join(":")) .join(";");
    1. Popper for Svelte with actions, no wrapper components or component bindings required! Other Popper libraries for Svelte (including the official @popperjs/svelte library) use a wrapper component that takes the required DOM elements as props. Not only does this require multiple bind:this, you also have to pollute your script tag with multiple DOM references. We can do better with Svelte actions!
    1. {#each charts as chart, i} <div class="wrapper"> <div class="icon" on:click={e => instances[i].handle(e)}>Click</div> <div class="content"> <svelte:component this={charts[i]} bind:this={instances[i]} /> </div> </div> {/each} ...where each child component exports a handle method: <script> let event; export function handle(e){ event = e; }; </script>
    1. If you manage to make Svelte aware of what needs to be tracked, chances are that the resulting code will be more performant than if you roll your own with events or whatever. In part because it will use Svelte's runtime code that is already present in your app, in part because Svelte produces seriously optimized change tracking code, that would be hard to hand code all while keeping it human friendly. And in part because your change tracking targets will be more narrow.
  2. Dec 2020
    1. The more I think about this, the more I think that using the context API (for all the stores — page, preloading and session) is the most regret-proof approach, using the proposal above

      Looks like this is the approach that they went with

    1. session can be used to pass data from the server related to the current request. It is a writable store, meaning you can update it with new data. If, for example, you populate the session with the current user on the server, you can update the store when the user logs in. Your components will refresh to reflect the new state
    2. Preload functions are typically used to load data that the page depends on, hence its name. This avoids the user seeing the page update as it loads, as is typically the case with client-side loading.
    1. With this change, we can re-run preload when the session store changes, e.g. as a result of something like this in a nav bar:
    2. I have a feeling that this functionality is scuppered by #415 - since my browser caches the page for 10 minutes, meaning that the page is never hit and thus the preload is never run, regardless of whether session has been changed or not.
    1. I'd instinctively associate a this.cache() inside preload with the preloaded data only -- meaning no matter what crazy thing I did inside preload, the returned data would be cached locally, where local means either the client or server.
    1. Just realised this doesn't actually work. If store is just something exported by the app, there's no way to prevent leakage. Instead, it needs to be tied to rendering, which means we need to use the context API. Sapper needs to provide a top level component that sets the store as context for the rest of the app. You would therefore only be able to access it during initialisation, which means you couldn't do it inside a setTimeout and get someone else's session by accident:
    1. I put together a POC that resembles react-rails and helps with server- and client-side rendering, and provides a view helper (svelte_component):
    2. webpacker-svelte misses server-side rendering, though.
    1. People really don't stress enough the importance of enjoying what you're programming. It aids creativity, makes you a better teammate, and makes it significantly easier to enter a state of flow. It should be considered an important factor in choosing a web development framework (or lack thereof). Kudos!
    1. Now that I got a clearer picture, I still don't understand why that error message (cannot bind to variable declared with let:) is there, in the sense that for me it would make a lot of sense to both bind (which connects bidirectionally the App#item variable with the Component#item variable) and also let (which connects the slot#item variable with the Component#item variable, allowing data to flow from slot to Component, and thus to the top-level App via the bind syntax.
    2. Binding In a nutshell, the purpose of this is to update the variable programmatically or when the DOM element/components updates it.
    1. Is using bleeding edge tech risky and foolish? How much blood are we talking about? My experience tells me Svelte is a safe choice, more leading edge than bleeding.
    2. Svelte is its own language, not plain HTML+CSS+JS

      its own _

    3. React abstracts the DOM with functionally pure declarative rendering and provides escape hatches back to mutable imperative DOM land. This is a profound philosophical difference that Rich gave a talk about.
    4. Making UIs with Svelte is a pleasure. Svelte’s aesthetics feel like a warm cozy blanket on the stormy web. This impacts everything — features, documentation, syntax, semantics, performance, framework internals, npm install size, the welcoming and helpful community attitude, and its collegial open development and RFCs — it all oozes good taste. Its API is tight, powerful, and good looking — I’d point to actions and stores to support this praise, but really, the whole is what feels so good. The aesthetics of underlying technologies have a way of leaking into the end user experience.
    5. It's true that Svelte does not allow you to map over children like React, but its slot API and <svelte:component> provide similarly powerful composition. You can pass component constructors as props and instantiate them with <svelte:component>, and use slots and their let bindings for higher order composition. It sounds like you're thinking in virtual DOM idioms instead of Svelte's.
    6. since the Svelte compiler actually does useful things (I have the same opinion on TypeScript). I love the idea of actual reactivity, rather than re-render + diff based solutions like React.
    7. These are valid comments. I think it is worth noting that svelte didn’t choose a non-javascript method for fun or because we think we should redesign the language. The additional constructs, for the most part, are there to allow svelte to more clearly work out exactly what is going on in the code in order to optimise. In short svelte needs a certain amount of information to do what it does and pure javascript is often difficult to analyse in this way. But I appreciate your concerns and comments and we try to take all feedback on board where we can. So thank you!
    8. My frustration is mainly from Svelte's choices that are very un-JavaScript-like. It doesn't have to be "like React/Vue". React is React because it doesn't restrict what you can do with JavaScript for the most part. It's just common FP practice to fold/map.
    1. Don't worry about the fact that we're redeclaring the foo function for every component instance — Svelte will hoist any functions that don't depend on local state out of the component definition.
  3. Nov 2020
    1. Really? I've been using Flutter for about a week and Svelte seems an order of magnitude better designed. I find Flutter overly complicated.
    2. Svelte by itself is great, but doing a complete PWA (with service workers, etc) that runs and scales on multiple devices with high quality app-like UI controls quickly gets complex. Flutter just provides much better tooling for that out of the box IMO. You are not molding a website into an app, you are just building an app. If I was building a relatively simple web app that is only meant to run on the web, then I might still prefer Svelte in some cases.
    1. If I understand the problem correctly, just changing the imports to point to svelte/internal isn't enough because they could still point to different packages depending on how your components are bundled. It solved your specific issue, but if you had two completely unrelated Svelte components compiled to vanilla javascript bundled with Svelte, you'd still hit issues with mismatching current_component when using slots or callbacks.
    2. It sounds like another case of multiple svelte/internal modules? I think we need to look into reworking how svelte/internal keeps track of the current component since it breaks when mixing components not bundled with the app. It sounds like we need to find a way to pass Svelte's internal runtime state when instantiating components, since slots and callbacks end up mixing different svelte/internal together.
    1. As mentioned in #2937, this is the sort of thing that happens when you have two copies of Svelte's internal scheduler running. If you're importing the compiled version of an external Svelte component into another Svelte component, this is what you end up with. There's a svelte field in package.json that's respected by rollup-plugin-svelte and which is intended to point at the uncompiled Svelte source, so that the external component can be bundled together with the main app, without any duplicated internals.
    2. DOM element binding using the bind:this attribute doesn't work apparently
    1. In the past, I tried to create some proof of concepts with svelte, but I usually ended up missing some of the features that RxJS provides. Now that I know that they complement each other well, I will grab this combination more often
    2. For me, this makes Svelte the most reactive "framework" at the moment
    1. Because of those similarities, it's possible to automate some of the changes.
    2. Those frameworks are used in a similar fashion, but conceptually use quite different approaches (Vue is a more traditional one, a library, and Svelte is a "dissapearing framework").

      interesting wording: Svelte is a "disappearing framework".

      • Functional blockchain library in Typescript
      • Svelte & Sapper for all things UI.
      • Blockchain sync with IndexedDB and reactivity hook.
      • Created some mini-apps to refine and test the core functionality.
      • User Authentication flow.
      • MVP: Kanban app.
    1. I encounter this problem in all of my Svelte projects- feels like I'm missing something. Fighting it with absolute positioning usually forces me to re-write a lot of CSS multiple times. Is there is a better way to solve this that I've overlooked?
    1. Svelte's advantage here is that it indicates the need for an update at the place where the associated data is updated, instead of at each place the data is used. Then each template expression of reactive statement is able to check very quickly if it needs to rerender or not.
    2. Converting Angular components into Svelte is largely a mechanical process. For the most part, each Angular template feature has a direct corollary in Svelte. Some things are simpler and some are more complex but overall it's pretty easy to do.
    3. We don't use "attribute directives" much which makes things easier.
    4. Directives like ng-if="info.report.revenue" sort of work in Angular if info.report is undefined, in that the ng-if becomes false. But the Svelte equivalent {#if info.report.revenue} throws an error. For now we're using lodash get in places where we need to and looking forward to Svelte support for optional chaining.
    5. Embedding Svelte inside Angular is pretty easy, for the most part. I wrote a function that would take in a Svelte component and generate an Angular controller class.
    6. It's really helpful that Svelte stores are easy to use in plain JS. We can change a state store over completely to Svelte and make the Angular components subscribe to that store as well without needing to maintain and sync 2 copies of the state.
    7. Svelte slots are much easier to use and reason about than Angular transclude, especially in cases where you don't want an extra wrapper element around the slot content.
    1. Any “unused” css will be stripped out when compiling, and since the compiler correctly sees that we have no p tags in App.svelte , it throws out that bit of css.
    1. After a few hours experimenting (updated NPM, NODE, ...) I found that renaming _smui-theme.scss to smui-theme.scss (without underscore prefix) solved the problem. I don't understand the mechanics behind (why in documentation is file with prefix).
    1. If your Svelte components contain <style> tags, by default the compiler will add JavaScript that injects those styles into the page when the component is rendered. That's not ideal, because it adds weight to your JavaScript, prevents styles from being fetched in parallel with your code, and can even cause CSP violations. A better option is to extract the CSS into a separate file. Using the emitCss option as shown below would cause a virtual CSS file to be emitted for each Svelte component. The resulting file is then imported by the component, thus following the standard Webpack compilation flow.
    2. If you rely on any external dependencies (files required in a preprocessor for example) you might want to watch these files for changes and re-run svelte compile. Webpack allows loader dependencies to trigger a recompile. svelte-loader exposes this API via options.externalDependencies.
    1. Frontend frameworks are a positive sum game! Svelte has no monopoly on the compiler paradigm either. Just like I think React is worth learning for the mental model it imparts, where UI is a (pure) function of state, I think the frontend framework-as-compiler paradigm is worth understanding. We're going to see a lot more of it because the tradeoffs are fantastic, to where it'll be a boring talking point before we know it.
    2. Since you've been using Svelte for a few months after using React, haven't you been hit by the lack of composability in Svelte?Passing around components as variables is such a common pattern in React, and there's no good replacement in Svelte. The lack of dynamism in components and styles makes theming and crafting reusable components (outside of simple widgets) very tedious [1][2]. I'm genuinely curious how someone can come from React and not be bothered by it.
    3. I don't love that you have to re-assign a object/array variable to get Svelte to notice it changed
    4. Stores are such an amazing abstraction.
    1. Another possible syntax is {#slot bar}<Foo/>{/slot}, which would also allow a bunch of DOM nodes and components inside the slot, without them needing to be from a single component

      I like it

    1. This subscription function must be immediately and synchronously called with the store's current value upon calling .subscribe. All of a store's active subscription functions must later be synchronously called whenever the store's value changes.
    2. Assignments to $-prefixed variables require that the variable be a writable store, and will result in a call to the store's .set method.
    1. What bothers me most from Svelte: <!-- I want to bind the value of this custom input just like I would bind to normal input --> <input bind:value="query" /> <!-- works --> <search-input bind:value="query" /> <!-- doesn't work :/ -->

      I think this works in current Svelte

    2. Essentially, for version 2 I'd like to move away from the Mustache-esque template syntax to something a bit lighter and more modern, which boils down to using one curly brace instead of two:
    3. The success of JSX has proved that the second curly is unnecessary. Moreover, a lot of people — particularly those who have been exposed to React — have a visceral negative reaction to double curlies, many of them assuming that it brings with it all the limitations of crusty old languages like Mustache and Handlebars, where you can't use arbitrary JavaScript in expressions.
    1. <input {...omitBy({pattern: undefined}, isUndefined)}>
    2. For now, using spread attributes allows you to control which attributes appear on an element. <div {...foo}> where foo is an object of attribute keys and values will add/remove attributes according to which are present and non-null.
  4. Oct 2020
    1. My version of https://svelte.dev/repl/9c7d12357a15457bb914705702f156d1?version=3.19.2 from https://github.com/sveltejs/svelte/issues/4586

      to try to simplify and help me understand it better.

      So the lack of synchronousness is only noticed inside handleClick.

      By the time the DOM gets updated, it has a consistent/correct state.

      In other words, the console.log shows wrong value, but template shows correct value. So this might not be an actual problem for many/most use cases.

    1. I too have been confused by behavior like this. Perhaps a clearly defined way to isolate atomic units with synchronous reactivity would help those of us still working through the idiosyncrasies of reactivity.
    2. For performance reasons, $: reactive blocks are batched up and run in the next microtask. This is the expected behavior. This is one of the things that we should talk about when we figure out how and where we want to have a section in the docs that goes into more details about reactivity. If you want something that updates synchronously and depends on another value, you can use a derived store:
    1. I don't want Svelte to go out of its way to try to catch all these edge cases. It would require lots of fragile heuristics in the compiler. I want a solid compiler I can trust, not something magic but often out of service. I want it the simplest possible.
    2. There's an issue #3368 for describing better what triggers reactive updates, as I do think there is some stuff we could be more explicit about
    1. Presumably this is so that you can import React libraries, even if they depend on ReactDOM, and they will work with Svelte instead.

      Reminds me of Wine. IIRC they have some system calls that they just make to be no-ops on Linux.

    1. Svelte forces you do to do all kinds of things in a very specific way (as does every other framework/library), those constraints generally make for a better experience.
    2. This is basically a design goal at this point, even though it has evolved organically.
    3. One of Svelte's advantages, for me, is that I can test out ideas with relatively few lines of code. the #with feature could save me from adding a separate component for the content of an #each loop. I get frustrated when I have to create a new file, move the content of the #each clause, import it as a component, and add attributes and create exports for that, and implement events to send messages back, and event handlers, when I just wanted to test a small feature.
    4. my second preference would be for let, probably #let expr as name for consistency with #each.
    1. You can see that behaviour in this example. Select a range of text and hit the tab key. Because the <textarea> value changes, the current selection is cleared and the cursor jumps, annoyingly, to the end.
    1. const { getByRole } = render(<input bind_value={text}>)
    2. svelte-htm - Hyperscript Tagged Markup for svelte; a jsx-like syntax using Tagged Templates
    3. For the sake of best compatibility we convert the className attribute to class for svelte.

      Svelte refuses to standardize on any way to pass a CSS class. I thought className was actually the most common name for this prop though even in Svelte...

    4. For event listeners we support the standard jsx naming convention onEventname (this is converted to on:eventname in svelte) as well.