enigmare/v2-crawler
1889
1{"id":"stack-58262380","source":"stackoverflow","questionId":58262380,"title":"How can I pass parameters to on:click in Svelte?","tags":["svelte","svelte-3"],"text":"Title: How can I pass parameters to on:click in Svelte?\nTags: svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nBinding a function to a button is easy and straightforward:\n\n```\n\n Clicks are handled by the handleClick function!\n\n```\n\nBut I don't see a way to pass parameters (arguments) to the function, when I do this:\n\n```\n\n Oh no!\n\n```\n\nThe function is called on page load, and never again.\n\nIs it possible at all to pass parameters to function called from `on:click{}`?\n\nI found the proper way to do it (see comments). Calling the function from an inline handler works.\n\n```\n handleClick(\"parameter1\")}>\n It works...\n\n```\n\n========================================\n\nTop Answer:\nRich has answered this in a comment, so credit to him, but the way to bind parameters in a click handler is as follows:\n\n```\nonDelete(projectId)}>delete\n\n function onDelete (id) {\n ...\n }\n\n```\n\nTo provide some extra detail for people who also struggle with this, and it *should* be in the docs if it isn't, you can also get the click event in such a handler:\n\n```\nonDelete(event)}>delete\n\n function onDelete (event) {\n // If it's a custom event you can get the properties passed to it:\n const customEventData = event.detail\n\n // If you want the element, you guessed it:\n const targetElement = event.target\n ...\n}\n\n```\n\nSvelte documentation/tutorial: inline handlers\n\n========================================\n\nCode:\n```html\n<button on:click={handleClick}>\n Clicks are handled by the handleClick function!\n</button>\n```\n\n```html\n<button on:click={handleClick(\"parameter1\")}>\n Oh no!\n</button>\n```\n\n```html\n<button on:click={() => handleClick(\"parameter1\")}>\n It works...\n</button>\n```\n\n```text\non:click{}\n```\n\n```html\n<button on:click={handleClick(\"arg1\")}>My awesome button</button>\n```\n\n```html\n<button on:click={() => handleClick(\"arg1\", \"arg2\")}>\n My awesome button\n</button>\n```\n\n```text\nhandleClick(\"arg1\")\n```\n\n```js\nconst handleClick = (parameter) => () => {\n // Actual function\n}\n```\n\n```html\n<button on:click={handleClick('parameter1')>\n It works...\n</button>\n```\n\n```js\nconst handleParameter1Click = () => handleClick('parameter1');\n```\n\n```js\nlet parameter1;\nconst handleParameter1Click = () => handleClick(parameter1);\n```\n\n```text\nhandleClick('parameter1')\n```\n\n```html\n<a href=\"#\" on:click|preventDefault={onDelete.bind(this, project_id)}>delete</a>\n```\n\n```js\nfunction onDelete(id) {\n}\n```\n\n```html\n<a href=\"#\" on:click|preventDefault={() => onDelete(projectId)}>delete</a>\n<script>\n function onDelete (id) {\n ...\n }\n</script>\n```\n\n```html\n<a href=\"#\" on:click={event => onDelete(event)}>delete</a>\n<script>\n function onDelete (event) {\n // If it's a custom event you can get the properties passed to it:\n const customEventData = event.detail\n\n // If you want the element, you guessed it:\n const targetElement = event.target\n ...\n}\n</script>\n```\n\n```html\n<input type=\"text\" on:keydown={event => onKeyDown(event)} />\n```\n\n```js\nconst onKeyDown = debounce(handleInput, 250);\n\nasync function handleInput(event){\n console.log(event);\n}\n```\n\n```none\n{#each data as item}\n <li on:click={handle(item)}>{item.name}</li>\n{/each}\n```\n\n```js\n// Utility function\nconst will = (f, v) => () => f(v);\n// In a Pug template, we can again assign with =\nFoo(on:click='{will(click, i)}')\n```\n\n```text\n!=\n```\n\n```text\n!=\n```\n\n```text\nFoo(on:click!='{() => click(i)}')\n```\n\n```text\nattr=\"{foo && bar}\"\n```\n\n```text\nattr=\"foo && bar\"\n```\n\n```text\n=\n```\n\n```text\n!=\n```\n\n```text\n!=\n```\n\n========================================\n\nComments:\n- Thats what even the docs have not explicitly mentioned. But yes thats the way for now i think.. Until they come up with a different solution..\n- This isn't a hack, it's *how it works*. It's explicitly mentioned in the tutorial svelte.dev/tutorial/inline-handlers\n- Thanks for your comments! This \"hacky way\" of doing it is not so bad after all, but I would dare say that the docs and tutorial are not *very* explicit about this. Maybe it's just me, though.\n- For what it's worth, the reason `on:click{() => clickHandler(param)}` is, as Rich said above, \"how it works\", is because one needs to pass a *reference* to the function needing to be executed. By calling `on:click{clickHandler(param)}`, you are executing the function immediately. That's not what you want.\n- Don't do this! Just create an inline function (`on:click={() => handleClick('parameter1')}`)\n- Just realised that's the proposal you were responding to. The reason I advise against the currying approach is twofold — first, it's less immediately clear what's happening (people tend to assume that `handleClick('parameter1')` is what happens *when the click happens*, incorrectly. Secondly, it means that the handler needs to be rebound whenever parameters change, which is suboptimal. Currently, there's a bug, meaning that doesn't work anyway svelte.dev/repl/a6c78d8de3e2461c9a44cf15b37b4dda?version=3.1‌​2.1\n- True, I was not aware of that bug never encountered it myself. Then again in the codebase I am working on we never pass parameter like this, they are almost always objects and that seems to work: svelte.dev/repl/72dbe1ebd8874cf8acab86779455fa17?version=3.1‌​2.1\n- I updated my answer with some currying pitfalls and other reflections. Thanks for the input\n- Ah yep, it'll work with objects, as long as the reference itself doesn't change (and the underlying bug will get fixed in due course as well)\n- Why are you using links for buttons, when they have no URL?\n- Because I build PWAs which have links as fallbacks, so it's more a reason of habit. It could easily be a button.\n- I think a button will submit the form on the page even if its outside the form. At least that was what I was seeing even with `...`\n- Looks like the link to the docs is now broken. I assume this is after the update to all the docs with svelte 5. Is there a new link to this part of the tutorial?\n- for me it is not work only handleClick(\"arg1\")}>\n- `on:click={() => handleClick(\"arg1\", \"arg2\")}` is the way to go\n- At a philosophical level, I guess having it this way also makes it as close to vanilla JavaScript as possible. The idea of \"when in doubt, do it like JavaScript\" holds here (and of course they've done some work behind the hood to make it efficient). In fact, if I hadn't bothered looking it up I'd probably have intuitively gone for this solution anyway :P\n- the `sort` function in that REPL returns a function, and that function handles the click. when the component is loaded, `sort` is called twice, with the name of the column, and returns two functions, one which will sort by id, and one which will sort by val.\n- If you can prove this works for you in the REPL I would be shocked. Here's a REPL showing that the functions will indeed run on initial render and not on click at all. svelte.dev/repl/741340eb0ec34ae89601a1f069747c22?version=3.4‌​4.1\n- You are right, I dont remember why I wrote that it worked back then.\n- Happens to me all the time, things stop working or change completely so often.\n- I've actually seen this work before too, and I *dont* know why.\n- I was losing my mind. Thanks very much for this Pug solution...\n- ***What*** appears to work in this particular situation? Which of Rich's comments is referred to? He has made a lot comments.\n- OK, the OP may have left the building: *\"Last seen more than a month ago\"*","metadata":{"transformedAt":"2026-08-18T18:33:40.652Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":245,"estimatedTokens":1857}}2{"id":"stack-58213585","source":"stackoverflow","questionId":58213585,"title":"Svelte 3 - How to loop each block X amount of times","tags":["javascript","arrays","svelte","svelte-3"],"text":"Title: Svelte 3 - How to loop each block X amount of times\nTags: javascript, arrays, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI'm hoping to find a way to iterate over an #each block a set amount of times in Svelte 3. In Vue I would do something like this:\n\n```\n\n- \n```\n\nBut as I understand Svelte handles loops much differently using the .length property of the array being #eached. Is there some way to pull off something like this in Svelte?\n\n```\n{#each 3 as i}\n \n- \n{/if}\n```\n\n========================================\n\nTop Answer:\nYou can use `{#each ...}`, like:\n\n```\n{#each Array(3) as _, i}\n \n- {i + 1}\n{/each}\n```\n\n========================================\n\nCode:\n```text\n<li v-for=\"i in 3\"><!-- somecontent --></li>\n```\n\n```text\n{#each 3 as i}\n <li><!-- somecontent --></li>\n{/if}\n```\n\n```text\n{#each {length: 3} as _, i}\n <li>{i + 1}</li>\n{/each}\n```\n\n```text\n{#each { length: 8 }, rank}\n <div>{rank}</div>\n{/each}\n```\n\n```text\n#each\n```\n\n```text\nas\n```\n\n```text\n{#each Array(3) as _, i}\n <li>{i + 1}</li>\n{/each}\n```\n\n```text\n{#each ...}\n```\n\n```text\n{#each Array.from(Array(b+1).keys()).slice(a) as i }\n <h1>{i}</h1> \n{/each}\n```\n\n```text\n{#each Array.from(Array(100+1).keys()).slice(1) as i }\n <h1>{i}</h1> \n{/each}\n```\n\n```text\na\n```\n\n```text\nb\n```\n\n```text\n// script\nexport let numOfPages = 10\nconst pagesArray = Array.from({length: numOfPages}, (x, i) => i+1) // [1,2,3,4,5,6,7,8,9,10]\n\n// template\n{#each pagesArray as page}\n <li>{page}</li>\n{/each}\n```\n\n```text\n/* code */\nexport function range(from, to) {\n const result = [];\n let i = from;\n\n while (i <= to) {\n result.push(i);\n i += 1;\n }\n\n return result;\n}\n```\n\n```text\n<!-- template -->\n{#each range(1, 3) as i}\n <li><!-- --></li>\n{/each}\n```\n\n```js\nfunction* range(start, end) {\n for (let i = start; i < end; i++) yield i;\n}\n```\n\n```text\nfunction* range(start: number, end: number): Generator<number> {\n for (let i = start; i < end; i++) yield i;\n}\n```\n\n```html\n{#each range(1, 3) as i}\n <li><!-- --></li>\n{/each}\n```\n\n```text\nfunction* repeat(count: number): Generator<number> {\n for (let i = 0; i < count; i++) yield i;\n}\n```\n\n```html\n{#each repeat(4) as i}\n <li><!-- --></li>\n{/each}\n```\n\n```text\n<=\n```\n\n```text\n<\n```\n\n========================================\n\nComments:\n- There's an up-to-date (Svelte 5) write up on this here. Though the answers here are pretty similar.\n- Is there a way to have this #each block re-render anytime the number variable changes (from 3 to 5 for example?). I'd like to render a certain number of form items based on previous user input. Ex: How many cars do you have? --> Number of Text Inputs created for each Car Make/Model, for example.\n- @Doomd: yes, see an example: svelte.dev/repl/fef2db8c70064c49913a6608ebf633b9?version=3.1‌​8.2\n- If you're going to do that - please key it @doomd so that Svelte can keep track of additions/removals: {#each x as _, i (x.id)} or similar.\n- This answer better suits my needs because for a long iteration it is better not to create a looooong array I think.\n- Agreed, much better solution IMHO too\n- Docs: svelte.dev/docs#template-syntax-each \"You can use each blocks to iterate over any array or array-like value — that is, any object with a length property.\"\n- An array with length = 10000 is just an object with { length: 10000 } and a few extra methods. There is, afaik, no substantial overhead between writing Array(10000) and { length: 10000 }\n- Very cool, not as useful for 1-X since you can use one of the other simpler approaches for that. But this has some interesting possibilities for pagination svelte.dev/repl/509ac9d542644544a282966aef6879e1?version=3.4‌​4.3\n- *This method allows for a lot of flexibility without using up memory for an array.* Good thinking, but I think Svelte internally creates an array with all the numbers anyway. github.com/sveltejs/svelte/pull/8626 But maybe they will optimize this in the future, so perhaps not a bad idea to use generators anyway.\n- @PeppeL-G Thanks for catching that! You're right. The code has moved around a bit since that pull request, but if the object's length is undefined (as it would be with a generator) Svelte currently passes it to `Array.from(iter)`. I removed the claim about reduced memory usage and also hope Svelte optimizes their `#each` blocks for generators.","metadata":{"transformedAt":"2026-08-18T18:33:40.652Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":181,"estimatedTokens":1103}}3{"id":"stack-56488202","source":"stackoverflow","questionId":56488202,"title":"How to persist svelte store","tags":["svelte","svelte-store"],"text":"Title: How to persist svelte store\nTags: svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\nIs there any direct option to persist svelte store data so that even when the page is refreshed, data will be available. \n\nI am not using local storage since I want the values to be reactive.\n\n========================================\n\nTop Answer:\nFor Svelte Kit I had issues with SSR.\nThis was my solution based on the Svelte Kit FAQ, the answer by Matyanson and the answer by Adnan Y.\n\nAs a bonus this solution also updates the writable if the `localStorage` changes (e.g. in a different tab). So this solution works across tabs. See the Window: storage event\n\nPut this into a typescript file e.g. `$lib/store.ts`:\n\n```\nimport { browser } from '$app/env';\nimport type { Writable } from 'svelte/store';\nimport { writable, get } from 'svelte/store'\n\nconst storage = (key: string, initValue: T): Writable => {\n const store = writable(initValue);\n if (!browser) return store;\n\n const storedValueStr = localStorage.getItem(key);\n if (storedValueStr != null) store.set(JSON.parse(storedValueStr));\n\n store.subscribe((val) => {\n if ([null, undefined].includes(val)) {\n localStorage.removeItem(key)\n } else {\n localStorage.setItem(key, JSON.stringify(val))\n }\n })\n\n window.addEventListener('storage', () => {\n const storedValueStr = localStorage.getItem(key);\n if (storedValueStr == null) return;\n\n const localValue: T = JSON.parse(storedValueStr)\n if (localValue !== get(store)) store.set(localValue);\n });\n\n return store;\n}\n\nexport default storage\n```\n\nThis can be used like this:\n\n```\nimport storage from '$lib/store'\n\ninterface Auth {\n jwt: string\n}\n\nexport const auth = storage(\"auth\", { jwt: \"\" })\n```\n\n========================================\n\nCode:\n```html\n<script>\n import { writable } from \"svelte/store\";\n const store = writable(localStorage.getItem(\"store\") || \"\");\n\n store.subscribe(val => localStorage.setItem(\"store\", val));\n</script>\n\n<input bind:value={$store} />\n```\n\n```text\nonMount(() => {\n console.log('I only run in the browser');\n});\n```\n\n```js\n// store.js\nimport { writable } from 'svelte/store';\n\nexport const count = writable(0);\n\n// App.svelte\nimport { count } from 'store.js';\n```\n\n```js\n// store.js\nimport { writable } from 'svelte/store';\n\nconst createWritableStore = (key, startValue) => {\n const { subscribe, set } = writable(startValue);\n \n return {\n subscribe,\n set,\n useLocalStorage: () => {\n const json = localStorage.getItem(key);\n if (json) {\n set(JSON.parse(json));\n }\n \n subscribe(current => {\n localStorage.setItem(key, JSON.stringify(current));\n });\n }\n };\n}\n\nexport const count = createWritableStore('count', 0);\n\n// App.svelte\nimport { count } from 'store.js';\n\ncount.useLocalStorage();\n```\n\n```text\ncount\n```\n\n```text\nuseLocalStorage\n```\n\n```text\nstore\n```\n\n```text\nApp.svelte\n```\n\n```text\nuseLocalStorage\n```\n\n```text\ncount.useLocalStorage()\n```\n\n```text\nonMount\n```\n\n```text\nif (process.browser)\n```\n\n```js\nexport const stored_object = writable(\n localStorage.stored_object? JSON.parse(localStorage.stored_object) : {});\nstored_object.subscribe(val => localStorage.setItem(\"stored_object\",JSON.stringify(val)));\n```\n\n```html\n<input type=\"text\" bind:value={$stored_object.name}>\n<input type=\"text\" bind:value={$stored_object.price}>\n```\n\n```text\nfunction persistent(name) {\n const value = writable(localStorage.getItem(name));\n value.subscribe(val => [null, undefined].includes(val) ? localStorage.removeItem(name) : localStorage.setItem(name, val));\n return value;\n}\n\n\nexport const my_token = persistent('token');\n```\n\n```text\nlocalStorage.setItem('someval', null)\n```\n\n```text\nlocalStorage.getItem('someval')\n```\n\n```text\n\"null\"\n```\n\n```js\nimport { writable, Writable } from 'svelte/store';\n\nconst wStorage = <T>(key: string, initValue: T): Writable<T> => {\n const storedValueStr = localStorage.getItem(key);\n const storedValue: T = JSON.parse(storedValueStr);\n\n const store = writable(storedValueStr != null ? storedValue : initValue);\n store.subscribe((val) => {\n localStorage.setItem(key, JSON.stringify(val));\n })\n return store;\n}\n\nexport default wStorage;\n```\n\n```js\nconst count = wStorage<number>('count', 0);\n```\n\n```js\nconst wStorage = <T>(key: string, initValue: T): Writable<T> => {\n const store = writable(initValue);\n if (typeof Storage === 'undefined') return store;\n\n const storedValueStr = localStorage.getItem(key);\n if (storedValueStr != null) store.set(JSON.parse(storedValueStr));\n\n store.subscribe((val) => {\n localStorage.setItem(key, JSON.stringify(val));\n })\n return store;\n}\n```\n\n```text\nwritable\n```\n\n```text\nonMount\n```\n\n```text\nif (process.browser)\n```\n\n```js\n<script>\n import { onMount } from 'svelte';\n import { writable } from \"svelte/store\";\n\n let value;\n\n onMount(() => {\n value = writable(localStorage.getItem(\"storedValue\") || \"defaut value\");\n value.subscribe(val => localStorage.setItem(\"storedValue\", val));\n })\n</script>\n\n<input bind:value={$value} />\n```\n\n```text\nlocalStorage\n```\n\n```text\nonMount()\n```\n\n```js\nimport { browser } from '$app/env';\nimport type { Writable } from 'svelte/store';\nimport { writable, get } from 'svelte/store'\n\nconst storage = <T>(key: string, initValue: T): Writable<T> => {\n const store = writable(initValue);\n if (!browser) return store;\n\n const storedValueStr = localStorage.getItem(key);\n if (storedValueStr != null) store.set(JSON.parse(storedValueStr));\n\n store.subscribe((val) => {\n if ([null, undefined].includes(val)) {\n localStorage.removeItem(key)\n } else {\n localStorage.setItem(key, JSON.stringify(val))\n }\n })\n\n window.addEventListener('storage', () => {\n const storedValueStr = localStorage.getItem(key);\n if (storedValueStr == null) return;\n\n const localValue: T = JSON.parse(storedValueStr)\n if (localValue !== get(store)) store.set(localValue);\n });\n\n return store;\n}\n\nexport default storage\n```\n\n```js\nimport storage from '$lib/store'\n\ninterface Auth {\n jwt: string\n}\n\nexport const auth = storage<Auth>(\"auth\", { jwt: \"\" })\n```\n\n```text\nlocalStorage\n```\n\n```text\n$lib/store.ts\n```\n\n```text\nimport { writable } from \"svelte/store\";\nimport { browser } from \"$app/env\"\n\nexport const fontSize = writable(browser && localStorage.getItem(\"fontSize\") || \"15\");\nfontSize.subscribe((value) => {\n if (browser) return localStorage.setItem(\"fontSize\", value)\n});\n```\n\n```text\n3.44.1\n```\n\n```text\nimport type { Writable, StartStopNotifier, Unsubscriber } from 'svelte/types/runtime/store';\nimport { writable } from 'svelte/store';\n\nconst attach = (writable: Writable<unknown>, key='store'): void =>{\n const json = localStorage.getItem(key);\n if (json) {\n writable.set(JSON.parse(json));\n }\n\n writable.subscribe(current => {\n localStorage.setItem(key, JSON.stringify(current));\n });\n}\ninterface Savable<T> extends Writable<T> {\n mount(localstore: Storage): void\n dismount(localstore: Storage): JSON\n unsub: Unsubscriber\n}\nfunction savable<T>(key: string, value?: T, start?: StartStopNotifier<T>): Savable<T>{\n const base = writable(value, start)\n return {\n ...base,\n mount(localstore) {\n if(this.mounted) throw new Error(\"Already mounted\");\n this.mounted = true;\n\n const json = localstore.getItem(key);\n if (json) {\n base.set(JSON.parse(json));\n }\n\n this.unsub = base.subscribe(current => {\n localStorage.setItem(key, JSON.stringify(current));\n });\n console.log(this)\n },\n dismount(localstore) {\n if(!this.mounted) throw new Error(\"Not mounted\");\n const json = JSON.parse(localstore.getItem(key))\n this.unsub()\n localstore.removeItem(key)\n return json\n },\n unsub() {\n throw new Error('Cannot unsubscribe when not subscribed')\n }\n }\n}\nexport {\n attach,\n savable,\n};\nexport type {\n Savable\n}\nexport default savable\n```\n\n```html\n<!—- Typescript is not required —->\n<script lang=ts>\n import savable from `$lib/savable`;\n const value = savable(‘input_value’);\n import { onMount } from ‘svelte’;\n onMount(()=>{\n value.mount()\n })\n</script>\n\n<input bind:value={$value}></input>\n```\n\n```text\n$lib/savable.ts\n```\n\n```text\nindex.svelte\n```\n\n```bash\nnpm install svelte-persisted-store\n```\n\n```js\n// in store.ts or similar\nimport { persisted } from 'svelte-persisted-store'\n\n// First param `preferences` is the local storage key.\n// Second param is the initial value.\nexport const preferences = persisted('preferences', {\n theme: 'dark',\n pane: '50%',\n ...\n})\n\n\n// in views\n\nimport { get } from 'svelte/store'\nimport { preferences } from './stores'\n\npreferences.subscribe(...) // subscribe to changes\npreferences.update(...) // update value\npreferences.set(...) // set value\nget(preferences) // read value\n$preferences // read value with automatic subscription\n```\n\n```js\nimport { writable } from 'svelte/store';\nimport { browser } from '$app/environment';\n\n// check if the item exists in local storage, if so, return the item, otherwise, return null. (This is to avoid errors on initial reads of the store)\n// browser && makes sure the command only works in the client side (browser).\nconst get_local_storage =\n browser && localStorage.getItem('presisted_local_store')\n ? browser && localStorage.getItem('presisted_local_store')\n : null;\n// create a writable store\nexport const presisted_local_store = writable(JSON.parse(get_local_storage));\n// create a subscribe method for the store to write back to the local storage (again, on the browser)\npresisted_local_store.subscribe((value) => {\n browser && localStorage.setItem('presisted_local_store', JSON.stringify(value));\n```\n\n========================================\n\nComments:\n- Using Snapshots you may not need a store at all depending on your use case.\n- This works properly in svelte. What is the recommended way of using this in Sapper. I created a separate JS file as below import { writable, derived } from 'svelte/store'; export const name = writable(localStorage.getItem(\"store\") ||'world'); name.subscribe(val => localStorage.setItem(\"store\", val)); But this not running in sapper as localStorage is not available in server\n- @AnilSivadas Doing it on the server complicates it a bit. You could skip it on the server and just do it in the browser with a `typeof window !== 'undefined'` check before using localStorage.\n- There is a similar / same example described here, including the solution (similar as @Tholle described) by using `{#if process.browser}`.\n- Another interesting option is to use `derived()`, but that will make you have double the amount of stores which is usually unnecessary.\n- In general, you should not manually subscribe to stores unless you also make sure to unsubscribe. In components it is not necessary either, just use: `$: localStorage.setItem(\"store\", $store);`\n- For others coming across this post and looking for the source: the blog seems to not exist anymore, just the source at github: https://github.com/higsch/higsch.me/blob/master/content/post‌​/2019-06-21-svelte-l‌​ocal-storage.md. However @mic posted the whole code here already. Also be aware that if you use sapper, you need to take care if it is run on the server or browser.\n- To make it work in Sapper specifically just place `count.useLocalStorage()` in `onMount` or `if (process.browser)` in the component consuming the store.\n- I really like the concept of deleting the value in localStorage when set to null. I see how to use the exported `my_token.set(\"hello\")` but it not clear on how to use that function to `get` the value from the my_token.js store function. I can see the value \"hello\" in the browser dev tools --> Applications --> Local Storage screen, but your words are **Here is a function that takes care of not only setting and getting, but also deletion.** I'm just not understanding how the `get()` works here.. Note: `my_token.set(null);` works great to delete the value in LocalStorage. Where is `.get()`\n- oops. `import { get } from \"svelte/store\";` Would you be offended if I proposed an edit to your code that showed it in use ?\n- Wouldn't this cause a memory leak? The subscription is never unsubscribed\n- @Jahir The data saved in localStorage won't be removed but also no more data will be saved. Only the fixed number of values you specify in your app will by saved, no more data will be accumulated over time. The value paired with a key will be overwritten, not added.\n- I understand that. But my question was that the explicit subscription is never unsubscribed. So, isn't there a risk of the subscriptions never getting released and causing memory leaks?\n- @Jahir That depends on where you call the `wStorage` function. How many times you call it, that many times is the subscription initialized. I use the `wStorage` in `src/store.ts` file, just how it is in the docs. I believe the code runs there only once, am I missing something? If you call the `wStorage` function in component, feel free to modify it (e.g. returning `[store, unsubscribe]` and then using `onDestroy(unsubscribe);` in the component).\n- @Jahir when you create a store using Writable, svelte will take care of the subscriptions/unsubscriptions for you - you just need to prefix your store with $ when referencing it in svelte files.\n- I've just created a svelte/vite project with **svelte 3.38** : it seems that `localStorage` is **available** outside `onMount()`\n- Work's like magic =)\n- Thanks for the full code. Just wondering why is the statement `if (storedValueStr == null) return;` needed? Because by the time the `storage` event listener runs, this key should already be existing in localStorage.\n- @Ammar I did run into this case. So there seems to be a scenario where it is not existing.\n- Isn't `[null, undefined].includes(val)` strictly equivalent to `val == null`? (I see later a loose comparison with `null` so just wondering if it could be rewritten for consistency without change in behavior.)\n- What about the compare at the end `f (localValue !== get(store))`? Wouldn't that fail if the value was an (nested) object?\n- thanks for the code @Spenhouet, may be it need to be updated because I get error `Argument of type 'T' is not assignable to parameter of type 'null | undefined'.` in this line `if ([null, undefined].includes(val))`\n- @Ammar , @Spenhouet it might be getting triggered when the key is removed. Look into Mozilla docs for `key` event property","metadata":{"transformedAt":"2026-08-18T18:33:40.653Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":40,"totalLines":483,"estimatedTokens":3685}}4{"id":"stack-59126405","source":"stackoverflow","questionId":59126405,"title":"Is it possible to access Svelte store from external js files?","tags":["javascript","svelte","svelte-store"],"text":"Title: Is it possible to access Svelte store from external js files?\nTags: javascript, svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI am wondering if i would be able to access my *Svelte* store values from a plain .js file.\n\nI am trying to write functions returning a dynamic value based on a store value, to import them in any component.\nBut in a plain .js file I can't just access the store value with the $ sign..\n\nQuick exemple of a basic function that uses a store value and could be used on multiple components:\n\n```\n//in .svelte\n\nfunction add() {\n $counter = $counter + 1;\n}\n```\n\n*EDIT: rephrasing a bit*\n\n*EDIT:*\nFound a solution but i don't really know if it's really optimized..\n\n```\n//in .js file\n\nimport { get } from \"svelte/store\";\nimport { counter } from \"./stores\";\n\nexport function add() {\n var counterRef = get(counter);\n counter.set(counterRef + 1);\n}\n```\n\n========================================\n\nTop Answer:\nYes, absolutely.\n\nFor one thing, the store API is very simple and nothing prevents you from subscribing to the store yourself to know the value:\n\n```\nimport myStore from './stores'\n\nmyStore.subscribe(value => {\n // do something with the new value\n // you could store it for future reference...\n})\n```\n\nAnd, if you just want to know the current value, Svelte has a helper for that, the `get` function:\n\n```\nimport { get } from 'svelte/store';\n\nimport myStore from './stores'\n\nconst value = get(myStore);\n```\n\n========================================\n\nCode:\n```js\n//in .svelte\n\nfunction add() {\n $counter = $counter + 1;\n}\n```\n\n```js\n//in .js file\n\nimport { get } from \"svelte/store\";\nimport { counter } from \"./stores\";\n\nexport function add() {\n var counterRef = get(counter);\n counter.set(counterRef + 1);\n}\n```\n\n```js\nimport { counter } from \"./stores\";\n\nexport function add() {\n counter.update(n => n + 1);\n}\n```\n\n```text\nadd\n```\n\n```text\nupdate\n```\n\n```js\nimport myStore from './stores'\n\nmyStore.subscribe(value => {\n // do something with the new value\n // you could store it for future reference...\n})\n```\n\n```js\nimport { get } from 'svelte/store';\n\nimport myStore from './stores'\n\nconst value = get(myStore);\n```\n\n```text\nget\n```\n\n```js\nimport { get } from 'svelte/store'\n\nexport function add(yourStore) {\n let _yourStore = get(yourStore)\n yourStore.set(_yourStore + 1)\n}\n```\n\n```text\nexport async function leave_locale() {\n return fetch(`./builds/leave`, {method: 'get'})\n .then(res => res.json())\n .then(res => {\n pstats.update((theStore) => {\n return Object.assign(theStore, {locale: 0});\n })\n })\n}\n```\n\n```text\n0\n```\n\n```text\npstats = {uid: 1, locale: 5}\n```\n\n```text\nimport { pstats} from './stores.js'\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.653Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":155,"estimatedTokens":689}}5{"id":"stack-73813721","source":"stackoverflow","questionId":73813721,"title":"SyntaxError: ambiguous indirect export: default Error when importing my own class","tags":["javascript","vue.js","svelte"],"text":"Title: SyntaxError: ambiguous indirect export: default Error when importing my own class\nTags: javascript, vue.js, svelte\nSource: Stack Overflow\n\nQuestion:\nI have written a validation class and want to include it in my VueJS 3 project. Unfortunately I get the following error: `SyntaxError: ambiguous indirect export: default`\n\n**This is my code:**\n\n```\n// ..classes/formValidationClass.js\nexport class FormValidator {\n...\n}\n\n// some vue file with a form\nimport FormValidation from \"..classes/formValidationClass\"\n\nexport default {...}\n```\n\nWhat does this error mean and what do I have to do to correct the error?\n\n========================================\n\nTop Answer:\n### Incompatibility of ES and CommonJS Modules Causes This Error\n\nThe most probable cause of this exception is inconsistency of syntaxes of **ES** and **CommonJS** modules. Using different syntax conventions in the same module can lead to conflicts resulting in **syntax errors** and runtime errors. I, for example, encountered this error (Chrome browser):\n\nUncaught SyntaxError: The requested module '/node_modules/axios/index.js?v=fae0673e' does not provide an export named 'default' (at index.ts:1:8)\n\nIn Firefox, the error text is as follows:\n\nUncaught SyntaxError: ambiguous indirect export: default\n\nIn 2023, you're most likely using ES syntax, but the libraries you're plugging in are most likely distributed in CommonJS syntax.\n\nTo determine the syntax:\n\n- look in `package.json` and check the `module` and `main` fields: if there is a file there with the extension `.mjs` or `.js`, this indicates the **ES** module format;\n\n- if the `main` field points to a file with `.cjs` extension (or the file uses *require* syntax), it points to the **CommonJS** format.\n\nIn my case, the error pointed to the following line:\n\n```\nimport axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from \"axios\";\n```\n\nI knew I was using ES6, but was unsure about axios 0.27.2. Opening its `package.json`,\nI found the `\"main\": \"index.js\"` property, but inside the file itself I saw CommonJS syntax:\n\n```\nmodule.exports = require('./lib/axios');\n```\n\nThe *require* meant that I was trying to import a CommonJS module from my ES module, which caused the error.\n\n### Solution\n\nThe solution was pretty simple: upgrade axios to version **1.4.0**, where the library uses ES syntax by default and CommonJS provides on-demand:\n\n```\nnpm i axios@latest\n```\n\n### Another possible solution\n\n```\nimport * as axios from \"axios\";\nconst defaultExport = axios.default;\n```\n\nFirst we import all exported values from \"axios\" module and pack them into one object named \"axios\", and then we access the default exported variable.\n\nYou can also consult MDN for detailed help on imports.\n\n========================================\n\nCode:\n```js\n// ..classes/formValidationClass.js\nexport class FormValidator {\n...\n}\n\n// some vue file with a form\nimport FormValidation from \"..classes/formValidationClass\"\n\nexport default {...}\n```\n\n```text\nSyntaxError: ambiguous indirect export: default\n```\n\n```js\n// ..classes/formValidatorClass.js // Comment: => suggestion change your file name to similar your class name\nexport class FormValidator {\n...\n}\n\n// some vue file with a form\n// import FormValidation from \"..classes/formValidationClass\"\nimport { FormValidator as FormValidation} from \"../classes/formValidatorClass\"; // Comment: => use brackets around your import name. if you want use FormValidation you can use also a alias (`originalName as newName`)\n\nexport default {...}\n```\n\n```text\n{}\n```\n\n```text\ndefault\n```\n\n```text\nexport default function myFunction()\n```\n\n```text\ndefault\n```\n\n```text\nimport users from './users.json';\nconsole.log(\"users\", users);\n```\n\n```text\nimport { users } from ...\n```\n\n```js\nimport { TUser } from '../models/Users/Users';\n```\n\n```js\nexport type TUser = { ... }\n```\n\n```text\nError: This import is never used as a value and must use 'import type' because 'importsNotUsedAsValues' is set to 'error'. (ts)\n```\n\n```text\nError: 'TUser' is a type and must be imported using a type-only import when 'preserveValueImports' and 'isolatedModules' are both enabled. (ts)\n```\n\n```js\nimport type { TUser } from '../models/Users/Users';\n```\n\n```text\ntsconfig\n```\n\n```text\npackage.json\n```\n\n```text\nsync\n```\n\n```text\nimportsNotUsedAsValues\n```\n\n```text\npreserveValueImports\n```\n\n```text\ntype\n```\n\n```text\nimport\n```\n\n```text\nTUser\n```\n\n```text\nmodule.exports = FormValidator;\n```\n\n```text\nexport default FormValidator;\n```\n\n```js\nexport default App\n```\n\n```js\nexport {App}\n```\n\n```text\nimport {Test} from './Test' ... Test()\n```\n\n```text\nnpx vite dev --open\n```\n\n```text\nexport const Test = () => { let test = new Test()... }\n```\n\n```text\nimport axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from \"axios\";\n```\n\n```js\nmodule.exports = require('./lib/axios');\n```\n\n```bash\nnpm i axios@latest\n```\n\n```js\nimport * as axios from \"axios\";\nconst defaultExport = axios.default;\n```\n\n```text\npackage.json\n```\n\n```text\nmodule\n```\n\n```text\nmain\n```\n\n```text\n.mjs\n```\n\n```text\n.js\n```\n\n```text\nmain\n```\n\n```text\n.cjs\n```\n\n```text\npackage.json\n```\n\n```text\n\"main\": \"index.js\"\n```\n\n```text\nimport { something } from 'file2'\n```\n\n```text\n// this function used to be named \"something\", but then I renamed it\nexport function somethingRenamed() { }\n```\n\n```text\nSyntaxError: ambiguous indirect export: something\n```\n\n```text\nUncaught SyntaxError: ambiguous indirect export\n```\n\n```text\n...\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"files\": [\n \"dist/**\"\n ],\n \"scripts\": {\n \"build\": \"tsup src/index.tsx --format esm,cjs --dts --external next @emotion/react @emotion/styled @mui/material react react-dom\",\n \"dev\": \"tsup src/index.tsx --format esm,cjs --watch --dts --external next @emotion/react @emotion/styled @mui/material react react-dom --sourcemap\",\n ...\n },\n ...\n```\n\n```text\nexport class NAME\n```\n\n```text\nexport const NAME\n```\n\n```text\nNAME\n```\n\n```text\nimport\n```\n\n```text\nNAME\n```\n\n```text\nexport default class NAME\n```\n\n```text\ndefault\n```\n\n```text\nNAME\n```\n\n```text\nimport\n```\n\n```text\nimport { VARIABLE } from MOD\n```\n\n```text\nMOD.VARIABLE\n```\n\n```text\nMOD\n```\n\n```text\nexport VARIABLE\n```\n\n```text\nimport VARIABLE from MOD\n```\n\n```text\ndefault\n```\n\n```text\nMOD\n```\n\n```text\nimport { default as VARIABLE } from MOD\n```\n\n```text\nMOD\n```\n\n```text\nexport default\n```\n\n```text\nNAME\n```\n\n```text\nNAME\n```\n\n```text\ndefault\n```\n\n```text\nTest*.js\n```\n\n```text\nImport.js\n```\n\n```text\nexport class TestClass {}; export default TestClass\n```\n\n```text\nTestClass\n```\n\n```text\ndefault\n```\n\n```text\nTest1a.js\n```\n\n```text\nimport { TestClass } from './Import.js';\n```\n\n```text\nTest1b.js\n```\n\n```text\nimport { TestClass as Test } from './Import.js';\n```\n\n```text\nTest\n```\n\n```text\nTestClass\n```\n\n```text\nTest2a.js\n```\n\n```text\nimport TestClass from './Import.js';\n```\n\n```text\nTest2b.js\n```\n\n```text\nimport Test from './Import.js';\n```\n\n```text\nTest1b.js\n```\n\n```text\nTest2b.js\n```\n\n```text\nCorrect 1\n```\n\n```text\nTest1b.js\n```\n\n```text\nImport.js\n```\n\n```text\ndefault\n```\n\n```text\nImport.js\n```\n\n```text\nexport class TestClass {}\n```\n\n```text\nTest.js\n```\n\n```text\nimport { TestClass } from './Import.js';\n```\n\n```text\nTestClass\n```\n\n```text\nImport.js\n```\n\n```text\nImport.js\n```\n\n```text\nexport class TestClass {}\n```\n\n```text\nTest.js\n```\n\n```text\nimport TestClass from './Import.js';\n```\n\n```text\ndefault\n```\n\n```text\nImport.js\n```\n\n```text\nerror: ambiguous indirect export: default\n```\n\n```text\nImport.js\n```\n\n```text\nexport default class {}\n```\n\n```text\nNAME\n```\n\n```text\nexport default class NAME {}\n```\n\n```text\nTest.js\n```\n\n```text\nimport TestClass from './Import.js';\n```\n\n```text\nImport.js\n```\n\n```text\nTestClass\n```\n\n```text\nImport.js\n```\n\n```text\nexport default class TestClass {}\n```\n\n```text\nTestClass\n```\n\n```text\nImport.js\n```\n\n```text\nImport.js\n```\n\n```text\nexport\n```\n\n```text\nTest.js\n```\n\n```text\nimport { TestClass } from './Import.js';\n```\n\n```text\nImport.js\n```\n\n```text\nTestClass\n```\n\n```text\ndefault\n```\n\n```text\nerror: ambiguous indirect export: TestClass\n```\n\n========================================\n\nComments:\n- It worked, but why?\n- @parsecer Perhaps my answer below explains why this works\n- I had the case where, importing Ref from vue, I had the \"ambiguous indirect export\" but not a better understandable error. Replacing import { Ref } from \"vue\" by import { type Ref } from \"vue\" did the trick, as I just needed the interface declaration.\n- Thanks for the explanation... It wasn't obvious that `import * as d3 from 'd3';` is not the same as `import d3 from 'd3';` — the latter gave me `ambiguous indirect export: default`, the former worked.","metadata":{"transformedAt":"2026-08-18T18:33:40.653Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":123,"totalLines":612,"estimatedTokens":2173}}6{"id":"stack-57392773","source":"stackoverflow","questionId":57392773,"title":"error: 'type' attribute cannot be dynamic if input uses two-way binding","tags":["svelte"],"text":"Title: error: 'type' attribute cannot be dynamic if input uses two-way binding\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI was trying to create an `Input` component for my project. I want to set type attribute dyamically on `input` element\n\nBut when i set type attribute dynamically on `input` i get error saying\n`'type' attribute cannot be dynamic if input uses two-way binding` \n\nSo is there any workaround for this such that i can set type attribute dynamically without loosing two way binding \n\n`Input.svelte`\n\n```\n\n export let placeholder = \"\";\n export let label = \"\";\n export let description = \"\";\n export let value = \"\";\n export let type = \"text\";\n\n {label}\n \n {description}\n\n```\n\n========================================\n\nTop Answer:\nIf you want to still use bind:value and SSR, you can do something like this:\n\n```\n\n export let type = \"text\";\n export let value = \"\";\n\n```\n\n========================================\n\nCode:\n```html\n<script>\n export let placeholder = \"\";\n export let label = \"\";\n export let description = \"\";\n export let value = \"\";\n export let type = \"text\";\n</script>\n\n<div class=\"container\">\n <label>{label}</label>\n <input {type} bind:value {placeholder} />\n <p>{description}</p>\n</div>\n```\n\n```text\nInput\n```\n\n```text\ninput\n```\n\n```text\ninput\n```\n\n```text\n'type' attribute cannot be dynamic if input uses two-way binding\n```\n\n```text\nInput.svelte\n```\n\n```html\n<script>\n export let placeholder = \"\";\n export let label = \"\";\n export let description = \"\";\n export let value = \"\";\n export let type = \"text\";\n\n const handleInput = e => {\n // in here, you can switch on type and implement\n // whatever behaviour you need\n value = type.match(/^(number|range)$/)\n ? +e.target.value\n : e.target.value;\n };\n</script>\n\n<div class=\"container\">\n <label>{label}</label>\n <input {type} {value} {placeholder} on:input={handleInput} />\n <p>{description}</p>\n</div>\n```\n\n```text\ntype\n```\n\n```text\nnumber\n```\n\n```text\nrange\n```\n\n```text\nchange\n```\n\n```text\ninput\n```\n\n```text\n<script>\n export let id = \"\";\n export let placeholder = \"\";\n export let label = \"\";\n export let description = \"\";\n export let value = \"\";\n export let type = \"text\";\n</script>\n\n<div class=\"container\">\n <label>{label}</label>\n <input {type} bind:value {placeholder}\n on:focus=\"{() => {\n console.log(type)\n let inpt = document.getElementById(id)\n inpt.setAttribute(\"type\", type)\n console.log(inpt)\n }}\"/>\n <p>{description}</p>\n</div>\n```\n\n```text\nelement.setAttribute(attributename, attributevalue)\n```\n\n```text\n<!-- InputField.svelte -->\n<script>\n export let placeholder = \"\";\n export let label = \"\";\n export let description = \"\";\n export let value = \"\";\n export let type = \"text\";\n\n const handleInputType = (e) => {\n e.target.type = type;\n };\n</script>\n\n<div class=\"container\">\n <label>{label}</label>\n <input {value} {placeholder} on:input={handleInputType} />\n <p>{description}</p>\n</div>\n```\n\n```text\n<InputField type=\"email\" bind:value={emailValue} />\n```\n\n```text\n{type}\n```\n\n```js\nexport let type: 'email' | 'text' | 'password' | 'number' = 'text'\n\nlet ref: HTMLInputElement\n\nonMount(() => {\n if (ref) {\n ref.type = type\n }\n})\n```\n\n```html\n<input bind:this={ref} />\n```\n\n```js\nexport let type: 'email' | 'text' | 'password' | 'number' = 'text'\n\nconst ref = (node: HTMLInputElement) => {\n node.type = type\n}\n```\n\n```html\n<input use:ref />\n```\n\n```text\n<script>\n export let name;\n export let value;\n export let type = 'text';\n</script>\n\n\n{#if type === 'password'}\n <input\n type=\"password\"\n id={name}\n {name}\n on:change\n on:blur\n bind:value\n />\n{:else if type === 'email'}\n <input\n type=\"email\"\n id={name}\n {name}\n on:change\n on:blur\n bind:value\n />\n{:else if type === 'number'}\n <input\n type=\"number\"\n id={name}\n {name}\n on:change\n on:blur\n bind:value\n />\n{:else if type === 'date'}\n <input\n type=\"date\"\n id={name}\n {name}\n on:change\n on:blur\n bind:value\n />\n{:else}\n <input\n type=\"text\"\n id={name}\n {name}\n on:change\n on:blur\n bind:value\n />\n{/if}\n```\n\n```text\ntype\n```\n\n```text\n<script>\n export let type = 'text'\n export let label\n export let value\n\n function typeAction(node) {\n node.type = type;\n }\n</script>\n\n<div class=\"space-y-1\">\n <label>{label}</label>\n\n <input use:typeAction bind:value class=\"rounded-md w-full\">\n\n <p class=\"text-sm text-red-600\">errors</p>\n</div>\n```\n\n```text\n<form on:submit|preventDefault={login}>\n <Input type=\"email\" label=\"Email\" bind:value={values.email}/>\n <Input type=\"password\" label=\"Password\" bind:value={values.password}/>\n\n <Button type=\"submit\" label=\"Login\"/>\n </form>\n```\n\n```text\nuse\n```\n\n```html\n<script>\n export let type = \"text\";\n export let value = \"\";\n</script>\n\n<input bind:value {...{ type }} />\n```\n\n```html\n<script>\n export let placeholder = \"\";\n export let label = \"\";\n export let description = \"\";\n export let value = \"\";\n export let type = \"text\";\n const inputProperties = { placeholder, type };\n</script>\n\n<div class=\"container\">\n <label>{label}</label>\n <input {...inputProperties} bind:value />\n <p>{description}</p>\n</div>\n```\n\n========================================\n\nComments:\n- Hi Rich, value coercion not working - I still get string type instead of number for [type=number] inputs. I used `console.log{ value: new FormData(form).get('inputname') }` inside `` event. Thanks for this wonderful Svelte framework btw!\n- UPDATE: Rich, actually your solution seems to work. Looks like it's the form's behavior that converts all form data to string types on submit.\n- multiple select is not working by this way - `on:input` always has single value only\n- Which type are you using to type the `event` argument of `handleInput(e: ???)`?\n- `handleInput(e: Event)` but if it's an input field you need to cast it over to an `InputEvent` to see the data there.\n- With this approach the value will always be of type string, when we specify `type=number` or `type=range` in svelte we expects the binded value shoud be of type number. In this approach we would also need to handle type changing from string to number\n- I recommend against rhetoric questions in answers. They risk being misunderstood as not an answer at all. You are trying to answer the question at the top of this page, aren't you? Otherwise please delete this post.\n- Very elegant, are there any downsides or considerations to this approach?\n- We stopped doing it this way, beacuse a JS error could prevent `typeAction` from running which could lead to passwords being rendered in plain text. If you're always expecting strings then I think stackoverflow.com/a/75298645/2301416 is much bette, it supports SSR, won't expose passwords and is far more elegant.\n- The most elegant answer of all!\n- I do not understand this one...what is happening here?\n- @rchrdnsh `{ type }` creates an object like `{ type: \"text\" }`. `...` destructures the attributes, that is, applies every property found in the object.\n- However you'll lose auto coercion handled by Svelte if you that. So do not forget to take care of it\n- This solution is great if you have a state between \"text\" and \"password\" which both use the same type under the hood, so you can safely bypass the Svelte coercion event handler here.","metadata":{"transformedAt":"2026-08-18T18:33:40.653Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":343,"estimatedTokens":1850}}7{"id":"stack-56318460","source":"stackoverflow","questionId":56318460,"title":"Cannot access 'variable_name' before initialization","tags":["svelte"],"text":"Title: Cannot access 'variable_name' before initialization\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nWhen using reactive variables by declaring them using the `$:` syntax, you get the following error.\n\n`Cannot access 'variable_name' before initialization`\n\nHere is the code:\n\n**App.svelte**\n\n```\n\n import { ledzep, redhotchilis } from './data.js'\n \n $: bandmembers = [...ledzep, ...redhotchilis]\n \n let namesWithA = bandmembers.filter(d => {\n if (d.indexOf('a') > 0) { \n return true;\n }\n else {\n return false\n }\n })\n \n\n### Band Members\n\n{#each bandmembers as member}\n \n- {member}\n{/each}\n\n### Members with \"A\" in their names\n\n{#each namesWithA as member}\n \n- {member}\n{/each}\n\n```\n\n**data.js**\n\n```\nexport const ledzep = [\"Jimmy Page\", \"John Bonham\", \"Robert Plant\", \"John Paul Jones\"]\nexport const redhotchilis = [\"Anthony Kiedis\", \"Flea\", \"Chad Smith\", \"Josh Klinghoffer\"]\n```\n\n========================================\n\nCode:\n```html\n<script>\n import { ledzep, redhotchilis } from './data.js'\n \n $: bandmembers = [...ledzep, ...redhotchilis]\n \n let namesWithA = bandmembers.filter(d => {\n if (d.indexOf('a') > 0) { \n return true;\n }\n else {\n return false\n }\n })\n \n</script>\n<h2>Band Members</h2>\n<ul>\n{#each bandmembers as member}\n <li>{member}</li>\n{/each}\n</ul>\n\n<h2>Members with \"A\" in their names</h2>\n<ul>\n{#each namesWithA as member}\n <li>{member}</li>\n{/each}\n</ul>\n```\n\n```js\nexport const ledzep = [\"Jimmy Page\", \"John Bonham\", \"Robert Plant\", \"John Paul Jones\"]\nexport const redhotchilis = [\"Anthony Kiedis\", \"Flea\", \"Chad Smith\", \"Josh Klinghoffer\"]\n```\n\n```text\n$:\n```\n\n```text\nCannot access 'variable_name' before initialization\n```\n\n```js\nlet namesWithA = bandmembers.filter(d => {\n if (d.indexOf('a') > 0) { \n return true;\n }\n else {\n return false\n }\n})\n```\n\n```js\n$: namesWithA = bandmembers.filter(d => {\n if (d.indexOf('a') > 0) { \n return true;\n }\n else {\n return false\n }\n})\n```\n\n```text\n$:\n```\n\n```text\nlet\n```\n\n```text\nconst\n```\n\n```text\nvar\n```\n\n```text\n$:\n```\n\n```text\n$:\n```\n\n========================================\n\nComments:\n- Just noting that in this example, you don't need to use `$:` at all, since `ledzep` and `redhotchilis` aren't reactive variables (values imported from another module are taken to be constant)\n- It's interesting that if the variable is coming as a parameter, used in the function body and then declared with let, it will raise the error too.","metadata":{"transformedAt":"2026-08-18T18:33:40.653Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":150,"estimatedTokens":646}}8{"id":"stack-57578775","source":"stackoverflow","questionId":57578775,"title":"How to change the default port 5000 in Svelte?","tags":["port","svelte","svelte-3"],"text":"Title: How to change the default port 5000 in Svelte?\nTags: port, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI am not getting how to change the default `5000` port in Svelte to some other port if we install the sample template through degit.\n\n========================================\n\nTop Answer:\nYou can use env vars `HOST` and `PORT`.\n\nFrom https://www.npmjs.com/package/sirv-cli:\n\nNote: The HOST and PORT environment variables will override flag values.\n\nLike this:\n\n```\nHOST=0.0.0.0 PORT=6000 npm run dev\n```\n\n========================================\n\nCode:\n```text\n5000\n```\n\n```json\n\"start:dev\": \"sirv public --single --dev\"\n```\n\n```json\n\"start:dev\": \"sirv public --single --dev --port 5555\"\n```\n\n```text\nsveltejs/template\n```\n\n```text\nsirv-cli\n```\n\n```text\n--port\n```\n\n```text\n-p\n```\n\n```text\nstart:dev\n```\n\n```text\npackage.json\n```\n\n```text\nsirv-cli\n```\n\n```text\nHOST=0.0.0.0 PORT=6000 npm run dev\n```\n\n```text\nHOST\n```\n\n```text\nPORT\n```\n\n```json\n\"start\": \"sirv public --no-clear\"\n```\n\n```json\n\"start\": \"sirv public --no-clear --port 8089\"\n```\n\n```text\npackage.json\n```\n\n```json\n\"dev\": \"vite --port 3333\",\n```\n\n```bash\nnpm run dev -- --port=3333\n```\n\n```text\nsvelte\n```\n\n```text\nsveltekit\n```\n\n```text\npackage.json\n```\n\n```text\n\"scripts\":\n```\n\n```text\ndev\n```\n\n```text\nexport default defineConfig({\n plugins: [sveltekit()],\n \n // ... other stuff ...\n\n server: {\n port: 4000\n }\n});\n```\n\n```text\nprocess.env.YOUR_PORT_VARIABLE\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.653Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":132,"estimatedTokens":367}}9{"id":"stack-59669571","source":"stackoverflow","questionId":59669571,"title":"Svelte dynamic html elements do not have css applied","tags":["svelte"],"text":"Title: Svelte dynamic html elements do not have css applied\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI have a svelte component which uses a library to display JSON tree, but that library needs an html hook where to be loaded. Afterwards it generates it's own html structure with it's own classes and ids. So far so good, but if I add inside my component some styles for the selectors which are generated in future, the style is not applied. \n\nIs this the problem ? Is there some work around ?\n\nHere is my code example:\n\n```\n\n import { onMount } from \"svelte\";\n import { Content } from \"@smui/card\";\n import { copyToClipboard } from \"../../public/js/utils\";\n\n export let data;\n let contentBody;\n\n onMount(() => {\n\n const editor = new JSONEditor(\n contentBody,\n { mode: \"view\", navigationBar: false },\n data\n );\n\n const editorMenu = document.getElementsByClassName(\"jsoneditor-menu\")[0];\n const copy = document.createElement(\"img\");\n copy.src = \"../../public/img/copy.png\";\n copy.setAttribute(\"class\", \"custom-button\");\n editorMenu.append(copy);\n\n copy.onclick = () => copyToClipboard(editor.getText()));\n });\n\n .jsoneditor-menu {\n background-color: #525b69;\n border: 1px solid #e8e8e8;\n }\n\n .jsoneditor {\n border: 1px solid #e8e8e8;\n }\n\n .json {\n height: 555px;\n }\n\n .custom-button {\n width: 20px;\n height: 20px;\n margin: 2px;\n padding: 2px;\n border-radius: 2px;\n border: 1px solid transparent;\n color: #fff;\n opacity: 0.8;\n font-family: arial, sans-serif;\n font-size: 10pt;\n float: left;\n }\n\n \n\n```\n\nNote: The style is applied only for root element `json` class\n\n========================================\n\nCode:\n```text\n<script>\n import { onMount } from \"svelte\";\n import { Content } from \"@smui/card\";\n import { copyToClipboard } from \"../../public/js/utils\";\n\n export let data;\n let contentBody;\n\n onMount(() => {\n\n const editor = new JSONEditor(\n contentBody,\n { mode: \"view\", navigationBar: false },\n data\n );\n\n const editorMenu = document.getElementsByClassName(\"jsoneditor-menu\")[0];\n const copy = document.createElement(\"img\");\n copy.src = \"../../public/img/copy.png\";\n copy.setAttribute(\"class\", \"custom-button\");\n editorMenu.append(copy);\n\n copy.onclick = () => copyToClipboard(editor.getText()));\n });\n</script>\n\n<style>\n .jsoneditor-menu {\n background-color: #525b69;\n border: 1px solid #e8e8e8;\n }\n\n .jsoneditor {\n border: 1px solid #e8e8e8;\n }\n\n .json {\n height: 555px;\n }\n\n .custom-button {\n width: 20px;\n height: 20px;\n margin: 2px;\n padding: 2px;\n border-radius: 2px;\n border: 1px solid transparent;\n color: #fff;\n opacity: 0.8;\n font-family: arial, sans-serif;\n font-size: 10pt;\n float: left;\n }\n\n</style>\n\n<Content>\n <div class=\"json\" bind:this={contentBody} />\n</Content>\n```\n\n```text\njson\n```\n\n```html\n<style>\n /* this will not be removed, and not scoped to the component */\n :global(.foo) { ... }\n\n /* this will not be removed, but still scoped to divs inside _this_ component */\n div :global(.bar) { ... }\n</style>\n```\n\n```text\n:global\n```\n\n```text\n.foo\n```\n\n```text\n.svelte-a3bmb2.foo\n```\n\n```text\n.foo\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.653Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":164,"estimatedTokens":785}}10{"id":"stack-56636764","source":"stackoverflow","questionId":56636764,"title":"Svelte/Sapper.js - How to initialize store with localStorage data?","tags":["javascript","state","server-side-rendering","svelte","sapper"],"text":"Title: Svelte/Sapper.js - How to initialize store with localStorage data?\nTags: javascript, state, server-side-rendering, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI come from a React background, but I'm switching to Svelte and Sapper for my next application in order to fight the massive bundle size that comes with React these days. However, I'm having trouble initializing Svelte's store with data retrieved from localStorage.\n\nAs per the Sapper docs (https://sapper.svelte.dev/docs#Getting_started), I created my project by running `npx degit \"sveltejs/sapper-template#rollup\" my-app` from the command line. I then installed the dependencies and removed the demo code in the `src` folder.\n\nI then created two files: `src/routes/index.svelte` and `src/store/index.js`.\n\nCode for both:\n\n**src/store/index.js**\n\n```\nimport {writable} from \"svelte/store\";\n \n export let userLang;\n \n if(typeof window !== \"undefined\") {\n userLang = writable(localStorage.getItem(\"lang\") || \"en\");\n } else {\n userLang = writable(null);\n }\n```\n\n**src/routes/index.svelte**\n\n```\n\n import {userLang} from \"../store\";\n \n \n Your Preferred Language: {$userLang}\n\n```\n\nWhen I run the application and hit the `index` route, I see this:\n\nYour Preferred Language: null\n\nwhich then almost immediately updates and changes to\n\nYour Preferred Language: en\n\nwhen there is no `lang` item in localStorage, and changes to\n\nYour Preferred Language: fr\n\nAfter explicitly setting `localStorage.setItem(\"lang\", \"fr\")` from the developer console and refreshing.\n\nI know that the store is being initialized on the server first where `window` is `undefined` and then is being rehydrated on the client. So this behavior is expected.\n\nSo my question is: how can I skip the server initialization entirely? Is it possible to only set up the store on the client (where `localStorage` is defined) so that the user's chosen language is immediately available?\n\nI can't default to having everything in English or any other language after the user has chosen to change their preferred language. I also can't get the user language from the browser via `navigator.language` on initial page load either since `navigator` is `undefined` on the server as well.\n\nAnd having a flash of empty text appear before the store rehydrates would screw up the UX for my application, especially when the value of `userLang` is going to be used all over the place with translations.\n\nSo any strategies or hacks for this are definitely appreciated.\n\n**** **Deeper Issue** ****\n\nI would actually prefer to **not** have server-side rendering at all for this application, but I do need all the other excellent features that Sapper provides, like routing, prefetching, and static site building.\n\nSo I tried running `npx sapper export` as per the docs to generate a completely static site in an effort to remove the server from the equation, but the exact same issue still occurs, even though there is no server being used at all.\n\nDoes anyone have any advice on how to configure Sapper and turn off SSR but keep the other features?\n\nThank you!\n\n**** **Update** ****\n\nAs per Rich Harris's answer, wrapping the markup with `{#if process.browser}` does the trick just fine. So I've updated the `src/routes/index.svelte`file like so:\n\n```\n\n import {userLang} from \"../store\";\n \n\n {#if process.browser}\n Your Preferred Language: {$userLang}\n\n {/if}\n```\n\nAnd the `userLang` variable is immediately set with the value from `localStorage` or defaults to `en` as I intended for this simple demo. There is no more flash of `null`, so it's essentially behaving like it's client-side only at this point.\n\nI will work on fleshing out my project and see if there are any more issues I encounter. Til then, I think this solves my issue.\n\n========================================\n\nCode:\n```text\nimport {writable} from \"svelte/store\";\n \n export let userLang;\n \n if(typeof window !== \"undefined\") {\n userLang = writable(localStorage.getItem(\"lang\") || \"en\");\n } else {\n userLang = writable(null);\n }\n```\n\n```text\n<script>\n import {userLang} from \"../store\";\n </script>\n \n <p>Your Preferred Language: {$userLang}</p>\n```\n\n```text\n<script>\n import {userLang} from \"../store\";\n </script>\n\n {#if process.browser}\n <p>Your Preferred Language: {$userLang}</p>\n {/if}\n```\n\n```text\nnpx degit \"sveltejs/sapper-template#rollup\" my-app\n```\n\n```text\nsrc\n```\n\n```text\nsrc/routes/index.svelte\n```\n\n```text\nsrc/store/index.js\n```\n\n```text\nindex\n```\n\n```text\nlang\n```\n\n```text\nlocalStorage.setItem(\"lang\", \"fr\")\n```\n\n```text\nwindow\n```\n\n```text\nundefined\n```\n\n```text\nlocalStorage\n```\n\n```text\nnavigator.language\n```\n\n```text\nnavigator\n```\n\n```text\nundefined\n```\n\n```text\nuserLang\n```\n\n```text\nnpx sapper export\n```\n\n```text\n{#if process.browser}\n```\n\n```text\nsrc/routes/index.svelte\n```\n\n```text\nuserLang\n```\n\n```text\nlocalStorage\n```\n\n```text\nen\n```\n\n```text\nnull\n```\n\n```text\n{#if process.browser}\n```\n\n========================================\n\nComments:\n- Thanks for the reply! I will definitely be keeping an eye on those issues and will try wrapping the markup in the if block as you said. And also thanks for the all around awesomeness that is Svelte. I know that the project will only get better and better as time goes on\n- My token is stored in localStorage, how do I get around that with sapper?\n- It's worth noting that checking `process.browser` also appears to work in regular JS code, not just in templates. Thanks!\n- process.browser works in my build environment. but it doesn't work when i export.","metadata":{"transformedAt":"2026-08-18T18:33:40.653Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":25,"totalLines":219,"estimatedTokens":1396}}11{"id":"stack-74361924","source":"stackoverflow","questionId":74361924,"title":"difference between svelte store and svelte context","tags":["svelte","store"],"text":"Title: difference between svelte store and svelte context\nTags: svelte, store\nSource: Stack Overflow\n\nQuestion:\nWhat is exact different between Svelte Context and Svelte Store?\n\nWhen to use in different situation?\n\n```\nimport { getContext } from 'svelte';\nimport { writable } from 'svelte/store';\n```\n\n========================================\n\nTop Answer:\nthe way i see it, the context is like props with steroids, meaning an ancestor can data to any deep nested component. i think this feature was also part of the react.\n\nThe store, on the other hand is a context with god like omnipotence. it can be used to data at any level of the component tree.\n\n========================================\n\nCode:\n```js\nimport { getContext } from 'svelte';\nimport { writable } from 'svelte/store';\n```\n\n```text\n$\n```\n\n```text\n.svelte.js\n```\n\n```text\n.svelte.ts\n```\n\n========================================\n\nComments:\n- I wouldn't call stores obsolete in Svelte 5. If I want a complex function to fire only when a specific variable changes, it sometimes makes more sense to subscribe() to a store instead of writing an $effect rune and having to untrack the other reactive states used in the function. As an added bonus, a class using subscribe() can be passed in a Promise.\n- @mysteryegg Untracking generally should not be necessary since the effect only fires when things are both used & changed. If both of those are true, the change is relevant to the effect, so it usually *should* execute. Of course there can be exception. Regarding the passing of stores, you also can pass state around, you just have to make sure it's an object and not a primitive value.\n- Niche scenarios perhaps, but Svelte devs describe stores as useful when you want \"more manual control over updating values or listening to changes\", e.g. if some of the dependent state changes are noisy or go through intermediate states that can be suppressed. I ran into a scenario recently that called for reactive class instances. Inside the class, $effects runes threw errors as \"orphaned\", but store subscriptions were fine. Not sure if caching state to localStorage can be easily done without stores. Finally, type safety is a bit more verbose when using contexts compared to stores alone.\n- Store and context are meant for client side code. If you want to store data on server side, use node-cache, redis or some other server side store","metadata":{"transformedAt":"2026-08-18T18:33:40.653Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":48,"estimatedTokens":599}}12{"id":"stack-62125395","source":"stackoverflow","questionId":62125395,"title":"Is there a standard way to document Svelte components?","tags":["visual-studio-code","svelte"],"text":"Title: Is there a standard way to document Svelte components?\nTags: visual-studio-code, svelte\nSource: Stack Overflow\n\nQuestion:\nI come from the world of JavaDocs and love the DX of working on a thoroughly-annotated application after a certain level of complexity. \n\nBeing able to hover over and peek all the props (and implied types) of a component with some brief documentation would save me so much time instead of having to open up and read through the whole component. Better yet, running a command to generate a documentation site just like you can with JavaDocs would be dope! \n\nAre there any standards or tools built around creating *SvelteDocs*? I looked through the VS Code marketplace and didn't see any documentation tooling related to Svelte.\n\n========================================\n\nTop Answer:\nAfter more digging, I found just a couple projects for documenting Svelte.\n\n- SvelteDoc Parser -- takes a VueDoc approach, based on JSDoc standards, generates JSON documentation for Svelte components\n\n- Svelte-Docs -- documentation in Markdown mixed with Svelte's features, can embed components in the generated doc pages\n\nBoth look interesting while taking completely separate approaches to solving the issue of application documentation. Perhaps there's still room to build a CLI-based site generator for the SvelteDoc Parser which could be turned into a VS Code plugin!\n\n========================================\n\nCode:\n```text\n<!--\n @component\n\n some markdown here\n-->\n```\n\n```text\n@component\n```\n\n```text\n<!-- @component\n```\n\n```text\nctrl+space\n```\n\n```text\nlet:\n```\n\n```text\n@component\n```\n\n```text\n/** ... */\n```\n\n```text\nSvelte for VS Code\n```\n\n```text\nSvelte Intellisense\n```\n\n```text\nSvelte-Docs\n```\n\n```text\nSvelteDoc Parser\n```\n\n========================================\n\nComments:\n- That would be really great if they added something.\n- I tried this and the @component keyword adds syntax highlighting for the documentation, but it seems buggy. Also what I write doesn't appear when I hover over my component in use in another file.\n- The first link is broken.\n- Can you make an example of the <!-- @ component doc string you include? I added the exposed propertys via @ property name but I don't get a suggestion by VS Code when hitting ctrl+space. Thanks!\n- @deristnochda the entry appears to be @ props. Also, for everyone else. . . there's spaces between the @ and the word so that this site doesn't think you're trying to notify users.","metadata":{"transformedAt":"2026-08-18T18:33:40.653Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":81,"estimatedTokens":616}}13{"id":"stack-57304022","source":"stackoverflow","questionId":57304022,"title":"Svelte execute function when any of group of variables changes","tags":["svelte","svelte-3"],"text":"Title: Svelte execute function when any of group of variables changes\nTags: svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nIn Svelte RealWorld App there is something like this:\n\n```\n$: query && getData();\n```\n\nThis calls REST API when page size or other query parameters change.\n\nI have similar situation for listing entities and do:\n\n```\n$: activePage && sort && pageSize && getData();\n```\n\nThis all works well (although the && is a strange construct to say I want to execute `getData()` when `activePage`, `sort` or `pageSize` changes.\n\nWith this approach a problem arises when you want to also include variables which evaluates to falsy.\n\nExample, add `searchQuery` text:\n\n```\nlet searchQuery = \"\";\n$: searchQuery && activePage && sort && pageSize && getData();\n```\n\nNow reactivity does not work since `searchQuery` evaluates to `false`.\n\nWe can do this:\n\n```\n$: activePage && sort && pageSize && getData();\n$: searchQuery, getData();\n```\n\nBut with this `getData()` gets called 2 times.\n\nDoes anybody know of better approach for this?\n\n========================================\n\nTop Answer:\nIn order to make things clearer, you can pass the observed variables to a function as arguments:\n\n```\n$: onChange(searchQuery, activePage, sort, pageSize);\n\nfunction onChange(...args) {\n getData();\n}\n```\n\nThus, you don't have to worry if some variable is falsy.\n\n========================================\n\nCode:\n```js\n$: query && getData();\n```\n\n```js\n$: activePage && sort && pageSize && getData();\n```\n\n```js\nlet searchQuery = \"\";\n$: searchQuery && activePage && sort && pageSize && getData();\n```\n\n```js\n$: activePage && sort && pageSize && getData();\n$: searchQuery, getData();\n```\n\n```text\ngetData()\n```\n\n```text\nactivePage\n```\n\n```text\nsort\n```\n\n```text\npageSize\n```\n\n```text\nsearchQuery\n```\n\n```text\nsearchQuery\n```\n\n```text\nfalse\n```\n\n```text\ngetData()\n```\n\n```js\n$: searchQuery, activePage && sort && pageSize && getData();\n// or\n$: searchQuery, activePage, sort, pageSize, getData();\n```\n\n```text\n,\n```\n\n```text\n&&\n```\n\n```js\n$: onChange(searchQuery, activePage, sort, pageSize);\n\nfunction onChange(...args) {\n getData();\n}\n```\n\n========================================\n\nComments:\n- Learn about the comma operator there: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…\n- Ah, another example of wonderful JS weirdness...","metadata":{"transformedAt":"2026-08-18T18:33:40.653Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":138,"estimatedTokens":587}}14{"id":"stack-59367822","source":"stackoverflow","questionId":59367822,"title":"How can I receive arbitrary props in a Svelte component and pass to a child component?","tags":["javascript","svelte","svelte-3"],"text":"Title: How can I receive arbitrary props in a Svelte component and pass to a child component?\nTags: javascript, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI want to receive arbitrary props from \"above\" and spread them onto an ``, as shown here where `inputProps` would become an object containing any additional props set on this component (similar to python's `**kwargs`, in case you're familiar):\n\n```\n\nexport let id;\nexport ...inputProps;\n\n id: {id}\n \n\n```\n\nCan you point me toward the correct Svelte mechanism for accomplishing something like this? I have a feeling that I'm asking the wrong question, but I need a svelte developer to set me straight. Should I use a slot instead? Or learn about actions / \"the use directive\"?\n\n========================================\n\nTop Answer:\nYou can use `$$props` to access all the props given to a component.\n\n `$$props` references all props that are passed to a component –\n including ones that are not declared with `export`. It is useful in rare\n cases, but not generally recommended, as it is difficult for Svelte to\n optimise.\n\n**Example (REPL)**\n\n```\n\n import Child from './Child.svelte';\n\n let id, inputProps;\n $: ({ id, ...inputProps } = $$props);\n\n id: {id}\n \n\n```\n\n========================================\n\nCode:\n```html\n<script>\nexport let id;\nexport ...inputProps;\n</script>\n\n<div>\n id: {id}\n <input {...inputProps} />\n</div>\n```\n\n```text\n<input>\n```\n\n```text\ninputProps\n```\n\n```text\n**kwargs\n```\n\n```text\n<Widget {...$$props}/>\n```\n\n```text\n<input {...$$restProps}>\n```\n\n```text\n$$restProps\n```\n\n```text\n$$props\n```\n\n```text\n$$restProps\n```\n\n```text\n<script>\n export let id;\n export inputProps;\n</script>\n\n<div>\n id: {id}\n <input {...inputProps} />\n</div>\n```\n\n```html\n<!-- App.svelte -->\n<script>\n import Child from './Child.svelte';\n</script>\n\n<Child id=\"foo\" placeholder=\"bar\" />\n\n<!-- Child.svelte -->\n<script>\n let id, inputProps;\n $: ({ id, ...inputProps } = $$props);\n</script>\n\n<div>\n id: {id}\n <input {...inputProps} />\n</div>\n```\n\n```text\n$$props\n```\n\n```text\n$$props\n```\n\n```text\nexport\n```\n\n```html\n<script lang=\"ts\">\n import type { ComponentProps } from 'svelte';\n import Popover from '../Popover/Popover.svelte';\n export let showTooltip = false;\n let customClasses = '';\n export { customClasses as class };\n export let popoverProps: Omit<ComponentProps<Popover>, 'active'> = {};\n</script>\n\n<!-- svelte-ignore a11y-no-static-element-interactions -->\n<Popover active={showTooltip} {...popoverProps}>\n <div\n class={customClasses}\n on:mouseenter={() => {\n showTooltip = true;\n }}\n on:mouseleave={() => {\n showTooltip = false;\n }}\n slot=\"main\"\n >\n <slot name=\"main\" />\n </div>\n <slot name=\"tooltip\" slot=\"popover\" />\n</Popover>\n```\n\n```text\nComponentProps\n```\n\n```text\nsvelte\n```\n\n========================================\n\nComments:\n- please check your link\n- I don't think this is what he is asking\n- $$props won't forward event handlers.\n- @Zheeeng does that mean in Svelte we cannot do what we do in React, wrap 3rd party components to add some custom props on top of existing ones?\n- Correct @Zheeeng, as of now: I believe we need to manually \"forward\" event handlers to child components using this nice shorthand: svelte.dev/tutorial/event-forwarding\n- @cikatomo are you asking if you can add custom props for use by the wrapper component, or to override some of the props going down to the 3rd party component? Either should be straightforward using $$props and $$restProps. Simply export your custom props or any props that you want to override, then $$restProps will contain the props that you want to pass through to the 3rd party component.\n- @colllin what I mean it's not possible to send all events in one go like answer said here: stackoverflow.com/a/70551898/1079002 , github issue for that is github.com/sveltejs/svelte/issues/2837 . So if I want to build component on top of button we have to type each event, unlike react where all props include events too","metadata":{"transformedAt":"2026-08-18T18:33:40.653Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":180,"estimatedTokens":1015}}15{"id":"stack-65310809","source":"stackoverflow","questionId":65310809,"title":"Do the order of rollup plugins matter?","tags":["svelte","rollup"],"text":"Title: Do the order of rollup plugins matter?\nTags: svelte, rollup\nSource: Stack Overflow\n\nQuestion:\nPlaying around with rollup and Svelte it seems like changing the order of plugins inside of `rollup.config.js` makes no difference.\n\n```\nplugins: [\n svelte({\n preprocess: sveltePreprocess(),\n compilerOptions: {\n // enable run-time checks when not in production\n dev: !production\n }\n }),\n // we'll extract any component CSS out into\n // a separate file - better for performance\n css({ output: 'bundle.css' }),\n\n // If you have external dependencies installed from\n // npm, you'll most likely need these plugins. In\n // some cases you'll need additional configuration -\n // consult the documentation for details:\n // https://github.com/rollup/plugins/tree/master/packages/commonjs\n resolve({\n browser: true,\n dedupe: ['svelte']\n }),\n commonjs(),\n typescript({\n sourceMap: !production,\n inlineSources: !production\n }),\n // In dev mode, call `npm run start` once\n // the bundle has been generated\n !production && serve(),\n\n // Watch the `public` directory and refresh the\n // browser on changes when not in production\n !production && livereload('public'),\n\n // If we're building for production (npm run build\n // instead of npm run dev), minify\n production && terser()\n],\n```\n\nIs it always the case that the order is irrelevant? Do the plugins actually run in sequence or not?\n\n========================================\n\nCode:\n```text\nplugins: [\n svelte({\n preprocess: sveltePreprocess(),\n compilerOptions: {\n // enable run-time checks when not in production\n dev: !production\n }\n }),\n // we'll extract any component CSS out into\n // a separate file - better for performance\n css({ output: 'bundle.css' }),\n\n // If you have external dependencies installed from\n // npm, you'll most likely need these plugins. In\n // some cases you'll need additional configuration -\n // consult the documentation for details:\n // https://github.com/rollup/plugins/tree/master/packages/commonjs\n resolve({\n browser: true,\n dedupe: ['svelte']\n }),\n commonjs(),\n typescript({\n sourceMap: !production,\n inlineSources: !production\n }),\n // In dev mode, call `npm run start` once\n // the bundle has been generated\n !production && serve(),\n\n // Watch the `public` directory and refresh the\n // browser on changes when not in production\n !production && livereload('public'),\n\n // If we're building for production (npm run build\n // instead of npm run dev), minify\n production && terser()\n],\n```\n\n```text\nrollup.config.js\n```\n\n========================================\n\nComments:\n- I'm assuming the order is from \"top-to-bottom\" in the `rollup.config.js` file, and not the reverse, like it is for webpack loaders.\n- Yes, Rollup is left to right, like a pipe, while Webpack is right from left, like compose.","metadata":{"transformedAt":"2026-08-18T18:33:40.654Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":103,"estimatedTokens":730}}16{"id":"stack-58567820","source":"stackoverflow","questionId":58567820,"title":"How do I force a rerender in Svelte when my props changes?","tags":["javascript","svelte"],"text":"Title: How do I force a rerender in Svelte when my props changes?\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI have a totaling component that needs to total the same index of multiple arrays in a multidimensional array, similar to totaling columns in a spread sheet. I have a different component that allows me to change the values in the arrays, and also totals the rows in the spreadsheet. I'm having troubles with the totaling component re-rendering and/or updating the columns total after a change to the array. I thought I might need to do a reactive declaration in my totaling component, but that doesn't seem to be working.\n\nHere's a link to the REPL.\n\nAnd here's the code:\n\n```\nTotals.svelte\n\n export let jobs\n\n //this creates a new array which is two indexes long for each of the columns\n //then fills each array with the sum of column\n //HOW DO I GET THIS TO UPDATE EACH TIME A JOB HOURS ENTRY IS CHANGED?\n $: totals = new Array(2).fill(null).map((v, i) => {\n let total = 0;\n jobs.jobHours.forEach((v) => {\n total += Number(v[i]);\n });\n return total;\n });\n\n //this sums the total hours row to give the grand total\n //HOW DO I GET THIS TO UPDATE EACH TIME THE TOTALS VARIABLE IS CHANGED?\n $: grandTotal = totals.reduce((acc, v) => (acc += v)); \n\n container {\n display: grid;\n grid-template-columns: 2fr 1fr 1fr 1fr; \n\n }\n div {\n width: 100%;\n height: 100%; \n width: 150px;\n }\n\n Total Hours\n {#each totals as total}\n \n {total}\n \n {/each}\n {grandTotal}\n\n```\n\n```\nApp.svelte\n\n import JobEntries from './JobEntries.svelte';\n import Totals from './Totals.svelte';\n\n const jobs = {\n jobNames: ['Job1', 'Job2', 'Job3'], \n jobHours: Array.from(Array(3), () => Array.from(Array(2), ()=>1))\n };\n\n```\n\n```\nJobEntries.svelte\n\n export let jobs\n let cell = Array.from(Array(3), () => Array.from(Array(3)));\n\n container {\n display: grid;\n grid-template-columns: 2fr 1fr 1fr 1fr;\n\n }\n input, div {\n width: 100%;\n height: 100%;\n min-width: 150px;\n }\n\n \n Name\n \n \n Time 1\n \n \n Time 2\n \n \n Total\n \n {#each jobs.jobNames as name, i}\n \n {#each jobs.jobHours[i] as hour, j}\n \n {/each}\n \n {jobs.jobHours[i].reduce((acc,v)=>acc+=v)}\n \n {/each}\n\n```\n\n========================================\n\nCode:\n```text\nTotals.svelte\n\n<script>\n export let jobs\n\n //this creates a new array which is two indexes long for each of the columns\n //then fills each array with the sum of column\n //HOW DO I GET THIS TO UPDATE EACH TIME A JOB HOURS ENTRY IS CHANGED?\n $: totals = new Array(2).fill(null).map((v, i) => {\n let total = 0;\n jobs.jobHours.forEach((v) => {\n total += Number(v[i]);\n });\n return total;\n });\n\n //this sums the total hours row to give the grand total\n //HOW DO I GET THIS TO UPDATE EACH TIME THE TOTALS VARIABLE IS CHANGED?\n $: grandTotal = totals.reduce((acc, v) => (acc += v)); \n\n</script>\n\n<style>\n container {\n display: grid;\n grid-template-columns: 2fr 1fr 1fr 1fr; \n\n }\n div {\n width: 100%;\n height: 100%; \n width: 150px;\n }\n</style>\n\n<container>\n <div>Total Hours</div>\n {#each totals as total}\n <div>\n {total}\n </div>\n {/each}\n <div>{grandTotal}</div>\n</container>\n```\n\n```text\nApp.svelte\n\n<script>\n import JobEntries from './JobEntries.svelte';\n import Totals from './Totals.svelte';\n\n const jobs = {\n jobNames: ['Job1', 'Job2', 'Job3'], \n jobHours: Array.from(Array(3), () => Array.from(Array(2), ()=>1))\n };\n</script>\n\n<JobEntries {jobs}/>\n<Totals {jobs} />\n```\n\n```text\nJobEntries.svelte\n\n<script>\n export let jobs\n let cell = Array.from(Array(3), () => Array.from(Array(3)));\n</script>\n\n<style>\n container {\n display: grid;\n grid-template-columns: 2fr 1fr 1fr 1fr;\n\n }\n input, div {\n width: 100%;\n height: 100%;\n min-width: 150px;\n }\n</style>\n\n<container>\n <div>\n Name\n </div> \n <div>\n Time 1\n </div>\n <div>\n Time 2\n </div>\n <div>\n Total\n </div>\n {#each jobs.jobNames as name, i}\n <input\n type=\"text\" \n bind:this={cell[i][0]}\n bind:value={name} />\n {#each jobs.jobHours[i] as hour, j}\n <input\n type=\"number\" \n bind:this={cell[i][j+1]}\n bind:value={hour}\n />\n {/each}\n <div>\n {jobs.jobHours[i].reduce((acc,v)=>acc+=v)}\n </div>\n {/each}\n</container>\n```\n\n```text\nApp.svelte\n\n<script>\n import JobEntries from './JobEntries.svelte';\n import Totals from './Totals.svelte';\n let jobs = {\n jobNames: ['Job1', 'Job2', 'Job3'], \n jobHours: Array.from(Array(3), () => Array.from(Array(2), ()=>1))\n };\n</script>\n\n<JobEntries bind:jobs/>\n<Totals {jobs} />\n```\n\n```text\nJobEntries.svelte\n\n<script>\n export let jobs \n let cell = Array.from(Array(3), () => Array.from(Array(3)));\n\n</script>\n\n<style>\n container {\n display: grid;\n grid-template-columns: 2fr 1fr 1fr 1fr;\n\n }\n input, div {\n width: 100%;\n height: 100%;\n min-width: 150px;\n }\n</style>\n\n<container>\n <div>\n Name\n </div> \n <div>\n Time 1\n </div>\n <div>\n Time 2\n </div>\n <div>\n Total\n </div>\n {#each jobs.jobNames as name, i}\n <input\n type=\"text\" \n bind:this={cell[i][0]}\n bind:value={name} />\n {#each jobs.jobHours[i] as hour, j}\n <input\n type=\"number\" \n bind:this={cell[i][j+1]}\n bind:value={hour}\n />\n {/each}\n <div>\n {jobs.jobHours[i].reduce((acc,v)=>acc+=v)}\n </div>\n {/each}\n</container>\n```\n\n========================================\n\nComments:\n- The issue comes down to `jobs` never being actually updated in App.svelte, therefore the reactive properties in Totals.svelte such as `totals` and `grandTotals` will never really re-calculate. You need to actually update `jobs` hours or similar via events or it may be a great use case for a svelte store to update jobs in a single place that can reactively be evaluated in other components.\n- This doesn't work for me in sveltekit.","metadata":{"transformedAt":"2026-08-18T18:33:40.654Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":301,"estimatedTokens":1554}}17{"id":"stack-60024414","source":"stackoverflow","questionId":60024414,"title":"How to do code splitting using Svelte without Sapper","tags":["svelte"],"text":"Title: How to do code splitting using Svelte without Sapper\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nHow do you do code splitting with Svelte?\n\n(I see that you could do it using Sapper, but I don´t want to take a dependency on a node backend)\n\n========================================\n\nTop Answer:\nThis repo might be a good place to start https://github.com/Rich-Harris/rollup-svelte-code-splitting\n\n========================================\n\nCode:\n```js\n// \"normal\" static ES import\n//\n// - statically analytisable\n// - must be called at top level\n// - will be greedily resolved (and most often inlined) by your bundler\n//\nimport Foo from './Foo.svelte'\n\n// dynamic import\n//\n// - called like a function\n// - returns a promise\n// - default export is accessible on key `default` of the result\n// - will be bundled into its own chunk by your bundler (hence code splitting)\n//\nimport('./Foo.svelte').then(module => {\n const cmp = module.default\n console.log(module.myNamedExport)\n})\n```\n\n```js\ninput: 'src/main.js', // not changed\n output: {\n format: 'es',\n dir: 'public/build/',\n },\n```\n\n```html\n<script defer type=\"module\" src=\"/build/main.js\"></script>\n```\n\n```js\nimport('./Foo.svelte')\n .then(module => module.default)\n .then(Foo => { /* do something with Foo */ })\n .catch(err => console.error(err))\n```\n\n```html\n<script defer type=\"module\" src=\"https://unpkg.com/dimport?module\"\n data-main=\"/build/main.js\"></script>\n <script defer type=\"nomodule\" src=\"https://unpkg.com/dimport/nomodule\"\n data-main=\"/build/main.js\"></script>\n```\n\n```sh\n# install\nnpx degit rixo/svelte-template-hot#example-code-splitting svelte-app\ncd svelte-app\nyarn # or npm install\n\n# dev\nyarn dev\n\n# build\nyarn build\n# serve build\nyarn start\n```\n\n```text\noutput.format\n```\n\n```text\n'es'\n```\n\n```text\noutput.file\n```\n\n```text\noutput.dir\n```\n\n```text\n'public/build'\n```\n\n```text\n<script>\n```\n\n```text\nindex.html\n```\n\n```text\n/build/main.js\n```\n\n```text\ntype=\"module\"\n```\n\n```text\noutput.format\n```\n\n```text\noutput.dir\n```\n\n```text\niife\n```\n\n```text\noutput.format: 'es'\n```\n\n```text\nimport\n```\n\n```text\nimport\n```\n\n```text\nimport(...)\n```\n\n```text\noutput.format: 'system'\n```\n\n```text\noutput.file\n```\n\n```text\noutput.dir\n```\n\n```text\nbundle.js\n```\n\n```text\nyarn build\n```\n\n```text\nnpm run build\n```\n\n```text\n.js\n```\n\n```text\n<script>\n```\n\n```text\nindex.html\n```\n\n```text\nsrc\n```\n\n```text\nbundle.js\n```\n\n```text\noutput.file\n```\n\n```text\ninput\n```\n\n```text\nsrc/main.js\n```\n\n```text\nmain.js\n```\n\n```text\nentryFileNames\n```\n\n```text\nimport\n```\n\n```text\noutput.format='esm'\n```\n\n```text\nscript\n```\n\n```text\nmodule\n```\n\n```text\ntype=\"module\"\n```\n\n```text\nFoo-[hash].js\n```\n\n```text\nchunkFileNames\n```\n\n```text\nFoo.svelte\n```\n\n```text\nimport('./Foo.svelte')\n```\n\n```text\nFoo\n```\n\n```text\nCmp\n```\n\n```text\nimport(...)\n```\n\n```text\ndimport\n```\n\n```text\n<script>\n```\n\n```text\nindex.html\n```\n\n```text\nexample-code-splitting\n```\n\n```text\nmaster\n```\n\n========================================\n\nComments:\n- Best answer ever! Thx.\n- @rixo Thanks a lot. I am using your template for splitting. When going to production caching is the issue. do you have solution for this : github.com/sveltejs/template/issues/39 `main.js` cached by browser. want to main.js in index.thml with dynamic hash.\n- I use HTTP expiry value of 1 day for the *index.html* (front/proxy server configuration), and also use cache busting strategy (bundler configuration) so that *main.js* script *src* is different every time a deploy occurs.","metadata":{"transformedAt":"2026-08-18T18:33:40.654Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":55,"totalLines":282,"estimatedTokens":876}}18{"id":"stack-68996697","source":"stackoverflow","questionId":68996697,"title":"How to access nested store with dollar sign syntax","tags":["svelte"],"text":"Title: How to access nested store with dollar sign syntax\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to decide on a unified pattern/interface for svelte custom stores. I find it useful to not only export the basic state of the store, but also expose some kind of getters. I can't seem to find a way to use sveltes $-syntax to access the nested stores when not destructured on import though:\n\n**User.store.js** (simplified)\n\n```\nimport { readable, writable } from 'svelte/store';\n\nconst store = writable({\n token: null,\n});\n\nconst loggedIn = readable(false, (set) => store.subscribe(s => set(!!s.token)));\n\nconst login = async (token) => store.set({token});\nconst logout = async () => store.set({token: null};\n\nconst state = {subscribe: store.subscribe}\n\nexport {state, loggedIn, login, logout}\nexport default {state, loggedIn, login, logout}\n```\n\n**Index.svelte**\n\n```\n\nimport {loggedIn} from './User.store.js'\nimport NameSpaced from './User.store.js'\nimport {loggedIn as NameSpacedLoggedIn} from './User.store.js'\n\nLoggedIn 1: {$loggedIn} // WORKS, BUT NOT NAMESPACED (false)\nLoggedIn 2: {NameSpaced.$loggedIn} // DOES NOT WORK (undefined)\nLoggedIn 3: {$NameSpaced.loggedIn} // DOES NOT WORK (undefined)\nLoggedIn 4: {$NameSpacedLoggedIn} // WORKS, BUT CUMBERSOME (false)\n```\n\n### Question\n\nHow to access store with the dollar-syntax when nested/namespaced?\n\n========================================\n\nCode:\n```js\nimport { readable, writable } from 'svelte/store';\n\nconst store = writable({\n token: null,\n});\n\nconst loggedIn = readable(false, (set) => store.subscribe(s => set(!!s.token)));\n\nconst login = async (token) => store.set({token});\nconst logout = async () => store.set({token: null};\n\nconst state = {subscribe: store.subscribe}\n\nexport {state, loggedIn, login, logout}\nexport default {state, loggedIn, login, logout}\n```\n\n```js\n<script>\nimport {loggedIn} from './User.store.js'\nimport NameSpaced from './User.store.js'\nimport {loggedIn as NameSpacedLoggedIn} from './User.store.js'\n\n</script>\n\nLoggedIn 1: {$loggedIn} // WORKS, BUT NOT NAMESPACED (false)\nLoggedIn 2: {NameSpaced.$loggedIn} // DOES NOT WORK (undefined)\nLoggedIn 3: {$NameSpaced.loggedIn} // DOES NOT WORK (undefined)\nLoggedIn 4: {$NameSpacedLoggedIn} // WORKS, BUT CUMBERSOME (false)\n```\n\n```svelte\n<script>\nimport NameSpaced from './User.store.js'\n\nconst loggedIn = NameSpaced.loggedIn;\n</script>\nLoggedIn: {$loggedIn}\n```\n\n========================================\n\nComments:\n- sad, would be a great addition in order to get organized\n- svelte/issues/10953: *Syntax for a reactive $store nested as an object property*","metadata":{"transformedAt":"2026-08-18T18:33:40.654Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":94,"estimatedTokens":653}}19{"id":"stack-61427565","source":"stackoverflow","questionId":61427565,"title":"Import Typescript modules in Svelte Component","tags":["svelte","svelte-3"],"text":"Title: Import Typescript modules in Svelte Component\nTags: svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI have setup `svelte-preprocess` so I can do this successfully:\n\n```\n\n let someConstant:string = \"some constant\";\n console.log({someConstant});\n\n```\n\nThat works. But I don't know how to externalise that constant. If I try:\n\n```\n\n import {someConstant} from './SomeTypescript.ts'\n console.log({someConstant});\n\n```\n\nI get this error message:\n\n`error TS2691: An import path cannot end with a '.ts' extension. Consider importing './SomeTypescript' instead.`\n\nWhen I change it to \n\n```\n\n import {someConstant} from './SomeTypescript'\n console.log({someConstant});\n\n```\n\nI get this error:\n\n`Error: Could not resolve './SomeTypescript' from src/tom/ManageAirtableModels.svelte`\n\nWhats the right way to do this?\n\n========================================\n\nCode:\n```text\n<script lang=\"typescript\">\n let someConstant:string = \"some constant\";\n console.log({someConstant});\n</script>\n```\n\n```text\n<script lang=\"typescript\">\n import {someConstant} from './SomeTypescript.ts'\n console.log({someConstant});\n</script>\n```\n\n```text\n<script lang=\"typescript\">\n import {someConstant} from './SomeTypescript'\n console.log({someConstant});\n</script>\n```\n\n```text\nsvelte-preprocess\n```\n\n```text\nerror TS2691: An import path cannot end with a '.ts' extension. Consider importing './SomeTypescript' instead.\n```\n\n```text\nError: Could not resolve './SomeTypescript' from src/tom/ManageAirtableModels.svelte\n```\n\n```text\nyarn add -D @rollup/plugin-typescript typescript tslib\n```\n\n```js\n//....\nimport autoProcess from 'svelte-preprocess'\nimport typescript from '@rollup/plugin-typescript'\n\nexport default {\n ...\n plugins: [\n typescript(),\n\n svelte({\n preprocess: autoProcess(),\n ...\n })\n ...\n ]\n}\n```\n\n```html\n<script lang=\"typescript\">\n import {someConstant} from './SomeTypescript'\n console.log({someConstant});\n</script>\n```\n\n```text\nplugin-typescript\n```\n\n```text\nplugins\n```\n\n```text\nrollup.config.js\n```\n\n```text\nimport\n```\n\n```text\n.ts\n```\n\n========================================\n\nComments:\n- For those coming here with this problem despite having rollup setup this way, try pointing the rollup typescript plugin's `tsconfig` parameter to the tsconfig you're using for Svelte. Worked for me.","metadata":{"transformedAt":"2026-08-18T18:33:40.654Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":132,"estimatedTokens":584}}20{"id":"stack-73871228","source":"stackoverflow","questionId":73871228,"title":"A transition from svelte/transitions greatly slows down the website","tags":["javascript","html","performance","css-transitions","svelte"],"text":"Title: A transition from svelte/transitions greatly slows down the website\nTags: javascript, html, performance, css-transitions, svelte\nSource: Stack Overflow\n\nQuestion:\nI have a project in svelte that I was developing and feels good.\n\nbut when I go to my android phone I see that when click it is delayed a lot.\n\nfrom what I know svelte is the fastest framework because uses native javascript code as output (no virtual dom) but what is happening here is out of the world (inexplicable)\n\n1000000x slower? what? how it even possible\n\nso I started debugging and investigating.\n\nand I found that without transition everything was fine, speed is good and everything.\n\nbut when starting using transition slow the website.\n\n### debugging\n\nwith chrome devtools\n\nhttps://i.sstatic.net/QhEvV.png\n\nwhen only adding `transition:scale`\n\nlike this ``\n\nhttps://i.sstatic.net/m2Pqh.png\n\nlike you see more than 80% of speed is because that scale transition\n\nhttps://i.sstatic.net/30Kbz.png\n\n### the solution\n\nwithout `transition:scale`\n\nhttps://i.sstatic.net/usWXU.png\n\n❌before\n✅now\n\n3.12s\n5μs\n\nI'm not gonna lie but is like 1000000x faster than the with animation one.\n\n### why? this happens\n\nI know the solution, but I need some explanation or a way to have animation without very very slow things.\n\nthe images you see on the top are the result of a very fast click on the button (like at least 20 times)\n\n========================================\n\nCode:\n```text\ntransition:scale\n```\n\n```text\n<div transition:scale>\n```\n\n```text\ntransition:scale\n```\n\n```html\n<script>\n import { scale } from 'svelte/transition';\n \n let count = 1000;\n let svelte;\n let classBased;\n</script>\n\n<label>\n Item count\n <input type=number bind:value={count} />\n</label>\n\n<label>\n <input type=checkbox bind:checked={svelte}/>\n Svelte transition\n</label>\n\n<label>\n <input type=checkbox bind:checked={classBased}/>\n Class transition\n</label>\n\n{#each { length: count } as i}\n {#if svelte}\n <h1 transition:scale={{duration: 300}}>Hello</h1>\n {/if}\n{/each}\n\n{#each { length: count } as i}\n <h1 class=\"transition\" class:show={classBased}>Hello</h1>\n{/each}\n\n<style>\n .transition {\n visibility: hidden;\n transform: scale(0);\n opacity: 0;\n transition: opacity 0.3s, transform 0.3s, visibility 0s 0.3s;\n }\n .transition.show {\n visibility: visible;\n opacity: 1;\n transform: scale(1);\n transition: opacity 0.3s, transform 0.3s;\n }\n</style>\n```\n\n```text\ntransform\n```\n\n```text\nstyle.animation\n```\n\n========================================\n\nComments:\n- It may be based on the sheer amount of HTML that is being animated\n- Svelte is by no means the fastest framework, just take a look at the benckmarks. Also, the Svelte `transition` directive is using JavaScript to animate the things so it cannot be more performant than similar functionality built in JQuery, as it runs in main thread and consume a lot of CPU with layout reflows. To have performant transitions you should use plain CSS to benefit from GPU acceleration.\n- I'm not sure why this transition is causing a perf hit (a repro would help), but the built-in Svelte transitions don't use JS to animate things - they construct a CSS animation using JS, and then apply it to the element as a regular CSS animation (which is off the main thread). See the tutorial\n- @GeoffRich \"*don't use JS to animate things - they construct a CSS animation using JS*\" you are contradicting yourself with this statement, also the tutorial is useless in giving an answer related to technical implementation, you should have to look at the source code, just search for 'getComputedStyle' to see how many layout trashes Svelte does, and check out the easing zero-CSS solution.\n- @n--: What Goeff is saying is: The JS is not used to set style properties in a loop, instead it generates the CSS for an animation and starts that. Hence, *not* a JS animation. The easing functions are used to calculate the property values in the CSS animation, never to set the properties directly.\n- `getComputedStyle` is commonly only used *once* to get an existing/start value.\n- I'm using svelte for an analog clock and using `svelte/easing` (as opposed to `svelte/transition` used in this thread). I notice significant performance problems but I'm only animating one element (the second hand) and doing so every second. Any possible way to improve performance with vanilla CSS and/or JS?\n- If you are not using very particular easings, you probably can just use regular CSS animations/transitions. Animating one element really should not be a performance issue, though. I suggest you ask a separate question and show your code, then people can more easily suggest appropriate solutions.","metadata":{"transformedAt":"2026-08-18T18:33:40.654Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":139,"estimatedTokens":1196}}21{"id":"stack-72443353","source":"stackoverflow","questionId":72443353,"title":"How do I use tailwindcss @apply directive inside a svelte component","tags":["javascript","webpack","tailwind-css","svelte","postcss"],"text":"Title: How do I use tailwindcss @apply directive inside a svelte component\nTags: javascript, webpack, tailwind-css, svelte, postcss\nSource: Stack Overflow\n\nQuestion:\nThis works:\n\n```\n\n```\n\nThis doesn't work:\n\n```\n\n @tailwind base;\n @tailwind components;\n @tailwind utilities;\n\n @layer components {\n .list {\n @apply p-2;\n }\n }\n\n```\n\nI looked in Svelte's docs, but it explains the process with SvelteKit, which I'm not using. How can I make it work?\n\nwebpack.config.js:\n\n```\n...\nmodule: {\nrules: [\n {\n test: /\\.css$/i,\n use: ['style-loader', 'css-loader', 'postcss-loader'],\n },\n```\n\ntailwind.config.js:\n\n```\nmodule.exports = {\n purge: [\n './*.html',\n './src/**/*.js',\n './src/**/*.svelte'\n ],\n darkMode: false, // or 'media' or 'class'\n theme: {\n extend: {},\n },\n variants: {\n extend: {},\n },\n plugins: [],\n}\n```\n\npostcss.config.js:\n\n```\nmodule.exports = {\n plugins: [\n ['tailwindcss'],\n ['autoprefixer'],\n ],\n};\n```\n\n========================================\n\nTop Answer:\nYou need to install `svelte-preprocess` and use it in the `svelte-loader` for Webpack.\n\nThe documentation for using `@import` gives an example:\n\n```\nconst sveltePreprocess = require('svelte-preprocess');\n...\nmodule.exports = {\n ...\n module: {\n rules: [\n ...\n {\n test: /\\.(html|svelte)$/,\n use: {\n loader: 'svelte-loader',\n options: {\n preprocess: sveltePreprocess({\n postcss: true\n })\n }\n }\n }\n ...\n ]\n },\n plugins: [\n new webpack.HotModuleReplacementPlugin(),\n ...\n ]\n}\n```\n\n(You may need various peer dependencies like `postcss` itself and `postcss-load-config` depending on which kinds of features you use.)\n\n========================================\n\nCode:\n```text\n<div class=\"list p-2\" />\n```\n\n```text\n<style lang=\"postcss\">\n @tailwind base;\n @tailwind components;\n @tailwind utilities;\n\n @layer components {\n .list {\n @apply p-2;\n }\n }\n</style>\n```\n\n```text\n...\nmodule: {\nrules: [\n {\n test: /\\.css$/i,\n use: ['style-loader', 'css-loader', 'postcss-loader'],\n },\n```\n\n```text\nmodule.exports = {\n purge: [\n './*.html',\n './src/**/*.js',\n './src/**/*.svelte'\n ],\n darkMode: false, // or 'media' or 'class'\n theme: {\n extend: {},\n },\n variants: {\n extend: {},\n },\n plugins: [],\n}\n```\n\n```text\nmodule.exports = {\n plugins: [\n ['tailwindcss'],\n ['autoprefixer'],\n ],\n};\n```\n\n```text\n<style lang=\"postcss\">\n .list {\n @apply p-2;\n }\n</style>\n```\n\n```text\n<style lang=\"postcss\">\n @import \"tailwindcss\";\n \n .list {\n @apply p-2;\n }\n</style>\n```\n\n```js\nconst sveltePreprocess = require('svelte-preprocess');\n...\nmodule.exports = {\n ...\n module: {\n rules: [\n ...\n {\n test: /\\.(html|svelte)$/,\n use: {\n loader: 'svelte-loader',\n options: {\n preprocess: sveltePreprocess({\n postcss: true\n })\n }\n }\n }\n ...\n ]\n },\n plugins: [\n new webpack.HotModuleReplacementPlugin(),\n ...\n ]\n}\n```\n\n```text\nsvelte-preprocess\n```\n\n```text\nsvelte-loader\n```\n\n```text\n@import\n```\n\n```text\npostcss\n```\n\n```text\npostcss-load-config\n```\n\n```css\n@import \"tailwindcss\";\n\n@theme {\n \n}\n```\n\n```html\n<style lang=\"postcss\">\n@reference \"./../css/global.css\";\n \n.list {\n @apply p-2;\n}\n</style>\n```\n\n```html\n<style lang=\"postcss\">\n@reference \"tailwindcss\";\n \n.list {\n @apply p-2;\n}\n</style>\n```\n\n```text\n@import \"tailwindcss\";\n```\n\n```text\n@import \"tailwindcss\";\n```\n\n```text\n@reference\n```\n\n```text\n@reference\n```\n\n```text\n@apply\n```\n\n```text\n@variant\n```\n\n```text\n<style>\n```\n\n```text\ntailwindcss\n```\n\n```text\n@reference\n```\n\n========================================\n\nComments:\n- Thank you, it's working now but it won't purge unused css. I'm getting 74 warnings of unused CSS selectors as soon as I add the three @tailwind directives in my tag. I tried manually setting process.env.NODE_ENV to \"production\" and my tailwind.config.js is bare bones.\n- You might want to place the `@tailwind` directives in a `global` style tag on a root component (example). That should get rid of the warnings, but I do not know if the purging will automatically work.\n- I tried that before, but for some reason the @tailwind directives are not being treated as global. If I try to use @apply in another component I get an error \"no matching `@tailwind components` directive\". A regular CSS selector works, it affects other components. The styles are in ``\n- Testing things further, if I only include the @tailwind directives in my main component, the tailwind classes that you apply inline to elements work fine, only when I try to use `@layer components` I get the error. And when I add the directives to that component as well, it complains about css duplication.\n- Related: **Stop using `@apply` - Moni**\n- imho, it should be the accepted answer : use reference over import tailwindcss if tailwind is already imported in a global.css\n- This should be the accepted answer. And while @apply might not be the best practice and you're better of writing ``, is suppose there are some valid use cases.\n- @rozsazoltan What if i have `{@html content}`, and i want to style h2 inside the content? Is `@reference \"./../css/global.css\"; :global(.content h2) { @apply text-primary; }` still worse than `{@html content}`?","metadata":{"transformedAt":"2026-08-18T18:33:40.654Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":310,"estimatedTokens":1313}}22{"id":"stack-65998542","source":"stackoverflow","questionId":65998542,"title":"How should I use Svelte Reactivity with DOM getElementById?","tags":["javascript","scroll","scrollbar","svelte","svelte-component"],"text":"Title: How should I use Svelte Reactivity with DOM getElementById?\nTags: javascript, scroll, scrollbar, svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI have a div element where it is scrollable\n\n```\n\n let scrollBoxObj;\n $: scrollBoxObj = document.getElementById(\"chat-box\");\n \n $: if (!(scrollBoxObj === undefined) && scrollBoxObj.scrollTop \n \n \n {#each chatBox as { user, content, type}}\n \n {/each}\n \n \n\n \n .chat-box {\n overflow-y: auto;\n }\n \n```\n\ni am trying to auto scroll down when a new message is added.\nbut it is not reactive.\nor i didn't understand how reactivity works in svelte.\ni also tried to assign scrollBoxObj in onMount but it was still the same result didn't work.\n\n========================================\n\nCode:\n```text\n<script>\n let scrollBoxObj;\n $: scrollBoxObj = document.getElementById(\"chat-box\");\n \n $: if (!(scrollBoxObj === undefined) && scrollBoxObj.scrollTop < scrollBoxObj.scrollHeight) {\n scrollBoxObj.scrollTop = scrollBoxObj.scrollHeight;\n }\n </script>\n <div id=\"scrollBox\" class=\"h-screen w-auto chat-box border border-orange rounded\">\n <div id=\"chat-box\" style=\"margin: 0\" class=\"chat-box\">\n {#each chatBox as { user, content, type}}\n <MessageBox {user} message={content} {type} />\n {/each}\n </div>\n </div>\n\n <style>\n .chat-box {\n overflow-y: auto;\n }\n </style>\n```\n\n```js\n$: scrollBoxObj = document.getElementById(\"chat-box\");\n```\n\n```html\n<script>\n let scrollbox\n</script>\n\n<div bind:this={scrollbox}>\n ...\n</div>\n```\n\n```js\n$: if (scrollBoxObj && scrollBoxObj.scrollTop < scrollBoxObj.scrollHeight) {\n scrollBoxObj.scrollTop = scrollBoxObj.scrollHeight;\n}\n```\n\n```text\n$: x = y\n```\n\n```text\ny\n```\n\n```text\ndocument.getElementById\n```\n\n```text\nbind:this={variable}\n```\n\n```text\non:scroll\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.654Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":99,"estimatedTokens":470}}23{"id":"stack-70990443","source":"stackoverflow","questionId":70990443,"title":"Unable to access request.body from the endpoint.js in sveltekit skeleton project","tags":["svelte","endpoint","sveltekit"],"text":"Title: Unable to access request.body from the endpoint.js in sveltekit skeleton project\nTags: svelte, endpoint, sveltekit\nSource: Stack Overflow\n\nQuestion:\nAfter initiating a skeleton project from sveltekit app. my index has a form :\n\n```\n\n let name\n let password\n\n async function submitit(){\n // console.log(\"name is :\", name)\n // console.log(\"password is :\", password)\n \n const doit = async () =>{\n let res = await fetch( 'formdata' ,{\n method : \"post\",\n headers: { \n 'Accept': 'application/json',\n 'content-type' : 'text/html; charset=UTF-8',\n //'Content-Type': 'multipart/form-data'\n },\n body : JSON.stringify({\n name : \"name\",\n password : \"password\"\n }) \n })// fetch\n let results =await res.json()\n console.log( \"xxxxxxxxxxxxxxxxxxxxx\" , results )\n return results\n } \n\n doit().then(data =>{\n console.log(\"data log : \" , data)\n })\n\n } //submitit\n\n \n Name :\n \n \n\n Password :\n \n \n\n Submit\n\n```\n\nmy endpoint formdata.js\n\n```\nexport async function post(request) { \n\n console.log(\"formdata js log of request : \", request)\n \n return {\n \n status : 200,\n headers: { \n 'content-type': 'application/json'\n },\n body : { \n message : \"login form submitted the login credentials\",\n }\n }\n\n}\n```\n\nWhen I click submit, the index.svelte returns the message \"login form submitted the login credentials\" and it is in the console.log of the browser. The cmd which is used to run the application using npm run dev, logs the dataform.js request and prints the following :\n\n```\nformdata js log of request : {\n request: Request {\n size: 0,\n : 20,\n compress: true,\n counter: 0,\n agent: undefined,\n highWaterMark: 16384,\n insecureHTTPParser: false,\n [Symbol(Body internals)]: {\n body: ,\n stream: [Readable],\n boundary: null,\n disturbed: false,\n error: null\n },\n [Symbol(Request internals)]: {\n method: 'POST',\n redirect: '',\n headers: [Object],\n parsedURL: [URL],\n signal: null,\n referrer: undefined,\n referrerPolicy: ''\n }\n },\n url: URL {\n href: 'http://127.0.0.1:3000/formdata',\n origin: 'http://127.0.0.1:3000',\n protocol: 'http:',\n username: '',\n password: '',\n host: '127.0.0.1:3000',\n hostname: '127.0.0.1',\n port: '3000',\n pathname: '/formdata',\n search: '',\n searchParams: URLSearchParams {},\n hash: ''\n },\n params: {},\n locals: {},\n platform: undefined\n}\n```\n\nNotice the following:\n1- there is no username or password fields in my form or the body json.stringify in the index.svelte but it is in the request log under the url section (both are empty despite the dummy text I entered in index.svelte)\n\n2- body stream is readable. I indicated the application to accept/send json.\n\nI also find this pr from Rich and have no idea if what I'm facing is because of this change. Here is the PR\n\nI'm lost with this sveltekit. I had great experience with Sapper and I hope I could figure out sveltekit so I can go on and start developing my application but this is the first step in any application, process form data.\n\n=================================================================\n\n****************** update : Explain needed if possible *****************************\nI still would like to understand how you got the event argument from this pr because in Rich's post, the code with + is the updated one. It doesn't mention event:\n\nUpdating endpoints\nSimilarly, handlers receive a RequestEvent. Most GET handlers will be unchanged, but any handler that needs to read the request body will need to update:\n\n```\n-export async function post({ params, body }) {\n+export async function post({ params, request }) {\n+ const body = await request.formData(); // or request.json(), etc\n await do_something_with(params, body);\n return { status: 201 };\n}\n```\n\n### there is no mention in event anywhere. How did you get the keyword \"event\" as an argument for the function?\n\n========================================\n\nTop Answer:\nYou're right that the PR changed how you access the body. Now to access the request body in your endpoint you have to use:\n\n```\nconst body = await request.json()\n```\n\nIf you directly used your form to send the data (with `action=\"/path/to/endpoint\"`) you would use:\n\n```\nconst body = await request.formData()\n```\n\nEdit: Note that the `Response` interface (`request` in SvelteKit) is a standard part of the Fetch API.\n\nDocs on the request object (all methods)\n\nSee SvelteKit docs for +server.ts\n\n========================================\n\nCode:\n```text\n<script>\n let name\n let password\n\n async function submitit(){\n // console.log(\"name is :\", name)\n // console.log(\"password is :\", password)\n \n const doit = async () =>{\n let res = await fetch( 'formdata' ,{\n method : \"post\",\n headers: { \n 'Accept': 'application/json',\n 'content-type' : 'text/html; charset=UTF-8',\n //'Content-Type': 'multipart/form-data'\n },\n body : JSON.stringify({\n name : \"name\",\n password : \"password\"\n }) \n })// fetch\n let results =await res.json()\n console.log( \"xxxxxxxxxxxxxxxxxxxxx\" , results )\n return results\n } \n\n doit().then(data =>{\n console.log(\"data log : \" , data)\n })\n\n\n } //submitit\n\n\n</script>\n\n\n\n\n\n\n\n\n\n<form on:submit|preventDefault={submitit}>\n <p>\n <label>Name :\n <input type=\"text\" placeholder=\"name\" aria-label=\"name\" required bind:value={name}>\n </label>\n</p>\n<p>\n <label>Password :\n <input type=\"password\" placeholder=\"password\" aria-label=\"password\" required bind:value={password}>\n </label>\n</p>\n <button type=\"submit\">Submit</button>\n</form>\n```\n\n```text\nexport async function post(request) { \n\n console.log(\"formdata js log of request : \", request)\n \n return {\n \n status : 200,\n headers: { \n 'content-type': 'application/json'\n },\n body : { \n message : \"login form submitted the login credentials\",\n }\n }\n\n}\n```\n\n```text\nformdata js log of request : {\n request: Request {\n size: 0,\n follow: 20,\n compress: true,\n counter: 0,\n agent: undefined,\n highWaterMark: 16384,\n insecureHTTPParser: false,\n [Symbol(Body internals)]: {\n body: <Buffer 7b 22 6e 61 6d 65 22 3a 22 6e 61 6d 65 22 2c 22 70 61 73 73 77 6f 72 64 22 3a 22 70 61 73 73 77 6f 72 64 22 7d>,\n stream: [Readable],\n boundary: null,\n disturbed: false,\n error: null\n },\n [Symbol(Request internals)]: {\n method: 'POST',\n redirect: 'follow',\n headers: [Object],\n parsedURL: [URL],\n signal: null,\n referrer: undefined,\n referrerPolicy: ''\n }\n },\n url: URL {\n href: 'http://127.0.0.1:3000/formdata',\n origin: 'http://127.0.0.1:3000',\n protocol: 'http:',\n username: '',\n password: '',\n host: '127.0.0.1:3000',\n hostname: '127.0.0.1',\n port: '3000',\n pathname: '/formdata',\n search: '',\n searchParams: URLSearchParams {},\n hash: ''\n },\n params: {},\n locals: {},\n platform: undefined\n}\n```\n\n```text\n-export async function post({ params, body }) {\n+export async function post({ params, request }) {\n+ const body = await request.formData(); // or request.json(), etc\n await do_something_with(params, body);\n return { status: 201 };\n}\n```\n\n```js\nexport async function post(event) {\n const body = await event.request.json();\n console.log('request body: ', body );\n // ... the rest is the same as before\n}\n```\n\n```js\nexport async function post({ request }) {\n const body = await request.json();\n console.log('request body: ', body );\n // ... the rest is the same as before\n}\n```\n\n```text\npost\n```\n\n```text\nrequest\n```\n\n```text\nrequest.body\n```\n\n```text\nevent\n```\n\n```text\nevent.request\n```\n\n```js\nconst body = await request.json()\n```\n\n```js\nconst body = await request.formData()\n```\n\n```text\naction=\"/path/to/endpoint\"\n```\n\n```text\nResponse\n```\n\n```text\nrequest\n```\n\n========================================\n\nComments:\n- Thanks for taking the time to comment. This issue deserves more attention because the endpoints are broken. As you can see from my code, I'm not using the action property. When I add const data = await request.json(), when compile using npm run dev, I get an error that request.json() is not a function. I don't know how to reach any of the maintainers to let them know or what to do to fix it.\n- Sorry, I couldn't be more helpful. I completely missed that in the docs they used object destructing (`post{( request })`) and your code didn't (`post(request)`).\n- It works and thank you for your help. I updated my question with a little request to understand how did you get that the function argument needed the event keyword? There is nothing in Rich's text or code that mentioned \"event\" keyword argument? Do you mind if you explain it to me so in the future I would be able to read those pr and be able to help myself. Thank you for all your help.\n- @Marco request in handle has been replaced with event. See github.com/sveltejs/kit/pull/3384 for details. Update occured on 19 Jan 2022. Look closely at the hooks.js example. But you are right, the info on that github pull link is not very clear. And the worst, *To access the request body use the text/json/arrayBuffer/formData methods, e.g. `body = await request.json()`* is a terrible error message\n- `request.json is not a function`","metadata":{"transformedAt":"2026-08-18T18:33:40.654Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":374,"estimatedTokens":2326}}24{"id":"stack-61585435","source":"stackoverflow","questionId":61585435,"title":"How to get store value from another store?","tags":["svelte","svelte-3","svelte-store"],"text":"Title: How to get store value from another store?\nTags: svelte, svelte-3, svelte-store\nSource: Stack Overflow\n\nQuestion:\nHow to get store value from another store?\nhttps://svelte.dev/repl/0ab80c2fb8e045958d844bd4b11c04a9?version=3.22.1\n\nIn the example I include a variable `inputVal` in `stores.js` file and changing in\n\n`set: (val) => {inputVal=val; set( val );}, and use in fn setToZero`\n\nQuestion: how to do it directly without using the `inputVal` variable?\n\n========================================\n\nCode:\n```text\ninputVal\n```\n\n```text\nstores.js\n```\n\n```text\nset: (val) => {inputVal=val; set( val );}, and use in fn setToZero\n```\n\n```text\ninputVal\n```\n\n```js\nimport {get, writable} from 'svelte/store'\n\nconst myStore = writable(41)\n\nconst value = get(myStore)\n```\n\n```text\nget(store)\n```\n\n```text\n.svelte\n```\n\n```text\n$\n```\n\n```text\nconst value = $myStore\n```\n\n========================================\n\nComments:\n- Minus of this solution: \"This works by creating a subscription, reading the value, then unsubscribing. It's therefore not recommended in hot code paths.\" svelte.dev/docs#get\n- Alternatives: 1) Use `store.subscribe(callback)`, the callback will be notified when the value changes. 2) Use a derived store `derived([storeA, storeB, ...], callback)`, when any dependent stores change your callback can produce a new (aggregate) value\n- @lukaszpolowczyk's link is now svelte.dev/docs#run-time-svelte-store-get","metadata":{"transformedAt":"2026-08-18T18:33:40.654Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":63,"estimatedTokens":356}}25{"id":"stack-71767581","source":"stackoverflow","questionId":71767581,"title":"How do I disable minification when running \"build\" command in sveltekit?","tags":["svelte","vite","sveltekit"],"text":"Title: How do I disable minification when running \"build\" command in sveltekit?\nTags: svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am deploying sveltekit to a dfinity container and I need to disable minification to debug.\n\nI have to build a static version to deploy it with `npm run build` -- is there a vite option to disable minification?\n\nI've tried this: `svelte.config.js` but it doesn't do anything:\n\n```\nvite: {\n resolve: {\n alias: {\n $components: path.resolve('./src/components'),\n $stores: path.resolve('./src/stores'),\n $api: path.resolve('./src/api')\n }\n },\n build: {\n minify: false\n }\n}\n```\n\n========================================\n\nCode:\n```js\nvite: {\n resolve: {\n alias: {\n $components: path.resolve('./src/components'),\n $stores: path.resolve('./src/stores'),\n $api: path.resolve('./src/api')\n }\n },\n build: {\n minify: false\n }\n}\n```\n\n```text\nnpm run build\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n plugins: [sveltekit()],\n build: {\n minify: false\n }\n});\n```\n\n```text\nvite.config.js/ts\n```\n\n========================================\n\nComments:\n- I cannot reproduce the issue. `vite.build.minify=false` does actually disable minification in a newly scaffolded SvelteKit project. Can you a link to a reproduction of the problem?\n- that works. it still compiled it but did not minify. so we're good.","metadata":{"transformedAt":"2026-08-18T18:33:40.654Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":73,"estimatedTokens":382}}26{"id":"stack-56817063","source":"stackoverflow","questionId":56817063,"title":"How to bind variable declared with Svelte let directive?","tags":["svelte"],"text":"Title: How to bind variable declared with Svelte let directive?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to workaround \"Cannot bind to a variable declared with the let: directive\" error.\n\n```\n// FancyList.svelte\n\n export let items = [] \n\n {#each items as item, i}\n \n- \n {/each} \n\n// App.svelte\n\n import FancyList from './FancyList.svelte'\n let items = [ {x: 'AX', y: 'AY'}, {x: 'BX', y: 'BY'}, {x: 'CX', y: 'CY'}]\n\n \n \n\n```\n\nAvailable as Svelte REPL\n\n### Things I have tried so far\n\n1) Making `FancyList` to pass item index instead of item itself and binding `items[index]` instead of `item`.\n\n```\n\n \n \n\n```\n\nAvailable as Svelte REPL\n\nThis will initially render properly but will emit \"ReferenceError: index is not defined\" error upon input value change.\n\n2) Making `FancyList` to pass `onChange` callback and not using `bind`.\n\n```\n\n onChange({...item, x: e.target.value})}>\n onChange({...item, y: e.target.value})}>\n\n```\n\nAvailable as Svelte REPL.\n\nThis works but is significantly more verbose.\n\n========================================\n\nTop Answer:\nYou can use `svelte:component` to accomplish this. It basically will let you pass a component to your FancyList, making it a Higher Order Component of sorts.\n\nHere's a REPL example that shows it working:\n\nhttps://svelte.dev/repl/bc985c21735f4b2a9945f1ddc74988e6?version=3.6.1\n\n========================================\n\nCode:\n```text\n// FancyList.svelte\n<script>\n export let items = [] \n</script>\n\n<ul>\n {#each items as item, i}\n <li><slot item={item}></slot></li>\n {/each} \n</ul>\n\n// App.svelte\n<script>\n import FancyList from './FancyList.svelte'\n let items = [ {x: 'AX', y: 'AY'}, {x: 'BX', y: 'BY'}, {x: 'CX', y: 'CY'}]\n</script>\n\n<FancyList bind:items={items} let:item={item}>\n <input type=text bind:value={item.x}>\n <input type=text bind:value={item.y}>\n</FancyList>\n```\n\n```text\n<FancyList items={items} let:index={index}>\n <input type=text bind:value={items[index].x}>\n <input type=text bind:value={items[index].y}>\n</FancyList>\n```\n\n```text\n<FancyList bind:items={items} let:item={item} let:onChange={onChange}>\n <input type=text value={item.x} on:input={e => onChange({...item, x: e.target.value})}>\n <input type=text value={item.y} on:input={e => onChange({...item, y: e.target.value})}>\n</FancyList>\n```\n\n```text\nFancyList\n```\n\n```text\nitems[index]\n```\n\n```text\nitem\n```\n\n```text\nFancyList\n```\n\n```text\nonChange\n```\n\n```text\nbind\n```\n\n```text\nsvelte:component\n```\n\n========================================\n\nComments:\n- This throws an error that it can't bind to a variable declared with the `let:` directive\n- That REPL has the same error `Cannot bind to a variable declared with the let: directive`\n- something must have changed 🤷♂️","metadata":{"transformedAt":"2026-08-18T18:33:40.654Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":141,"estimatedTokens":690}}27{"id":"stack-62761623","source":"stackoverflow","questionId":62761623,"title":"How do you import a Svelte component in a Typescript file?","tags":["typescript","svelte","rollup"],"text":"Title: How do you import a Svelte component in a Typescript file?\nTags: typescript, svelte, rollup\nSource: Stack Overflow\n\nQuestion:\nIs it possible to import a Svelte component in a Typescript file and have Rollup successfully compile it?\n\nThe following code works as a Javascript file, but errors when converted to Typescript, because the TS compiler doesn’t know how to handle a `.svelte` file:\n\n```\nimport Component from './Component.svelte';\n\nconst foo = () => new Component({ target: document.body });\n```\n\nIs there a combination of `rollup-plugin-svelte` and `@rollup/plugin-typescript` that will preprocess the Svelte component in such a way that the Typescript compiler can include the Svelte code?\n\nIn case some more context is helpful, boardgame.io includes an in-browser debugging component built with Svelte, which is bundled in both a plain JS client & in a React client component, and we’re trying to update our Rollup config for exactly this scenario.\n\n========================================\n\nTop Answer:\nTry adding `@tsconfig/svelte` to your project, then updating your tsconfig.json file:\n\n```\n{\n \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n \"include\": [\"src/**/*\"],\n \"exclude\": [\"node_modules/*\", \"__sapper__/*\", \"public/*\"],\n}\n```\n\n========================================\n\nCode:\n```js\nimport Component from './Component.svelte';\n\nconst foo = () => new Component({ target: document.body });\n```\n\n```text\n.svelte\n```\n\n```text\nrollup-plugin-svelte\n```\n\n```text\n@rollup/plugin-typescript\n```\n\n```text\ndeclare module '*.svelte' {\n export { SvelteComponentDev as default } from 'svelte/internal';\n}\n```\n\n```js\n{\n // ... Omitted...\n\n \"compilerOptions\": {\n // ... Omitted...\n\n \"types\": [\"svelte\"]\n }\n}\n```\n\n```text\n/// <reference types=\"svelte\" />\n```\n\n```text\nimport \"svelte\";\n```\n\n```js\n{\n \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n \n // ... Omitted...\n\n \"compilerOptions\": {\n // ... Omitted...\n\n \"types\": [\"node\"] // This overrides [\"svelte\"]!\n }\n}\n```\n\n```text\n.svelte\n```\n\n```text\n3.35.0\n```\n\n```text\nsvelte/types/runtime/ambient.d.ts\n```\n\n```text\n.svelte\n```\n\n```text\n.svelte\n```\n\n```text\nset_attributes()\n```\n\n```text\nsvelte/internal\n```\n\n```text\ndeclare module '*.svelte' {}\n```\n\n```text\n.svelte\n```\n\n```text\nsvelte/types/runtime/ambient.d.ts\n```\n\n```text\ntypes\n```\n\n```text\npackage.json\n```\n\n```text\ntypes/runtime/index.d.ts\n```\n\n```text\n@tsconfig/svelte/tsconfig.json\n```\n\n```text\n\"svelte\"\n```\n\n```text\ncompilerOptions.types\n```\n\n```text\n\"types\": [\"node\"]\n```\n\n```text\n\"types\": [\"node\", \"svelte\"]\n```\n\n```text\n{\n \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n \"include\": [\"src/**/*\"],\n \"exclude\": [\"node_modules/*\", \"__sapper__/*\", \"public/*\"],\n}\n```\n\n```text\n@tsconfig/svelte\n```\n\n========================================\n\nComments:\n- The typescript compiler need to know about `./Component.svelte` module. You need to define it. `Rollup` is a bundler, and it needs to know how to handle modules as well, which is the role of rollup's plugin.\n- Full Typescript support for Svelte is likely to be days away - take a look at this Twitter thread which is pretty close to confirmation twitter.com/sveltejs/status/1277235019845644288?s=20\n- Thanks! This seems to make `tsc` happy, but for a library consumer using Typescript, no declaration file is output for the Svelte entrypoint and they would see a “TS2307: Cannot find module `./Component.svelte` or its corresponding type declarations” error when requiring a module that imports the component. Would any Typescript consumer also need tsconfig to extend `@tsconfig/svelte/tsconfig.json` or add `\"types\": [\"svelte\", ...]`? Or is there a way to output a type declaration for the component?\n- Not sure — if it's a library that consumes a component, it sounds like maybe you need to remove `node_modules` from the `exclude` array?\n- Not sure if this is the right approach, but I got it working by adding `import 'svelte'` to our main type definitions. Svelte has to be a dependency (instead of a dev dependency) to ensure it’s installed for consumers, but this seems to make the ambient `*.svelte` module declaration visible for consumers too.\n- Ah, in fact, doing that means we also don’t need to tell `tsc` about the Svelte types in tsconfig.json, because they’re already hoisted by the import.\n- I just added `import 'svelte'` to one of my ts files (the root one) and it worked. Thanks @delucis","metadata":{"transformedAt":"2026-08-18T18:33:40.654Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":187,"estimatedTokens":1104}}28{"id":"stack-57390682","source":"stackoverflow","questionId":57390682,"title":"Debugging with svelte","tags":["svelte"],"text":"Title: Debugging with svelte\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to dig into Svelte 3 (v3.7.1) and it works quite well ... with a few stumbling blocks when it comes to including external CSS (bootstrap).\n\nBut nevertheless, one thing I cannot seem to wrap my head around is debugging the svelte app in my browser\n\nI found a post on svelte github issues that stated that I just need to include `{@debug}` somewhere in my code in order to make the browser break at \"that point\" so I can debug and inspect current state.\n\nBut: This does not work at all. Even though the `{@debug}` is present, there is no breaking even though I have the developer tools open.\n\nWhat do I have to do in order to debug my code? \n\nEDIT: I figured you needed to know about my setup\n\nI use a node/express web server that serves the compiled svelte client as `app.use(express.static('svelteclient/public'))` from the svelte project's subfolder.\n\nCode excerpt:\n\n```\n\n import { onMount } from 'svelte';\n\n let searches = [\"angular\", \"deno\", \"svelte\", \"stencil\"];\n let tweets = {};\n\n let currentImage = null;\n let currentYTUrl = \"\";\n\n for(let search of searches) {\n tweets[search] = [];\n }\n\n let socket = io();\n\n let modal = null;\n let ytmodal = null;\n\n onMount(() => {\n modal = UIkit.modal('#mymodal');\n ytmodal = UIkit.modal('#myytmodal');\n });\n\n...\n\n .uk-panel-badge .uk-badge {\n cursor: pointer;\n }\n\n{@debug}\n\n {#each searches as search}\n \n ...\n \n {/each}\n\n```\n\nChrome version is 75.0.3770.142\n\n========================================\n\nTop Answer:\nThe `{@debug}` template syntax can be used as an alternative to `console.log`.\n\nYou can place it in your html code, and then open the `devtools` of your browser.\n\nIf your component goes through the `@debug` statement while the `devtools` are open, it will automatically pause the execution.\n\n**edit**\n\nif you have this svelte code\n\n```\n\n let name = 'world';\n\n{@debug name}\n\n### Hello {name}!\n\n```\n\nit will compile to\n\n```\n// more code\nc: function create() {\n {\n const { } = ctx;\n console.log({ name }); // It will run every time the component is rendered. Including the first time. It isn't bound to the value change if said value change doesn't trigger a new render.\n\nIf you want to bind a console log to a value change you need to use a **reactive statement** in your script\n\n```\n$: console.log(name);\n```\n\nor\n\n```\n$: value, console.log('value has been updated');\n```\n\nthe `debugger` statement stop the script execution in both Chrome 76 and Firefox Quantum 68\n\n========================================\n\nCode:\n```text\n<script>\n\n import { onMount } from 'svelte';\n\n let searches = [\"angular\", \"deno\", \"svelte\", \"stencil\"];\n let tweets = {};\n\n let currentImage = null;\n let currentYTUrl = \"\";\n\n for(let search of searches) {\n tweets[search] = [];\n }\n\n let socket = io();\n\n let modal = null;\n let ytmodal = null;\n\n onMount(() => {\n modal = UIkit.modal('#mymodal');\n ytmodal = UIkit.modal('#myytmodal');\n });\n\n...\n</script>\n\n<style>\n .uk-panel-badge .uk-badge {\n cursor: pointer;\n }\n</style>\n\n{@debug}\n\n\n<div class=\"uk-grid\" data-uk-grid-margin>\n {#each searches as search}\n <div class={'uk-width-medium-1-' + searches.length}>\n ...\n </div>\n {/each}\n</div>\n```\n\n```text\n{@debug}\n```\n\n```text\n{@debug}\n```\n\n```text\napp.use(express.static('svelteclient/public'))\n```\n\n```text\nplugins: [\n svelte({\n // Always enable run-time checks\n dev: true,\n ...\n }),\n ...\n // NOT use terser, otherwise debugger will be stripped!\n //production && terser()\n```\n\n```text\ndebugger\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run build\n```\n\n```html\n<script>\n let name = 'world';\n</script>\n\n{@debug name}\n\n<h1>Hello {name}!</h1>\n```\n\n```js\n// more code\nc: function create() {\n {\n const { } = ctx;\n console.log({ name }); // <-- Note those 2 lines\n debugger; // <-- corresponding to the @debug statement\n }\n\n t0 = space();\n h1 = element(\"h1\");\n t1 = text(\"Hello \");\n t2 = text(name);\n t3 = text(\"!\");\n add_location(h1, file, 6, 0, 56);\n}\n// more code\n```\n\n```js\n$: console.log(name);\n```\n\n```js\n$: value, console.log('value has been updated');\n```\n\n```text\n{@debug}\n```\n\n```text\nconsole.log\n```\n\n```text\ndevtools\n```\n\n```text\n@debug\n```\n\n```text\ndevtools\n```\n\n```text\ndebugger\n```\n\n```text\n<script>\n let name = 'world';\n\n setTimeout(() => {\n name = 'moon';\n }, 3000)\n</script>\n\n{@debug name}\n<h1>Hello {name}!</h1>\n```\n\n```text\n{@debug}\n```\n\n========================================\n\nComments:\n- Make sure you're compiling with `dev: true`, otherwise `{@debug ...}` tags will be stripped out\n- If you mean `dev: true` in rollup.config.js -> plugins -> svelte() ... it doesn't work. But I found a way ... just `npm run dev` and then immediately stop the live reload server\n- `dev: true` works if you also prevent the terser() plugin from running\n- use svelte-watch, it allows monitoring components state using redux devtools\n- No, it won't ... that's what I did and what I thought, but it just won't stop there\n- What's your browser? Because it's working fine in Chrome and Firefox\n- I have Google Chrome 75.0.3770.142 ... see my code in my latest edit\n- I'm using Chrome, go to a new tab, open your devtools, go to this link using your own code. Because the debugger is pausing execution for me.\n- Confirmed ... so why is it not doing it in my setup? The code compiles just fine (no errors, no warnings) and runs perfectly. But @debug doesn't trigger\n- Any chance you would be using some kind of SSR ? Maybe try to check in your compiled file if you can find `debugger` or not.\n- No SSR involved here ... but the minified bundle.js does NOT contain a debugger statement. That might of course be the cause of my problem. Maybe it is because I used `npm run build` to build it?\n- Yeah the debug statements are probably not included in the build version. Leaving console.logs in a production apps is often frowned upon, so it makes sense that the svelte compiler is scrapping them.\n- So then I'm lost ... the dev build won't run smoothly with my Node/Express setup (especially the socket.io part is doing all kinds of weird things). Can I maybe do a `npm run dev` without running a live server? I would just need the dev build ....\n- If you want a Node/Express setup running svelte, you should take a look at sapper. Otherwise yeah, you should be able to run a dev build w/o a live server\n- Oh never mind, it also triggers the first time the page renders. If that doesn't work for you, please provide more details on your browser, version and ideally an example of your code.","metadata":{"transformedAt":"2026-08-18T18:33:40.655Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":290,"estimatedTokens":1668}}29{"id":"stack-72379987","source":"stackoverflow","questionId":72379987,"title":"What is the correct way for updating a Svelte writable array store?","tags":["svelte","svelte-store"],"text":"Title: What is the correct way for updating a Svelte writable array store?\nTags: svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\nWhat is the correct way (or differences if both are correct) for updating a `$orderItems = writable([])` Svelte writable array store? We'll assume `result` is a new item I want to push at the end of `$orderItems`.\n\n```\norderItems.update(items => ([...items, result]))\n```\n\nor\n\n```\n$orderItems = [...$orderItems, result]\n```\n\n========================================\n\nTop Answer:\nEven easier (with just one assignment):\n\n```\n$orderItems[$orderItems.length] = result\n```\n\n========================================\n\nCode:\n```html\norderItems.update(items => ([...items, result]))\n```\n\n```html\n$orderItems = [...$orderItems, result]\n```\n\n```text\n$orderItems = writable([])\n```\n\n```text\nresult\n```\n\n```text\n$orderItems\n```\n\n```text\n$orderItems.push(result)\n$orderItems = $orderItems\n```\n\n```text\norderItems.update(items => {\n items.push(result)\n return items\n})\n```\n\n```text\n$\n```\n\n```text\n.svelte\n```\n\n```text\n.js\n```\n\n```text\n.set() / .update()\n```\n\n```text\n$orderItems[$orderItems.length] = result\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.655Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":80,"estimatedTokens":285}}30{"id":"stack-73531618","source":"stackoverflow","questionId":73531618,"title":"Svelte components with generics","tags":["typescript","svelte","typescript-generics","sveltekit","svelte-3"],"text":"Title: Svelte components with generics\nTags: typescript, svelte, typescript-generics, sveltekit, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI want to use a generic type in a Svelte(Kit) component's props, and I found out there is this `type T = $$Generic` thing:\n\n```\n\n import type { Writable } from \"svelte/store\";\n type T = $$Generic;\n export let store: Writable;\n\n```\n\nWhile that is great, I do need slightly more information than that: I require that the `T` has a property `id`. Normally I'd do something like this:\n\n```\nexport type WithId = { id: number };\nfunction foo(property: T) { ... }\n```\n\nHow can I do something similar for Svelte component props?\n\n========================================\n\nTop Answer:\nThe answer by @brunnerh is already very good. But in order to have no eslint errors, the generic type `T` needs to be defined in typescript and not only the `generics` attribute of the ``. This will hopefully change in the future.\n\n```\n\n type T = { id: number };\n\n import type { Writable } from \"svelte/store\";\n export let store: Writable;\n\n```\n\n========================================\n\nCode:\n```html\n<script lang=\"ts\">\n import type { Writable } from \"svelte/store\";\n type T = $$Generic;\n export let store: Writable<T[]>;\n</script>\n```\n\n```js\nexport type WithId = { id: number };\nfunction foo<T extends WithId>(property: T) { ... }\n```\n\n```text\ntype T = $$Generic\n```\n\n```text\nT\n```\n\n```text\nid\n```\n\n```html\n<script lang=\"ts\" generics=\"T extends { id: number }\">\n```\n\n```js\ntype T = $$Generic<{ id: number }>;\n```\n\n```html\n<script lang=\"ts\" context=\"module\">\n interface WithId { id: number }\n</script>\n<script lang=\"ts\">\n export let store: Writable<T[]>;\n\n type T = $$Generic<WithId>;\n</script>\n```\n\n```text\nextends\n```\n\n```text\ntype\n```\n\n```text\ninterface\n```\n\n```html\n<script lang=\"ts\" context=\"module\">\n type T = { id: number };\n</script>\n\n<script lang=\"ts\" generics=\"T extends { id: number }\">\n import type { Writable } from \"svelte/store\";\n export let store: Writable<T[]>;\n</script>\n```\n\n```text\nT\n```\n\n```text\ngenerics\n```\n\n```text\n<script>\n```\n\n========================================\n\nComments:\n- this is pretty useful information. I could not find anything on svelte docs but it works. Should I open an issue for that?\n- @sryscad It's still not completely finalized, see this\n- This isn't such an old question, so I'll try to answer a question: after defining `generics=\"T\"`, how do I enter a value for it when calling the component?\n- @Lucas: It's derived from usage. E.g. if you have `export let value: T`, the `T` will be whatever you put in when specifying ``.","metadata":{"transformedAt":"2026-08-18T18:33:40.655Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":127,"estimatedTokens":652}}31{"id":"stack-57407177","source":"stackoverflow","questionId":57407177,"title":"Can I move JS code out of Svelte component file to other file js file?","tags":["javascript","svelte"],"text":"Title: Can I move JS code out of Svelte component file to other file js file?\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI am currently exploring Bucklescript/ReasonML with Svelte 3 for my next project. Typical Svelte component is a `.svelte` file:\n\n```\n\n let name = 'world';\n\n### Hello world!\n\n```\n\n**Instead, can I have `script` tag with `src` or equivalent to keep JS code in a separate file?**\n\n```\n\n```\n\nBy moving the `js` code to a separate file, the target of the Bucklescript compiler (which is a JS file) could be used for the component.\n\nVue.js already supports this with their SFC `.vue` file.\n\n On a side note: I could use Vue.js for this but the presence Virtual DOM is problematic for legacy codebase. And, **Svelte** is diminishing at runtime and thus very much desirable. Also, the use `this` in Vue makes things awkward in Ocaml/Reason.\n\n========================================\n\nTop Answer:\nAs far as I know, this isn't possible right now.\n\nWhat you could do is export everything you need from the js file, and then import them in the component: https://svelte.dev/repl/1d630ff27a0c48d38e4762cf6b0c2da5?version=3.7.1\n\n```\n\n import { name } from './mycode.js'\n\n### Hello {name}!\n\n```\n\n```\nexport let name = 'World';\n```\n\nHowever that would only be a partial solution as any mutation of data occurring within the file would not trigger a re-render of the DOM, as Svelte would not compile the .js file and would not be able to add its own code invalidating the values: https://svelte.dev/repl/c4b41b769ed747acb01a02a9af33e545?version=3.7.1\n\n```\n\n import { name, handleClick } from './mycode.js'\n\n### Hello {name}!\n\n```\n\n```\nexport let name = 'World';\nexport const handleClick = () => {\n name = 'Everyone';\n}\n```\n\nBut that doesn't mean you can't be tricky if you are willing to go the extra mile to achieve this: https://svelte.dev/repl/8e259df629614ac99cb14cfae2f30658?version=3.7.1\n\n```\n\n import { name, handleClick } from './mycode.js'\n\n const onClick = () => {\n handleClick();\n name = name;\n }\n\n### Hello {name}!\n\n```\n\n```\nexport let name = 'World';\nexport const handleClick = () => {\n name = 'Everyone';\n}\n```\n\nThe extra line `name = name` forcing the DOM update.\n\n========================================\n\nCode:\n```text\n<script>\n let name = 'world';\n</script>\n\n<h1>Hello world!</h1>\n```\n\n```text\n<script src='./some-file.js'></script>\n```\n\n```text\n.svelte\n```\n\n```text\nscript\n```\n\n```text\nsrc\n```\n\n```text\njs\n```\n\n```text\n.vue\n```\n\n```text\nthis\n```\n\n```js\nconst path = require( 'path' )\nconst fs = require( 'fs' )\n...\n\nplugins: [\n svelte({\n // ...\n preprocess: {\n script: ({ content, attributes, filename }) => {\n if ( 'string' === typeof attributes.src ) {\n const file = path.resolve(path.dirname(filename), attributes.src);\n const code = fs.readFileSync(file, 'utf-8');\n return {code, dependencies: [file]};\n }\n }\n }\n })\n]\n```\n\n```text\npreprocess\n```\n\n```html\n<script>\n import { name } from './mycode.js'\n</script>\n\n<h1>Hello {name}!</h1>\n```\n\n```text\nexport let name = 'World';\n```\n\n```html\n<script>\n import { name, handleClick } from './mycode.js'\n</script>\n\n<h1 on:click={handleClick}>Hello {name}!</h1>\n```\n\n```text\nexport let name = 'World';\nexport const handleClick = () => {\n name = 'Everyone';\n}\n```\n\n```html\n<script>\n import { name, handleClick } from './mycode.js'\n\n const onClick = () => {\n handleClick();\n name = name;\n }\n</script>\n\n<h1 on:click={onClick}>Hello {name}!</h1>\n```\n\n```text\nexport let name = 'World';\nexport const handleClick = () => {\n name = 'Everyone';\n}\n```\n\n```text\nname = name\n```\n\n========================================\n\nComments:\n- That will work but it is too much boilerplate. It goes against the principles of Svelte. Looks like I will have to rest it.\n- At this point, it seems the code is only preprocessed once per `npm run dev`. I've created some edits that I think fix and improve (adding a watch dependency) this sample. Thanks @Rich-Harris!","metadata":{"transformedAt":"2026-08-18T18:33:40.655Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":207,"estimatedTokens":1001}}32{"id":"stack-62841384","source":"stackoverflow","questionId":62841384,"title":"svelte: how can a component modify a variable/object on its parent?","tags":["svelte","svelte-3","svelte-component"],"text":"Title: svelte: how can a component modify a variable/object on its parent?\nTags: svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI have a main application that contains the user object and the login component\n\n```\n\nlet user = {}\n\nhello {user.username}\n\n```\n\nIn the login component, I make a call to ajax and receive some data like:\n\n```\nuser = {id:1, username:\"john\"}\n```\n\nHow can I then \"inform\" the main application I have updated the user so it displays hello john\n\nFor now, I dispatch an event\n\n```\nimport { createEventDispatcher } from 'svelte';\nconst dispatch = createEventDispatcher();\n```\n\nIs there a better way to achieve that ?\n\n========================================\n\nTop Answer:\nSvelte has 2-way binding via the `bind` keyword. You may have seen it when binding form inputs, and it works the same way in your own parent-child relationships.\n\nHere's how it looks: `` or the shorthand when the names are the same: ``.\n\nAll you have to do is define a prop in the child (Login) component and when you update it, the parent value changes.\n\nHere is a REPL to see it in action\n\nSome extra things I'll point out in case you're interested:\n\n- Components usually start with a capital letter. This allows the compiler to differentiate them with regular HTML components. Who knows, someday there may be an HTML component named ``! 😅\n\n- While the strategy above works for user logins, the typical way to handle this is using the concept of stores.\n\n========================================\n\nCode:\n```text\n<script>\nlet user = {}\n</script>\n\nhello {user.username}\n<login user={user} />\n```\n\n```text\nuser = {id:1, username:\"john\"}\n```\n\n```text\nimport { createEventDispatcher } from 'svelte';\nconst dispatch = createEventDispatcher();\n```\n\n```text\n<login user={user} />\n```\n\n```text\n<login bind:user={user} />\n```\n\n```text\nbind\n```\n\n```text\n<Login bind:user={user} />\n```\n\n```text\n<Login bind:user />\n```\n\n```text\n<login>\n```\n\n========================================\n\nComments:\n- Why not create a login svelte store to observe and the login state.\n- And which one do you think is the \"cleanest\"?\n- I would implement a storage solution. Thinking on OIDC token flow or session related information this might be useful?\n- If there is no need, dispatching is fine for me. Mentioning that two-way-binding is good for frequently changing values, the login process is used only once per session.\n- otherwise: less code is always better! -> two-way-binding??? It depends;) best","metadata":{"transformedAt":"2026-08-18T18:33:40.655Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":102,"estimatedTokens":622}}33{"id":"stack-63934543","source":"stackoverflow","questionId":63934543,"title":"Svelte reactivity not triggering when variable changed in a function","tags":["javascript","svelte","svelte-3"],"text":"Title: Svelte reactivity not triggering when variable changed in a function\nTags: javascript, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI am a bit confused here and unluckily I couldn't get any solution on the discord channel of svelte so here I go...\n\nI have a rather basic example of two classes, let them be `App` and `Comp`.\n`App` creates a `Comp` instance and then updates this instance's `value` after a button click.\n\nThe Comp instance should set this value to a different variable (`inputValue`) and upon changing that variable it should fire `validate(inputValue)` which is reactive. Here is a REPL: https://svelte.dev/repl/1df2eb0e67b240e9b1449e52fb26eb14?version=3.25.1\n\nApp.svelte:\n\n```\n\n import Comp from './Comp.svelte';\n \n let value = 'now: ' + Date.now();\n \n function clickHandler(e) {\n value = 'now ' + Date.now();\n }\n\nchange value\n```\n\nComp.svelte:\n\n```\n\n import { onMount } from 'svelte';\n\n export let value;\n\n let rendered = false;\n let inputValue = '';\n\n $: validate(inputValue); // This doesn't execute. Why?\n\n function validate(val) {\n console.log('validation:', val); \n }\n\n onMount(() => {\n rendered = true;\n });\n\n $: if (rendered) {\n updateInputValue(value);\n }\n\n function updateInputValue(val) {\n console.log('updateInputValue called!');\n if (!value) {\n inputValue = '';\n }\n else {\n inputValue = value;\n }\n }\n\n```\n\nSo as soon as the value is changed:\n\n- The reactive `if (rendered) {...}` condition is called\n\n- `updateInputValue` is called and `inputValue` is changed. HTML input element is updated to this value.\n\n- `validate(inputValue)` never reacts to this change - **WHY?**\n\nIf I omit the extra call to the `updateInputValue` function in the reactive `if (rendered)` condition and put `updateInputValue` function body's code directly to the condition, then `validate(inputValue)` is triggered correctly, i.e.:\n\n```\n// works like this \n$: if (rendered) {\n if (!value) {\n inputValue = '';\n }\n else {\n inputValue = value;\n }\n}\n```\n\nSo how come it doesn't work when updated in the function?\n\n========================================\n\nTop Answer:\nReally strange (and I couldn't really explain it) but if you put the reactive statement `$: validate(inputValue);` after the function `updateInputValue` declaration, it's working as expected:\n\n```\n\n import { onMount } from 'svelte';\n \n export let value;\n \n let rendered = false;\n let inputValue = '';\n\n function validate(val) {\n console.log('validation:', val);\n }\n \n onMount(() => {\n rendered = true;\n });\n \n $: if (rendered) {\n updateInputValue(value);\n }\n \n function updateInputValue(val) {\n console.log('updateInputValue called!');\n if (!value) {\n inputValue = '';\n }\n else {\n inputValue = value;\n }\n }\n \n $: validate(inputValue);\n\n```\n\nCheck this REPL.\n\n========================================\n\nCode:\n```text\n<script>\n import Comp from './Comp.svelte';\n \n let value = 'now: ' + Date.now();\n \n function clickHandler(e) {\n value = 'now ' + Date.now();\n }\n</script>\n\n<Comp\n bind:value={value}\n/>\n<button type=\"button\" on:click={clickHandler}>change value</button>\n```\n\n```text\n<script>\n import { onMount } from 'svelte';\n\n export let value;\n\n let rendered = false;\n let inputValue = '';\n\n $: validate(inputValue); // This doesn't execute. Why?\n\n function validate(val) {\n console.log('validation:', val); \n }\n\n onMount(() => {\n rendered = true;\n });\n\n $: if (rendered) {\n updateInputValue(value);\n }\n\n function updateInputValue(val) {\n console.log('updateInputValue called!');\n if (!value) {\n inputValue = '';\n }\n else {\n inputValue = value;\n }\n }\n</script>\n\n<input type=\"text\" bind:value={inputValue}>\n```\n\n```text\n// works like this \n$: if (rendered) {\n if (!value) {\n inputValue = '';\n }\n else {\n inputValue = value;\n }\n}\n```\n\n```text\nApp\n```\n\n```text\nComp\n```\n\n```text\nApp\n```\n\n```text\nComp\n```\n\n```text\nvalue\n```\n\n```text\ninputValue\n```\n\n```text\nvalidate(inputValue)\n```\n\n```text\nif (rendered) {...}\n```\n\n```text\nupdateInputValue\n```\n\n```text\ninputValue\n```\n\n```text\nvalidate(inputValue)\n```\n\n```text\nupdateInputValue\n```\n\n```text\nif (rendered)\n```\n\n```text\nupdateInputValue\n```\n\n```text\nvalidate(inputValue)\n```\n\n```js\nlet count = 0;\n$: double = count * 2;\n$: quadruple = double * 2;\n```\n\n```js\n$: validate(inputValue);\n$: if (rendered) updateInputValue(value);\n```\n\n```js\n$: if (rendered) {\n updateInputValue(value);\n}\n$: validate(inputValue);\n```\n\n```js\n$: validate(inputValue);\n\n$: if (rendered) {\n inputValue = updateInputValue(value);\n}\n \nfunction updateInputValue(val) {\n console.log('updateInputValue called!');\n if (!value) {\n return '';\n }\n else {\n return value;\n }\n}\n```\n\n```text\nquadruple\n```\n\n```text\ndouble\n```\n\n```text\n$: double = count * 2;\n```\n\n```text\n$: quadruple = double * 2\n```\n\n```text\nvalidate\n```\n\n```text\ninputValue\n```\n\n```text\nrendered\n```\n\n```text\nupdateInputValue\n```\n\n```text\nvalue\n```\n\n```text\ninputValue\n```\n\n```text\nrendered\n```\n\n```text\nvalue\n```\n\n```text\nvalidate(inputValue);\n```\n\n```text\nif (rendered) updateInputValue(value);\n```\n\n```text\nrendered\n```\n\n```text\nvalue\n```\n\n```text\nvalidate(inputValue)\n```\n\n```text\ninputValue\n```\n\n```text\nif (rendered) updateInputValue(value)\n```\n\n```text\nupdateInputValue\n```\n\n```text\ninputValue\n```\n\n```html\n<script>\n import { onMount } from 'svelte';\n \n export let value;\n \n let rendered = false;\n let inputValue = '';\n\n function validate(val) {\n console.log('validation:', val);\n }\n \n onMount(() => {\n rendered = true;\n });\n \n $: if (rendered) {\n updateInputValue(value);\n }\n \n function updateInputValue(val) {\n console.log('updateInputValue called!');\n if (!value) {\n inputValue = '';\n }\n else {\n inputValue = value;\n }\n }\n \n $: validate(inputValue);\n</script>\n```\n\n```text\n$: validate(inputValue);\n```\n\n```text\nupdateInputValue\n```\n\n```text\n<script>\n let nb\n let n=0\n$: console.log(\"nb1:\",nb)\n$: update(n)\n$: console.log(\"nb2:\",nb)\nfunction update(v) {\n console.log(\"update\",v)\n nb = v\n}\n</script>\n<h1 on:click={()=>n=Math.floor(Math.random()*100)}>click: {nb}</h1>\n<h1 on:click={()=>update(Math.floor(Math.random()*100))}>click: {nb}</h1>\n```\n\n```text\n<script>\n let nb\n let n=0\n $: console.log(\"nb1:\",nb)\n $: nb = update(n)\n $: console.log(\"nb2:\",nb)\n function update(v) {\n console.log(\"update\",v)\n return v\n }\n </script>\n <h1 on:click={()=>n=Math.floor(Math.random()*100)}>click: {nb}</h1>\n <h1 on:click={()=>update(Math.floor(Math.random()*100))}>click: {nb}</h1>\n```\n\n```text\nnb\n```\n\n```text\nn\n```\n\n```text\n$: update(n)\n```\n\n```text\nnb\n```\n\n```text\nnb\n```\n\n```text\nupdate\n```\n\n```text\nh1\n```\n\n```text\nnb\n```\n\n========================================\n\nComments:\n- Notice that it's working if you write something in the input manually (without clicking the button).\n- @johannchopin That I find logical & correct because of the direct binding to `inputValue`, i.e. it excludes calling the reactive `if` statement and thus `updateInputValue` function. But I need to be able to update the value from outside of the component => changing the `value` prop.\n- That's an excellent catch, I didn't think of that. Thanks! This looks like a bug to me... Please take an upvote meanwhile.\n- @Fygo Yeah it's really curious could you open an issue on the repo?\n- If you look at compiled js, you will notice that reactivity is obtained via marking a variable ’dirty’. If you have the `validate()`-function call before assigning a value to `inputValue` variable, then `inputValue` is not dirty and therefore `validate()` is not called. (To notify also @johannchopin)\n- Problem seems to be that the assignment to `inputValue` doesn’t mark it dirty and this happens if the `inputValue` assignment is in subfunction. This works fine `$: if (rendered) { inputValue=updateInputValue(value); }` and this also works `$: if (rendered) { inputValue=’’;updateInputValue(value);}` In first version you must of course return the correct value from function. I believe this is a bug.\n- Yeah you're right but since I didn't read something about it in the official documentation it could be helpful to open an issue for that. Have you the time for it @grohjy?\n- @johannchopin I created a semi-report/semi-question yesterday about this, which got closed unluckily, but I guess it could be reopened. If you are interested, here is the link: github.com/sveltejs/svelte/issues/5408\n- Updated blog post link","metadata":{"transformedAt":"2026-08-18T18:33:40.655Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":56,"totalLines":498,"estimatedTokens":2158}}34{"id":"stack-46104897","source":"stackoverflow","questionId":46104897,"title":"How to debounce / throttle with Svelte?","tags":["javascript","svelte"],"text":"Title: How to debounce / throttle with Svelte?\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nSo i currently have:\n\n**App.html**\n\n```\n\n \n\n import { debounce } from 'lodash'\n\n export default {\n data () {\n name: ''\n },\n\n methods: {\n debounce,\n async handleInput (event) {\n this.set({ name: await apiCall(event.target.value).response.name })\n }\n }\n }\n\n```\n\nAnd get the error `Uncaught TypeError: Expected a function at App.debounce`. This comes from Lodash so it doesn't seem like the method from Svelte is being passed through.\n\n**Extra extra edit**\n\nExtra context for how i'm currently achieving it:\n\n```\noncreate () {\n const debounceFnc = this.handleInput.bind(this)\n\n this.refs.search.addEventListener('input', debounce(debounceFnc, 300))\n}\n```\n\n========================================\n\nTop Answer:\n```\n\n let val = $state('');\n\n function debounce(cb, t) {\n let timer;\n return (...args) => {\n clearTimeout(timer);\n timer = setTimeout(() => cb(...args), t);\n }\n }\n\n val = event.target.value, 600 )} />\n{val}\n```\n\nSvelte 5 Playground\n\n========================================\n\nCode:\n```text\n<div>\n <input on:input=\"debounce(handleInput, 300)\">\n</div>\n\n<script>\n import { debounce } from 'lodash'\n\n export default {\n data () {\n name: ''\n },\n\n methods: {\n debounce,\n async handleInput (event) {\n this.set({ name: await apiCall(event.target.value).response.name })\n }\n }\n }\n</script>\n```\n\n```text\noncreate () {\n const debounceFnc = this.handleInput.bind(this)\n\n this.refs.search.addEventListener('input', debounce(debounceFnc, 300))\n}\n```\n\n```text\nUncaught TypeError: Expected a function at App.debounce\n```\n\n```html\n<input on:input={handleInput}>\n\n<script>\n import debounce from 'lodash/debounce'\n\n let name = '';\n \n const handleInput = debounce(e => {\n name = e.target.value;\n }, 300)\n</script>\n```\n\n```html\n<div>\n <input on:input=\"handleInput(event)\">\n</div>\n\n<script>\n import { debounce } from 'lodash'\n\n export default {\n data () {\n return { name: '' };\n },\n\n methods: {\n handleInput: debounce (async function (event) {\n this.set({ name: await apiCall(event.target.value).response.name })\n }, 300)\n }\n }\n</script>\n```\n\n```text\ndebounce\n```\n\n```text\nhandleInput\n```\n\n```text\n<input placeholder='edit me' bind:this={input}>\n<p>name: {name}</p>\n\n<script>\n import { onMount } from \"svelte\"\n import { debounce } from 'lodash-es'\n var name=\"\", input;\n onMount(()=>{\n input.addEventListener('input', debounce((e)=>{name=e.target.value}, 250))\n })\n</script>\n```\n\n```text\n<script>\n let val = $state('');\n\n function debounce(cb, t) {\n let timer;\n return (...args) => {\n clearTimeout(timer);\n timer = setTimeout(() => cb(...args), t);\n }\n }\n</script>\n\n<input oninput={debounce( (event) => val = event.target.value, 600 )} />\n{val}\n```\n\n========================================\n\nComments:\n- Can you elaborate on what you're trying to do? You wouldn't typically have a `debounce` method on a component — instead, one of your methods would *be* debounced\n- @RichHarris sorry Rich my example seemed to have missed the template part i added. Added a bit more context to show what i'm trying to achieve too.\n- Try using `import debounce from 'lodash/debounce'`\n- Same error @OluwafemiSule. I further edited with extra context to show how i'm currently achieving this. I just wondered if i could do it in the template the \"Svelte\" way.\n- `debounce` is a method defined on the component so it should be used as `this.debounce(debounceFnc, 300)`\n- I've tried both `debounce` and `this.debounce`. I registered it on the component to see if it would with on this `on:input` as i couldn't use it straight up without declaring in in `methods: {}` i also tried `helpers: {}` and that doesn't work either.\n- Had no idea you could import from lodash in the REPL. Thanks, Rich!\n- Is there an updated example of how to do this in Svelte 3? I'm struggling since the syntax has changed so drastically\n- @TheHanna i assume you've worked it out but I've updated the answer. cheers Rich for all the work you've done.\n- Typing seems like a pain. Cannot assign type 'Function' to type 'UIEventHandler'. Any fixes? (Using JSDoc for typing)\n- you should not have to use a ref for this use the on:input directive :)","metadata":{"transformedAt":"2026-08-18T18:33:40.655Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":192,"estimatedTokens":1090}}35{"id":"stack-62126621","source":"stackoverflow","questionId":62126621,"title":"How to call destroy on a component from inside the component?","tags":["svelte","svelte-component"],"text":"Title: How to call destroy on a component from inside the component?\nTags: svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI have a modal component and I want to be able to destroy it when the user clicks on the x button, I also have a notification popup that destroys itself after an interval but I'd like to give the user the ability to close it with the x button too.\nI know I can pass an event to the component but I think it'll be better if the component is self destructive.\nAlso there might be a better design for such case but that's the way I thought about it, other pointers will be appreciated.\n\n========================================\n\nTop Answer:\n[Update 2023]\nAlso `component.$destroy()` can be used as shown here in this link (which triggers the onDestroy events):\n\nhttps://svelte.dev/docs#run-time-client-side-component-api-$destroy\n\nAnd if you want to get the reference to any component within itself you can import the `get_current_component()` function from `svelte/internal` and do:\n\n```\nimport {get_current_component} from 'svelte/internal'\nconst THISComponent = get_current_component()\n\nfunction destroySelf(){\n THISComponent.$destroy();\n}\n```\n\nDon't forget you can use the `get_current_component()` only in the component initilization meaning it has to be on top level of a component (not in any functions or other declerations)\n\n========================================\n\nCode:\n```js\n<script>\n let nodeRef\n</script>\n\n<div bind:this={nodeRef}>\n <h3>Hey I'm a component</h3>\n <button on:click={() => nodeRef.parentNode.removeChild(nodeRef)}>\n Remove me :(\n </button>\n</div>\n```\n\n```js\n<script>\n import MyModal from './MyModal.svelte'\n\n let showModal = false\n</script>\n\n<div>\n {#if showModal}\n <MyModal onClose={() => showModal = false} />\n {/if}\n <button on:click={() => showModal = true}>Show Modal</button>\n</div>\n```\n\n```js\n<script>\n export let onClose\n</script>\n\n<div>\n <h3>Hi I'm a modal <span on:click={onClose}>X</span></h3>\n</div>\n```\n\n```text\nbind:this\n```\n\n```text\nNode.removeChild()\n```\n\n```js\nimport {get_current_component} from 'svelte/internal'\nconst THISComponent = get_current_component()\n\nfunction destroySelf(){\n THISComponent.$destroy();\n}\n```\n\n```text\ncomponent.$destroy()\n```\n\n```text\nget_current_component()\n```\n\n```text\nsvelte/internal\n```\n\n```text\nget_current_component()\n```\n\n```text\nsomeChildReference.getRootNode().host\n```\n\n```text\n<svelte:options customElement=\"afkar-sv-modal\" />\n\n<script lang=\"typescript\">\n\n let dialog; // HTMLDialogElement\n\n $: if (dialog) dialog.showModal();\n</script> \n\n<!-- svelte-ignore a11y-click-events-have-key-events a11y-no-noninteractive-element-interactions -->\n\n<dialog\n bind:this={dialog}\n on:click|self={() => \n {\n dialog.close();\n dialog.getRootNode().host.remove();\n }}\n>\n <!-- svelte-ignore a11y-no-static-element-interactions -->\n <div on:click|stopPropagation>\n <slot name=\"header\" />\n <hr />\n <slot />\n <hr />\n <!-- svelte-ignore a11y-autofocus -->\n </div>\n</dialog>\n\n<style>\n dialog {\n max-width: 64em;\n border-radius: 0.2em;\n border: none;\n padding: 0;\n }\n dialog::backdrop {\n background: rgba(0, 0, 0, 0.3);\n }\n dialog > div {\n padding: 1em;\n }\n dialog[open] {\n animation: zoom 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);\n }\n @keyframes zoom {\n from {\n transform: scale(0.95);\n }\n to {\n transform: scale(1);\n }\n }\n dialog[open]::backdrop {\n animation: fade 0.2s ease-out;\n }\n @keyframes fade {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n }\n button {\n display: block;\n }\n</style>\n```\n\n```text\n<script>\n export let thisRef;\n onCloseClicked = ()=>thisRef.remove();\n</script>\n...\n```\n\n```text\n// I assume you have the Modale.svelet defined and imported, and this is the caller of Modal\n<script>\n let modal;\n</script>\n<Modal bind:this={modal} thisRef={modal} />\n```\n\n========================================\n\nComments:\n- to illustrate more, something like this.destroy() maybe?\n- Thank you, I was using the 2nd approach but felt there might be a better one, happy to know that I haven't went far off with my thinking.\n- Note that if your modal/notification component is not a direct child of the parent handling the display/dismissal logic, it might be worth using a store to hold the `showModal` or `showNotification` boolean so that you don't have to pass down a close handler through several layers of nested components.\n- gotcha! of course will keep that in mind, I'll just try to put myself in a position where I won't have to use stores for UI, only data :)\n- I hear you, and I generally agree, but it's not always possible (or desirable) to keep these components as direct children, and frankly, in these situations, having a single store dedicated to tracking UI state is a very simple and efficient solution. Good luck with your dev! :)\n- I'm suspicious of this because onDestroy isn't called. Please see your updated Demo 1 REPL console logs svelte.dev/repl/49dc7605f26c4b32939d1223317158b2?version=3.2‌​3.0\n- Suspicious as in I think this leaks memory (until garbage collected).\n- @n-smits that `onDestroy` isn't called is not surprising as we're manipulating the DOM directly instead of delegating to Svelte to trigger a re-render (and thus benefit from life cycle hooks, among them `onDestroy`) as is the case in the 2nd approach (which is the favored one if you read through my answer, notably because it is cleaner, as in I'm expecting Svelte-generated code to do a better job handling object destruction and garbage collection).\n- I've read it, but it isn't what I'm looking for (removing the component from within itself, at least without massive complication). I've read somewhere on github from Harris (creator of Svelte) there is no way to do it, but haven't looked deeper into this yet.\n- I wonder why they chose the snake case for internal functions in a JS/TS context.\n- Throws an error in new versions of Svelte :/ github.com/sveltejs/svelte/issues/9189\n- @FranciscoGomes twitter.com/Rich_Harris/status/1620183347740950528\n- @codingexplorer hahaha nice. Not scientific, but nice\n- In 2024, this actually works best in my opinion--since 'removeChild' seems to not do much.","metadata":{"transformedAt":"2026-08-18T18:33:40.655Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":212,"estimatedTokens":1606}}36{"id":"stack-57813243","source":"stackoverflow","questionId":57813243,"title":"How do I make a component that is aware of the current url in Sapper with Svelte?","tags":["svelte","sapper"],"text":"Title: How do I make a component that is aware of the current url in Sapper with Svelte?\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI have a page that has a nav bar with a \"Quarters\" link. Under the Quarters link, when the user is on the `/quarters` route, a list of quarters will be shown, like 2019Q2 etc. The url will be `/quarters/2019q2`. \n\nI want to make a component that show shows a hyperlink that will have the `selected` class if the current url matches the href of the link. Here's the closest I can get: \n\n```\n\n import { afterUpdate } from 'svelte';\n export let segment;\n export let text = 'text here';\n export let link;\n let isCurrentPath = false;\n console.log(segment, link, text);\n afterUpdate(() => {\n if (window.location.pathname.includes(link)) {\n isCurrentPath = true;\n debugger;\n }\n console.log('HL afterUpdate ', window.location);\n });\n\n /* omitted */\n\n{text}\n```\n\nThat works fine for the first load, but when the user navigates to a different data page the selection is not updated. How do I get some code to only run on the client-side? If I access the `window` object outside of `afterUpdate` I will get an null ref error from the server-side code.\n\nETA: Tried this too: \n\n```\nlet isCurrentPath = false;\n let path = typeof window === 'undefined' ? '' : window.location.pathname;\n $: if (path) isCurrentPath = window.location.pathname.includes(link);\n```\n\nThat code doesn't fire when the user clicks one of the data links. Tried `onMount` as well with no positive result.\n\n========================================\n\nTop Answer:\nFor people using SvelteKit, the given answers still apply. Take a look at the docs for the page store: https://svelte.dev/docs/kit/$app-stores#page\n\nEDIT: There were breaking changes in a new SvelteKit update. You still access the current url from the page store like this:\n\n```\n\n import { page } from '$app/stores';\n\n### {$page.url.pathname}\n\n```\n\nEDIT 2: `$app/stores` is deprecated since SvelteKit 2.12 (Svelte 5) and subject to be removed in SvelteKit 3, use `$app/state` instead:\n\n```\n\n import { page } from '$app/state'; // replace $app/stores with $app/state\n let longTitle = $derived(page.url.pathname.length > 20 ? true : false); // remove $ from $page\n\n```\n\n========================================\n\nCode:\n```text\n<script>\n import { afterUpdate } from 'svelte';\n export let segment;\n export let text = 'text here';\n export let link;\n let isCurrentPath = false;\n console.log(segment, link, text);\n afterUpdate(() => {\n if (window.location.pathname.includes(link)) {\n isCurrentPath = true;\n debugger;\n }\n console.log('HL afterUpdate ', window.location);\n });\n</script>\n\n<style>\n /* omitted */\n</style>\n\n<a class:selected={segment && isCurrentPath} href={link}>{text}</a>\n```\n\n```text\nlet isCurrentPath = false;\n let path = typeof window === 'undefined' ? '' : window.location.pathname;\n $: if (path) isCurrentPath = window.location.pathname.includes(link);\n```\n\n```text\n/quarters\n```\n\n```text\n/quarters/2019q2\n```\n\n```text\nselected\n```\n\n```text\nwindow\n```\n\n```text\nafterUpdate\n```\n\n```text\nonMount\n```\n\n```text\n<!--\nThis is used to have a link on the page that will show highlighted if the url meets the criteria.\nYou might want to adjust the logic on line 19.\nusage: \n<HighlightedLink bind:segment highlight=\"faq\" rel=\"prefetch\" link=\"/faq\" text=\"FAQ\" />\n--> \n\n<script>\n import { stores } from '@sapper/app';\n const { page } = stores();\n export let highlight;\n export let segment;\n export let text = 'text here';\n export let link;\n export let target;\n let highlightPath = false;\n $: highlightPath =\n $page.path && highlight && ($page.path.includes(highlight) || $page.path.includes(link));\n</script>\n\n<style>\n .selected {\n position: relative;\n display: inline-block;\n }\n .selected::after {\n position: absolute;\n content: '';\n width: calc(100% - 1em);\n height: 2px;\n background-color: rgb(255, 62, 0);\n display: block;\n bottom: -1px;\n }\n a {\n padding-left: 10px;\n }\n</style>\n\n\n<a class:selected={highlightPath} href={link}>{text}</a>\n```\n\n```text\nafterUpdate\n```\n\n```text\nonMount\n```\n\n```text\nisCurrentPath\n```\n\n```html\n<script>\n import { page } from '$app/stores';\n</script>\n\n<h1>{$page.url.pathname}</h1>\n```\n\n```html\n<script>\n import { page } from '$app/state'; // replace $app/stores with $app/state\n let longTitle = $derived(page.url.pathname.length > 20 ? true : false); // remove $ from $page\n</script>\n```\n\n```text\n$app/stores\n```\n\n```text\n$app/state\n```\n\n========================================\n\nComments:\n- can you provide example? the docs are useless.\n- @chovy Actually I think they're pretty good. But here you go: Import the store this way: `import { page } from '$app/stores';` and then use it like this: `{#if $page.path == '/some/route'}`","metadata":{"transformedAt":"2026-08-18T18:33:40.655Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":207,"estimatedTokens":1205}}37{"id":"stack-67663671","source":"stackoverflow","questionId":67663671,"title":"Understanding Context in Svelte (convert from React Context)","tags":["reactjs","svelte","svelte-3","react-context","svelte-store"],"text":"Title: Understanding Context in Svelte (convert from React Context)\nTags: reactjs, svelte, svelte-3, react-context, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI have a react app that uses ContextAPI to manage authentication and I am trying to implement a similar thing in Svelte.\n\nIn `Authenticate.js` I have this:\n\n```\nimport React, { useContext, useState, useEffect } from \"react\"\nimport { auth } from \"../firebase\"\n\nconst AuthCt = React.createContext()\n\nexport function Auth() {\n return useContext(AuthCt)\n}\n\nexport function AuthComp({ children }) {\n const [currentUser, setCurrentUser] = useState()\n const [loading, setLoading] = useState(true)\n\n function login(email, password) {\n return auth.signInWithEmailAndPassword(email, password)\n }\n\n function logout() {\n return auth.signOut()\n }\n\n useEffect(() => {\n const unmount = auth.onAuthStateChanged(user => {\n setCurrentUser(user)\n setLoading(false)\n })\n\n return unmount\n }, [])\n\n const value = {\n currentUser,\n login,\n signup\n }\n\n return (\n \n {!loading && children}\n \n )\n}\n```\n\nThis context is used in other `Login.js` component like this:\n\n```\nimport { Auth } from \"./Authenticate\"\n\nconst Login = () => {\n const { currentUser, login } = Auth()\n```\n\nAnd in `App.js` I have:\n\n```\nimport { AuthComp } from \"./Authenticate\";\n\nfunction App() {\n return (\n \n All others go here \n \n );\n}\n```\n\nHow do I achieve this in Svelte, particularly the `Authenticate` context?\n\nI haven't been able to do much in Svelte as I don't know how to proceed from here. So far I have `AuthComp.svelte`. I don't know if I am doing the right thing.\n\n```\n\n import { getContext, setContext } from 'svelte';\n import { auth } from '../firebase';\n import { writable } from 'svelte/store';\n\n let Auth = getContext('AuthCt')\n setContext('Auth', Auth)\n\n let currentUser;\n let loading = true;\n\n \n const unmount = auth.onAuthStateChanged(user => {\n currentUser = user;\n loading = false\n });\n\n function login(email, password) {\n return auth.signInWithEmailandPassWord(email,password)\n }\n \n function logout() {\n return auth.signOut()\n }\n \n const value = { currentUser, login, signUp }\n \n\n```\n\n========================================\n\nTop Answer:\nIn Svelte, context is set with `setContext(key, value)` in a parent component, and children can access the `value` object with `getContext(key)`. See the docs for more info.\n\nIn your case, the context would be used like this:\n\n```\n\n import { getContext, setContext } from 'svelte';\n import { auth } from '../firebase';\n import { writable } from 'svelte/store';\n\n // you can initialize this to something else if you want\n let currentUser = writable(null)\n let loading = true\n \n // maybe you're looking for `onMount` or `onDestroy`?\n const unmount = auth.onAuthStateChanged(user => {\n currentUser.set(user)\n loading = false\n });\n\n function login(email, password) {\n return auth.signInWithEmailandPassWord(email,password)\n }\n \n function logout() {\n return auth.signOut()\n }\n \n const value = { currentUser, login, signUp }\n\n setContext('Auth', value) \n \n\n{#if !loading}\n \n{/if}\n```\n\nHere, `currentUser`, `login`, and `signup` (not sure where that's coming from?) are set as context with `setContext()`. To use this context, you would probably have something like this:\n\n```\n\n \n \n\n import { getContext } from 'svelte'\n\n const { currentUser, login, signup } = getContext('Auth')\n // you can subscribe to currentUser with $currentUser\n\nsome content\n```\n\nAs written in the docs, context is **not reactive**, so `currentUser` is first converted into a store so it can be subscribed to in a child. As for the `useEffect`, Svelte has lifecycle functions that you can use to run code at different points, such as `onMount` or `onDestroy`.\n\nIf you're new to Svelte, their tutorial is very comprehensive with plenty of examples that you can refer back to.\n\nHope this helped!\n\n========================================\n\nCode:\n```text\nimport React, { useContext, useState, useEffect } from \"react\"\nimport { auth } from \"../firebase\"\n\nconst AuthCt = React.createContext()\n\nexport function Auth() {\n return useContext(AuthCt)\n}\n\nexport function AuthComp({ children }) {\n const [currentUser, setCurrentUser] = useState()\n const [loading, setLoading] = useState(true)\n\n function login(email, password) {\n return auth.signInWithEmailAndPassword(email, password)\n }\n\n function logout() {\n return auth.signOut()\n }\n\n useEffect(() => {\n const unmount = auth.onAuthStateChanged(user => {\n setCurrentUser(user)\n setLoading(false)\n })\n\n return unmount\n }, [])\n\n const value = {\n currentUser,\n login,\n signup\n }\n\n return (\n <AuthCt.Provider value={value}>\n {!loading && children}\n </AuthCt.Provider>\n )\n}\n```\n\n```text\nimport { Auth } from \"./Authenticate\"\n\nconst Login = () => {\n const { currentUser, login } = Auth()\n```\n\n```text\nimport { AuthComp } from \"./Authenticate\";\n\nfunction App() {\n return (\n <AuthComp>\n <div> All others go here </div>\n </AuthComp>\n );\n}\n```\n\n```text\n<script>\n import { getContext, setContext } from 'svelte';\n import { auth } from '../firebase';\n import { writable } from 'svelte/store';\n\n let Auth = getContext('AuthCt')\n setContext('Auth', Auth)\n\n let currentUser;\n let loading = true;\n\n \n const unmount = auth.onAuthStateChanged(user => {\n currentUser = user;\n loading = false\n });\n\n\n function login(email, password) {\n return auth.signInWithEmailandPassWord(email,password)\n }\n \n function logout() {\n return auth.signOut()\n }\n \n const value = { currentUser, login, signUp }\n \n</script>\n\n<slot value={value}></slot>\n```\n\n```text\nAuthenticate.js\n```\n\n```text\nLogin.js\n```\n\n```text\nApp.js\n```\n\n```text\nAuthenticate\n```\n\n```text\nAuthComp.svelte\n```\n\n```html\n<!-- parent.svelte -->\n\n<script>\n import { setContext } from 'svelte'\n\n setContext('myContext', true)\n</script>\n\n<!-- child.svelte -->\n\n<script>\n import { getContext } from 'svelte'\n\n const myContext = getContext('myContext')\n</script>\n```\n\n```text\n// mystore.ts\nimport { writable } from 'svelte/store'\n\n// 0 is the initial value\nconst writableStore = writable(0)\n\n// set the new value to 1\nwritableStore.set(1)\n\n// use `update` to set a new value based on the previous value\nwritableStore.update((oldValue) => oldValue + 1)\n\nexport { writableStore }\n```\n\n```html\n<script>\n import { writableStore } from './mystore'\n\n</script>\n\n{$writableStore}\n```\n\n```html\n<!-- parent.svelte -->\n\n<script>\n import { setContext } from 'svelte'\n import { writable } from 'svelte/store'\n\n const writableStore = writable(0)\n setContext('myContext', writableStore)\n</script>\n\n<!-- child.svelte -->\n\n<script>\n import { getContext } from 'svelte'\n\n const myContext = getContext('myContext')\n</script>\n\n{$myContext}\n```\n\n```text\n// doubled will always be twice of single. If single updates, doubled will run again.\n$: doubled = single * 2\n\n// equivalent to this\n\nlet single = 0\nconst [doubled, setDoubled] = useState(single * 2)\n\nuseEffect(() => {\n setDoubled(single * 2)\n}, [single])\n```\n\n```html\n<script>\n import { setContext } from 'svelte'\n import { writable } from 'svelte/store'\n\n // this value is bound to the input's value. When the user types, this variable will always update\n let value\n\n const valueStore = writable(value)\n\n setContext('inputContext', valueStore)\n\n $: valueStore.set(value)\n\n</script>\n\n<input type='text' bind:value />\n```\n\n```html\n<!-- parent.svelte -->\n<script>\n import { writable } from 'svelte/store'\n import { onDestroy, setContext } from 'svelte'\n\n import { auth } from '../firebase'\n\n const userStore = writable(null)\n\n const firebaseUnsubscribe = auth.onAuthStateChanged((user) => {\n userStore.set(user)\n })\n\n const login = (email, password) => auth.signInWithEmailandPassWord(email,password)\n\n const logout = () => auth.signOut()\n\n setContext('authContext', { user: userStore, login, logout })\n\n onDestroy(() => firebaseUnsubscribe())\n\n</script>\n\n<slot />\n\n<!-- child.svelte -->\n<script>\n import { getContext } from 'svelte'\n\n const { login, logout, user } = getContext('authContext')\n</script>\n\n{$user?.displayName}\n```\n\n```text\nuseEffect\n```\n\n```text\nuseEffect\n```\n\n```text\nvalueStore\n```\n\n```text\nonAuthStateChanged\n```\n\n```text\nonAuthStateChanged\n```\n\n```html\n<script>\n import { getContext, setContext } from 'svelte';\n import { auth } from '../firebase';\n import { writable } from 'svelte/store';\n\n // you can initialize this to something else if you want\n let currentUser = writable(null)\n let loading = true\n \n // maybe you're looking for `onMount` or `onDestroy`?\n const unmount = auth.onAuthStateChanged(user => {\n currentUser.set(user)\n loading = false\n });\n\n\n function login(email, password) {\n return auth.signInWithEmailandPassWord(email,password)\n }\n \n function logout() {\n return auth.signOut()\n }\n \n const value = { currentUser, login, signUp }\n\n setContext('Auth', value) \n \n</script>\n\n{#if !loading}\n <slot></slot>\n{/if}\n```\n\n```html\n<!-- App -->\n<AuthComp>\n <!-- Some content here -->\n <Component />\n</AuthComp>\n\n<!-- Component.svelte -->\n<script>\n import { getContext } from 'svelte'\n\n const { currentUser, login, signup } = getContext('Auth')\n // you can subscribe to currentUser with $currentUser\n</script>\n<div>some content</div>\n```\n\n```text\nsetContext(key, value)\n```\n\n```text\nvalue\n```\n\n```text\ngetContext(key)\n```\n\n```text\ncurrentUser\n```\n\n```text\nlogin\n```\n\n```text\nsignup\n```\n\n```text\nsetContext()\n```\n\n```text\ncurrentUser\n```\n\n```text\nuseEffect\n```\n\n```text\nonMount\n```\n\n```text\nonDestroy\n```\n\n========================================\n\nComments:\n- This is awesome. About your question - `maybe you're looking for onMount or onDestroy?` - The idea was to replicate the `useEffect` to change the `currentUser` and `loading` values when the auth state changes. I guess what I would need if `afterUpdate` but I don't know if that's what will give me the same thing as what the `useEffect` does. I am not sure if the unmount function will get me that.\n- @Kay Without knowing more about what the `auth.onAuthStateChanged` function does, I don't think I can help you with that (maybe that's a different question since this one is mainly about context). It is possible that you don't need any lifecycle hooks at all and can just call it directly.\n- `onAuthStateChanged` adds an observer for changes to the user's sign-in state and is triggered when the user signs in or out.\n- I guess you're using firebase auth. I've used it too and what I did was just subscribe to `onAuthStateChanged` in `onMount` of `App.svelte`. Then, based on the `user` parameter I set some reactive values that are used to determine what to render.\n- Really GREAT answer!\n- Hey @Nick do you know the impact of calling `auth.onAuthStateChanged()` like you did above (i.e. directly in the component) vs calling it in `onMount()`?\n- Unless you're doing server side rendering, I don't think there's a noticeable difference. Calling it outside of `onMount` will run it sooner since `onMount` waits until the component is on the screen. With server side rendering, I've been just checking to see if `typeof window !== 'undefined` (since `onAuthStateChanged` needs to run in the browser) instead of waiting for `onMount` most of the time. Not sure if this is the best way, but it's worked for me.\n- What is the purpose of keeping a store scoped? If you could just import a store into both the parent and child, then context isn't needed. Is there an advantage to this or is this an anti-pattern? Btw this comparison has helped me so much.\n- You're correct, context isn't needed to use stores. And it's not an anti-pattern to do so. The main thing to be aware of when using a store that way is you'll need to initialize it in a separate file—you can't export stores from inside components (as far as I know). Using context with stores is great if you want to scope the store, or you don't want to deal with hooking up the context. One example are and components. ListItems should always be inside lists, and there can be multiple lists. In this case, it's idiomatic to scope the context. Does that help?\n- Really helpful explanation, thanks @Nick! In fact there is a way to export a store from a component from inside a `` here's a REPL\n- Holy smoke! you really nailed it!","metadata":{"transformedAt":"2026-08-18T18:33:40.656Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":560,"estimatedTokens":3104}}38{"id":"stack-62087073","source":"stackoverflow","questionId":62087073,"title":"Svelte 3, async onMount or a valid alternative?","tags":["javascript","ecmascript-6","svelte","svelte-3","svelte-component"],"text":"Title: Svelte 3, async onMount or a valid alternative?\nTags: javascript, ecmascript-6, svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nWhat I need is to use `async-await` in Svelte `onMount()`.\n\n*Or maybe you can suggest me what is wrong and what I can use alternatively.*\n\n**To Reproduce**\n\n- go here: https://svelte.dev/repl/000ae69c0fe14d9483678d4ace874726?version=3.23.0\n\n- open the console\n\n- click on the button\n\n- you should see messages: `\"Mounting...\"` and `\"A lot of background work...\"`\n\n- if you click again the destroy message is not written\n\n**WHY?**\n\nDid `onMount()` recognizes the `async` function promise? Should it?\n\nI need that `async` behavior because I need to wait for `function lazyLoading()` before rendering the `Child` component.\n\n**Is there an alternative way to do this in Svelte?**\n\n========================================\n\nTop Answer:\n`onMount` must be synchronous. However, you can use an `{#await}` block in your markup and make `lazyLoading` `async`, for example:\n\n```\n{#await lazyLoading() then data}\n I'm the child and I loaded \"{data}\".\n{/await}\n```\n\nYou could also do...\n\n```\n\n let dataPromise = lazyLoading()\n\n{#await dataPromise then data}\n I'm the child and I loaded \"{data}\".\n{/await}\n```\n\nSee my working example here.\n\nThis has the additional benefit of allowing you to use a loader as well as markup that appears when the promise is rejected, using this syntax:\n\n```\n{#await promise}\n loading\n{:then value}\n loaded {value}\n{:catch error}\n failed with {error}\n{/await}\n```\n\n========================================\n\nCode:\n```text\nasync-await\n```\n\n```text\nonMount()\n```\n\n```text\n\"Mounting...\"\n```\n\n```text\n\"A lot of background work...\"\n```\n\n```text\nonMount()\n```\n\n```text\nasync\n```\n\n```text\nasync\n```\n\n```text\nfunction lazyLoading()\n```\n\n```text\nChild\n```\n\n```js\nonMount(() => {\n async function foo() {\n bar = await baz();\n }\n\n foo();\n\n return () => console.log('destroyed');\n});\n```\n\n```text\nonMount\n```\n\n```text\nasync\n```\n\n```text\nonMount\n```\n\n```text\nasync\n```\n\n```text\nuseEffect\n```\n\n```text\nonMount\n```\n\n```text\nuseEffect\n```\n\n```text\nasync\n```\n\n```html\n{#await lazyLoading() then data}\n I'm the child and I loaded \"{data}\".\n{/await}\n```\n\n```html\n<script>\n let dataPromise = lazyLoading()\n</script>\n\n{#await dataPromise then data}\n I'm the child and I loaded \"{data}\".\n{/await}\n```\n\n```html\n{#await promise}\n loading\n{:then value}\n loaded {value}\n{:catch error}\n failed with {error}\n{/await}\n```\n\n```text\nonMount\n```\n\n```text\n{#await}\n```\n\n```text\nlazyLoading\n```\n\n```text\nasync\n```\n\n```text\n<script lang=\"ts\">\n import { listen, type UnlistenFn } from \"@tauri-apps/api/event\";\n import { onMount } from \"svelte\";\n\n onMount(() => {\n let unMountFunction: UnlistenFn | null = null;\n\n listen(\"my-event\", (event) => {\n // event callback\n }).then(unlisten => unMountFunction = unlisten);\n\n return () => {\n if (unMountFunction) {\n unMountFunction();\n }\n };\n });\n</script>\n```\n\n========================================\n\nComments:\n- Look at `{#await}`: svelte.dev/tutorial/await-blocks\n- Are you suggesting to use `#await` and `onMount`, both?\n- No, I'm not sure what you'd want to do at `onMount` then. Check out my example: svelte.dev/repl/7e175db016b74c4ba4688c76114866c9?version=3.2‌​3.0\n- Hm let me put that into an actual answer...\n- It is interesting that it still works when making it async, only that the clean up breaks. Is there a reason why it does not work async, like it does in React?\n- For clarity, React has the exact same limitation — your `useEffect` handler (the nearest equivalent to `onMount`) must return a cleanup function synchronously, to avoid race conditions.\n- I have a question about this. In the sapper docs, under sapper.svelte.dev/docs#Making_a_component_SSR_compatible onMount is used with an `async` keyword. Doesn't this contradict your statement about `onMount` not being asynchronous? This confuses me, is there something I don't see?\n- Does this imply that when you don't need a destroy function, it is okay to use async?\n- Yes, that's totally valid\n- Now, you can use `async` function inside `onMount` hook. See svelte.dev/tutorial/onmount.\n- @LaodeMuhammadAlFatih No, this isn't true, afaik. Since this documentation page has the async key word for long time and was always 'wrong' and confusing. But Rich wrote it: it is okay to use it, as long as you don't need to return a destroy function.","metadata":{"transformedAt":"2026-08-18T18:33:40.656Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":225,"estimatedTokens":1115}}39{"id":"stack-50702662","source":"stackoverflow","questionId":50702662,"title":"Passing Parent Method to Child in Svelte","tags":["svelte"],"text":"Title: Passing Parent Method to Child in Svelte\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nAs the title suggests, I am trying to pass a method from a parent component to a child component.\n\nFor example,\n\n*App.html*\n\n```\n\n \n\n import TodoItem from './TodoItem.html';\n export default {\n components: {\n TodoItem,\n },\n methods: {\n toggle(index) {\n console.log(index);\n },\n },\n };\n\n```\n\n*TodoItem.html*\n\n```\n\n \n\n export default {\n methods: {\n toggle(index) {\n // a guess. this works if you pass in console.log\n this.options.data.toggle(index)\n },\n },\n };\n\n```\n\nThe desired functionality is that TodoItem calls the parent's method with its data.\n\nThis example breaks, the console logs `TypeError: this.options.data.toggle is not a function`.\n\n========================================\n\nTop Answer:\nSeems like \"fire\" was part of svelte v2 but in svelte v3 it's changed with `createEventDispatcher`\n\ne.g -\n\nchild.svelte\n\n```\n\n import { createEventDispatcher } from 'svelte';\n\n const dispatch = createEventDispatcher();\n\n function sayHello() {\n dispatch('message', {\n text: 'Hello!'\n });\n }\n\n Click to say hello\n\n```\n\nparent.svelte\n\n```\n\n import Inner from './child.svelte';\n\n function handleMessage(event) {\n alert(event.detail.text);\n }\n\n```\n\nfor more info - please visit : https://svelte.dev/tutorial/component-events\n\n========================================\n\nCode:\n```html\n<div>\n <TodoItem\n done={todo.done}\n toggle={toggle}\n />\n</div>\n<script>\n import TodoItem from './TodoItem.html';\n export default {\n components: {\n TodoItem,\n },\n methods: {\n toggle(index) {\n console.log(index);\n },\n },\n };\n</script>\n```\n\n```html\n<div>\n <button on:click=\"toggle(0)\"></button>\n</div>\n<script>\n export default {\n methods: {\n toggle(index) {\n // a guess. this works if you pass in console.log\n this.options.data.toggle(index)\n },\n },\n };\n</script>\n```\n\n```text\nTypeError: this.options.data.toggle is not a function\n```\n\n```html\n<div>\n <TodoItem\n {todo}\n on:toggle=\"toggle(todo)\"\n />\n</div>\n<script>\n import TodoItem from './TodoItem.html';\n export default {\n components: {\n TodoItem,\n },\n methods: {\n toggle(todo) {\n todo.done = !todo.done;\n const { todos } = this.get();\n this.set({ todos });\n }\n }\n };\n</script>\n```\n\n```html\n<div>\n <button on:click=\"fire('toggle')\">{todo.description}</button>\n</div>\n```\n\n```html\n<TodoItem on:toggle=\"fire('toggle', event)\">...</TodoItem>\n```\n\n```text\n<TodoItem on:toggle>...</TodoItem>\n```\n\n```html\n<script>\n import { createEventDispatcher } from 'svelte';\n\n const dispatch = createEventDispatcher();\n\n function sayHello() {\n dispatch('message', {\n text: 'Hello!'\n });\n }\n</script>\n\n<button on:click={sayHello}>\n Click to say hello\n</button>\n```\n\n```html\n<script>\n import Inner from './child.svelte';\n\n function handleMessage(event) {\n alert(event.detail.text);\n }\n</script>\n\n<Inner on:message={handleMessage}/>\n```\n\n```text\ncreateEventDispatcher\n```\n\n```text\n<script>\n import Child from './Child.svelte'\n \n const handleSubmit = value => {\n console.log(value)\n }\n</script>\n\n<Child {handleSubmit}/>\n```\n\n```text\n<script>\n export let handleSubmit\n let value = ''\n \n const onSubmit = e => {\n e.preventDefault()\n handleSubmit(value)\n }\n</script>\n\n<form on:submit={onSubmit}>\n <input type=\"text\" bind:value/>\n</form>\n```\n\n```text\n<script>\n import { getContext, setContext } from 'svelte';\n import Child1 from './Child1.svelte';\n import Child2 from './Child2.svelte';\n \n let counter = 10;\n \n setContext('counter', { increment, decrement });\n \n function increment(delta) {\n counter += delta;\n }\n function decrement(delta) {\n counter -= delta;\n }\n</script>\n\n<Child1 />\n<Child2 />\n\n<button on:click={() => { increment(10); }}>\n Increment x10\n</button>\n\n<div>{counter}</div>\n```\n\n```text\n<script>\n import { getContext } from 'svelte';\n \n const { increment } = getContext('counter');\n</script>\n\n<button on:click={() => increment(1)}>Increment</button>\n```\n\n```text\n<script>\n import { getContext } from 'svelte';\n \n const { decrement } = getContext('counter');\n</script>\n\n<button on:click={() => decrement(1)}>Decrement</button>\n```\n\n========================================\n\nComments:\n- What if the child is not a component but a simple ``?\n- This is easier in Svelte 3 as Ujjwal Kumar Gupta pointed out. Maybe it's worth updating this answer with the Svelte 3 example along the Svelte 2 version since this has already been accepted as the correct answer.\n- By using the `| preventDefault` modifier it was also possible to directly call the passed function without the need of the intermediate `onSubmit` like this ``","metadata":{"transformedAt":"2026-08-18T18:33:40.656Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":288,"estimatedTokens":1206}}40{"id":"stack-57068381","source":"stackoverflow","questionId":57068381,"title":"How to redo {#await ...} in Svelte?","tags":["javascript","node.js","svelte"],"text":"Title: How to redo {#await ...} in Svelte?\nTags: javascript, node.js, svelte\nSource: Stack Overflow\n\nQuestion:\nI want this to be fully client side rendering.. So, I don't want to refresh the page just to redo the promise..\n\nHere's the code that I made..\n\n```\n{#await myFetchMethod(\"/api/v1/me\")}\n \n{:then loggedIn}\n {#if loggedIn}\n Profile\n Logout\n {:else}\n Login\n Register\n {/if}\n{:catch error}\n Can't connect to the server!\n\n Refresh\n{/await}\n```\n\nI want the refresh button to just redo the `myFetchMethod(\"/api/v1/me\")` promise and get the result as intended.\n\n========================================\n\nTop Answer:\nPass a parameter to your function that triggers a re-run on change.\n\n```\n{#await myFetchMethod(\"/api/v1/me\", triggerParameter)}\n...\n{:then result}\n...\n{:catch error}\n...\n{/await}\n```\n\nThe parameter does not necessarily to be used inside the async function. But when the value of the parameter changes, the function is run again. (When input changes, a new output is to expected).\n\nTo let it be triggered by a refresh button you can do:\n\n```\n\n let trig = false;\n\n{#await myFetchMethod(\"/api/v1/me\", trig)}\n \n{:then loggedIn}\n ...\n{:else}\n ...\n{:catch error}\n\n Can't connect to the server!\n\n trig = !trig}>Refresh\n{/await}\n```\n\n========================================\n\nCode:\n```text\n{#await myFetchMethod(\"/api/v1/me\")}\n <Loading />\n{:then loggedIn}\n {#if loggedIn}\n <Link class=\"mb-0 h3\" to=\"/profile\">Profile</Link>\n <Link class=\"mb-0 h3\" to=\"/logout\">Logout</Link>\n {:else}\n <Link class=\"mb-0 h3\" to=\"/login\">Login</Link>\n <Link class=\"mb-0 h3\" to=\"/register\">Register</Link>\n {/if}\n{:catch error}\n <p>Can't connect to the server!</p>\n <button on:click={whatShouldIDoHere}>Refresh</button>\n{/await}\n```\n\n```text\nmyFetchMethod(\"/api/v1/me\")\n```\n\n```js\n<script>\n let doLoginCheck = checkIfLoggedIn()\n\n function tryAgain() {\n doLoginCheck = checkIfLoggedIn()\n }\n\n function checkIfLoggedIn() {\n return fetch('/api/v1/me')\n .then(res => {\n if (!res.ok) {\n throw new Error('Cannot connect to server!');\n }\n return res.json();\n });\n }\n</script>\n\n{#await doLoginCheck}\n <Loading />\n{:then loggedIn}\n {#if loggedIn}\n <Link class=\"mb-0 h3\" to=\"/profile\">Profile</Link>\n <Link class=\"mb-0 h3\" to=\"/logout\">Logout</Link>\n {:else}\n <Link class=\"mb-0 h3\" to=\"/login\">Login</Link>\n <Link class=\"mb-0 h3\" to=\"/register\">Register</Link>\n {/if}\n{:catch error}\n <p>{error.message}</p>\n <button on:click={tryAgain}>Refresh</button>\n{/await}\n```\n\n```text\n{#await myFetchMethod(\"/api/v1/me\", triggerParameter)}\n...\n{:then result}\n...\n{:catch error}\n...\n{/await}\n```\n\n```text\n<script>\n let trig = false;\n</script>\n\n{#await myFetchMethod(\"/api/v1/me\", trig)}\n <Loading />\n{:then loggedIn}\n ...\n{:else}\n ...\n{:catch error}\n\n <p>Can't connect to the server!</p>\n <button on:click={() => trig = !trig}>Refresh</button>\n{/await}\n```\n\n========================================\n\nComments:\n- This seems like a more elegant solution than the accepted answer. Wish Svelte had a \"blessed\" way of doing this.\n- oh my, I was trying to reimplement React's useSWR doing some crazy Class state management and dind't realize you could just do that instead.","metadata":{"transformedAt":"2026-08-18T18:33:40.656Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":158,"estimatedTokens":816}}41{"id":"stack-74549820","source":"stackoverflow","questionId":74549820,"title":"SvelteKit page data doesn't always update when opening new page in the same dynamic route","tags":["svelte","sveltekit"],"text":"Title: SvelteKit page data doesn't always update when opening new page in the same dynamic route\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a route structure `/items/[category]`. When the user is browsing `/items/category1` and then tries to go to a another page in the same route (eg. `/items/category2`) the page data usually updates to show category2 items, but not always. Sometimes the URL updates in the browser but the page data still shows items from the previous URL.\n\nMy `+page.server.js` for `/items/[category]` looks like:\n\n```\nimport { getItems } from '$lib/services/ItemService';\nexport const csr = false;\nexport const load = ({ locals, params }) => {\n return {\n items: getItems(locals, `category = \"${params.itemCategory}\"`)\n };\n};\n```\n\nAnd my `+page.svelte` is:\n\n```\n\n import { ItemCard } from '$lib/components';\n export let data\n let items = data.items\n\n...\n \n {#each items as item}\n \n {/each}\n\n```\n\nThe `getItems()` function retrieves JSON data from pocketbase and is working correctly.\n\nI read that adding the `export const csr = false;` to the `+page.server.js` should solve the problem, but it appears that the page still isn't always re-loading data from the server when swapping between routes.\n\n========================================\n\nTop Answer:\nChange\n\n```\nlet categoryUrl = $page.params.category;\n```\n\nto\n\n```\n$: categoryUrl = $page.params.category;\n```\n\n========================================\n\nCode:\n```js\nimport { getItems } from '$lib/services/ItemService';\nexport const csr = false;\nexport const load = ({ locals, params }) => {\n return {\n items: getItems(locals, `category = \"${params.itemCategory}\"`)\n };\n};\n```\n\n```html\n<script>\n import { ItemCard } from '$lib/components';\n export let data\n let items = data.items\n</script>\n...\n<div class=\"grid grid-cols-1 md:grid-cols-3 px-4 gap-6\"> \n {#each items as item}\n <ItemCard {item}/>\n {/each}\n</div>\n```\n\n```text\n/items/[category]\n```\n\n```text\n/items/category1\n```\n\n```text\n/items/category2\n```\n\n```text\n+page.server.js\n```\n\n```text\n/items/[category]\n```\n\n```text\n+page.svelte\n```\n\n```text\ngetItems()\n```\n\n```text\nexport const csr = false;\n```\n\n```text\n+page.server.js\n```\n\n```js\nlet items = data.items\n```\n\n```js\n$: items = data.items // Svelte 3/4\nconst items = $derived(data.items) // Svelte 5 runes\n```\n\n```js\n$: ({ items } = data) // Svelte 3/4\nconst { items } = $derived(data) // Svelte 5 runes\n```\n\n```text\ndata\n```\n\n```text\nitems\n```\n\n```html\n<button on:click={() => {\n window.location.href = `/path/${id}`;\n }}>\nGo\n</button>\n```\n\n```text\nwindow.location.href\n```\n\n```text\nimport { navigating } from '$app/stores';\nlet categoryUrl = $page.params.category;\n$: {\n categoryUrl = typeof window !== 'undefined' ? window.location.href.split('/').pop() : $page.params.category;\n}\n$: if($navigating) {\n let newUrl = typeof window !== 'undefined' ? window.location.href.split('/').pop() : $page.params.category;\n if(categoryUrl !== newUrl) { \n .....\n }\n}\n```\n\n```js\nlet categoryUrl = $page.params.category;\n```\n\n```js\n$: categoryUrl = $page.params.category;\n```\n\n========================================\n\nComments:\n- This works only for the first time, when going 'back' to a previous url, the page isn't updated. unless I pass 'invalidateAll:true' in the 'goto()'. Any ideas how to fix that?\n- This will cause a page reload, which is wasteful. SvelteKit has a client-side router that only loads data that is not already loaded. Your page is probably mutating state non-reactively.\n- `params` is reactive, or rather, the store that it is in is. If you just write `{$page.params.category}` somewhere in the template, it should update just fine. Maybe you navigated without using `goto` or had some intermediary variable that was not declared reactively.","metadata":{"transformedAt":"2026-08-18T18:33:40.656Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":179,"estimatedTokens":961}}42{"id":"stack-57954008","source":"stackoverflow","questionId":57954008,"title":"Call Svelte component's function from global scope","tags":["javascript","google-signin","svelte","sapper"],"text":"Title: Call Svelte component's function from global scope\nTags: javascript, google-signin, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI am creating a Sapper page, where I'd like to use Google Sign-in button. It requires `data-onsuccess` attribute to specify callback function. From what I was able to discover from Google's platform JS library, it looks for the function in the global/`window` scope.\n\nIs there a way to access/call Svelte's component function from global webpage scope? It might be of use for interop with external libraries which cannot be loaded through `import` right into the component.\n\nExample of what I am trying to do:\n\n```\n\n function onSignComponent(user){\n console.log('Signed in');\n }\n\n```\n\nThis work when `onSignComponent` is in global scope but not when it is in component scope.\n\n========================================\n\nTop Answer:\nOne way to do this would be to add `` directive in your component and then in the method `onSignComponent` raise this *xxx* event.\n\n**in component**\n\n```\n\n```\n\n**somewhere else**\n\n```\nconst myEvent = new CustomEvent('loginSuccess', { ... some object });\nwindow.dispatchEvent(myEvent);\n```\n\n========================================\n\nCode:\n```text\n<script>\n function onSignComponent(user){\n console.log('Signed in');\n }\n</script>\n\n<div id=\"login\" class=\"g-signin2\" data-onsuccess=\"{onSignComponent}\" data-theme=\"dark\" />\n```\n\n```text\ndata-onsuccess\n```\n\n```text\nwindow\n```\n\n```text\nimport\n```\n\n```text\nonSignComponent\n```\n\n```js\n<script>\n window.onSignIn = user => {\n // ...\n };\n</script>\n\n<div id=\"login\" class=\"g-signin2\" data-onsuccess=\"onSignIn\" data-theme=\"dark\" />\n```\n\n```text\nwindow\n```\n\n```text\n<svelte:window on:loginSuccess={loginSuccess}></svelte:window>\n```\n\n```text\nconst myEvent = new CustomEvent('loginSuccess', { ... some object });\nwindow.dispatchEvent(myEvent);\n```\n\n```text\n<svelte:window on:xxx>\n```\n\n```text\nonSignComponent\n```\n\n========================================\n\nComments:\n- Cool. I thought about `svelte:window` but didn't know I could connect it with custom events\n- Wow, that is embarrassingly simple. I should have thought about that while trying another workaround (attaching svelte stores to window object). Thanks a lot!\n- I am getting a `ReferenceError: window is not defined` in Svelte 5","metadata":{"transformedAt":"2026-08-18T18:33:40.656Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":105,"estimatedTokens":577}}43{"id":"stack-68403820","source":"stackoverflow","questionId":68403820,"title":"Function called outside component initialization","tags":["javascript","svelte","svelte-3","svelte-component"],"text":"Title: Function called outside component initialization\nTags: javascript, svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\ni wanna to recall the onMount in my Svelte app by clicking some button, but i got this error.\nAny idea would be amazing, thx :)\n\n========================================\n\nCode:\n```svelte\n<script>\n import { onMount } from 'svelte';\n\n function someFunction() {\n // do stuff\n }\n\n onMount(someFunction)\n</script>\n\n<button on:click={someFunction}>Click me</button>\n```\n\n```text\nonMount\n```\n\n```text\nonMount\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.656Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":32,"estimatedTokens":139}}44{"id":"stack-64396362","source":"stackoverflow","questionId":64396362,"title":"Svelte transitions and animations on page load","tags":["svelte","svelte-transition"],"text":"Title: Svelte transitions and animations on page load\nTags: svelte, svelte-transition\nSource: Stack Overflow\n\nQuestion:\nI am currently working on a website using Svelte and Sapper. I'm using Svelte transitions to animate some of the page elements. Whenever I change to a new page route, the transitions animate correctly. But when I load the page for the first time, they do not animate.\n\nHow does Svelte handle animations on page load? Do I need to use onMount() to get them to work properly?\n\n========================================\n\nCode:\n```html\n<script>\n import { onMount } from 'svelte';\n\n let ready = false;\n onMount(() => ready = true);\n</script>\n\n<div class=\"always-visible\">\n {#if ready}\n <div class=\"visible-on-mount\">...</div>\n {/if}\n</div>\n```\n\n```text\nintro: true\n```\n\n```text\nonMount\n```\n\n========================================\n\nComments:\n- @FractalHQ created a nice component for this\n- I think now you can use the `global` modifier for transitions","metadata":{"transformedAt":"2026-08-18T18:33:40.656Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":40,"estimatedTokens":244}}45{"id":"stack-58809240","source":"stackoverflow","questionId":58809240,"title":"How to compare Prop changes in Svelte 3","tags":["svelte","svelte-3"],"text":"Title: How to compare Prop changes in Svelte 3\nTags: svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nIs there a mechanism in Svelte 3 for comparing prop changes inside a component before rendering? Similar to React getDerivedStateFromProps. \n\n```\n\n export let color;\n\n // Does anything like this exist in Svelte?\n\n beforeUpdate((changes) => {\n const same = changes.prev.color === changes.next.color\n })\n\n```\n\n========================================\n\nTop Answer:\nI've actually written a package that uses Svelte Stores to give you a simple interface to reference as many previous values as you need.\n\nSvelte Previous.\n\n```\n\n export let color;\n const [currentColor, previousColor] = usePrevious(color);\n $: $currentColor = color;\n\n{$previousColor} to {$currentColor}\n```\n\n========================================\n\nCode:\n```html\n<script>\n export let color;\n\n // Does anything like this exist in Svelte?\n\n beforeUpdate((changes) => {\n const same = changes.prev.color === changes.next.color\n })\n</script>\n```\n\n```html\n<script>\n export let color;\n\n $: {\n console.log('color changed', color);\n // will only get called when the `color` changed.\n }\n</script>\n```\n\n```html\n<script>\n export let color;\n let prevColor;\n\n $: {\n console.log('currentColor:', color, 'prevColor:', prevColor);\n prevColor = color;\n }\n</script>\n```\n\n```text\ncolor\n```\n\n```html\n<script>\n export let color;\n const [currentColor, previousColor] = usePrevious(color);\n $: $currentColor = color;\n</script>\n\n{$previousColor} to {$currentColor}\n```\n\n========================================\n\nComments:\n- just wondering if setting `prevColor` can trigger another reactive statement where prevColor is used.\n- @thecodejack you mean this svelte.dev/repl/36d1988c4718405c9208cec2f02b6d2a?version=3.1‌​6.7 ?\n- kind of similar..but here was my exact concern..svelte.dev/repl/d4156f465dbe42a597309fb7af0799c0?ve‌​rsion=3.16.7 ..with ReactJS, you can't do that in easy way but i can see Svelte handling it correct...Awesome","metadata":{"transformedAt":"2026-08-18T18:33:40.656Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":93,"estimatedTokens":508}}46{"id":"stack-63551277","source":"stackoverflow","questionId":63551277,"title":"Typing 's \"this\" property in TypeScript","tags":["typescript","svelte"],"text":"Title: Typing 's \"this\" property in TypeScript\nTags: typescript, svelte\nSource: Stack Overflow\n\nQuestion:\nI am building kind of a portal system in Svelte using a store to pass a component to display somewhere up the component tree.\n\nMy problem is not about implementing that system, it is about typing the store. I tried to declare it like so:\n\n```\nconst modalComponent = writable(null)\n```\n\nBut this doesn't work. When I import a component somewhere, VS Code shows me a type of `typeof __SvelteComponent_`, which is not compatible with the `SvelteComponent` type (which is actually an alias of `SvelteComponentDev`):\n\nType 'typeof __SvelteComponent_' is missing the following properties from type 'SvelteComponentDev': $set, $on, $destroy, $capture_state, and 2 more.\n\nHow am I supposed to type this? I would like to avoid using `any`.\n\n**Update**: here is a codesandbox of what would reproduce the case. Unfortunately, I can't seem to be able to get it to work with TypeScript. I'm still sharing it, hoping it can help.\n\n========================================\n\nCode:\n```text\nconst modalComponent = writable<SvelteComponent>(null)\n```\n\n```text\ntypeof <componentName>__SvelteComponent_\n```\n\n```text\nSvelteComponent\n```\n\n```text\nSvelteComponentDev\n```\n\n```text\nany\n```\n\n```text\nwritable<typeof SvelteComponent>\n```\n\n========================================\n\nComments:\n- Could you please provide a minimal reproductible example (probably using codesandbox). Can you also provide the way you import the type. Where did you get the `.d.ts` I didn't find it on `DefinitelyTyped`.\n- I'll try and setup a codesandbox. For typings, I just followed the official Svelte blog post about TS support : svelte.dev/blog/svelte-and-typescript. It includes a section about the tsconfig file to use (with a specific `include` config value)\n- Could you open an issue at github.com/sveltejs/language-tools/issues for this? This is something we have not considered and need to investigate how to fix this.\n- Do you mean an issue about my origin post or about the codesandbox that I can't get working?\n- It's fixed now. You should also note that it's `writable`, not `writable` in your answer.\n- I had the same issue in the latest version of svelte(3.58). I managed to get it working by switching to typescript version 5.0.4, instead of 4.9.5\n- As an alternative, svelte now ships ComponentType - a typescript utility that should help avoid issues like this one.","metadata":{"transformedAt":"2026-08-18T18:33:40.656Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":58,"estimatedTokens":611}}47{"id":"stack-69874742","source":"stackoverflow","questionId":69874742,"title":"SvelteKit console error \"window is not defined\" when i import library","tags":["import","console","svelte","apexcharts","sveltekit"],"text":"Title: SvelteKit console error \"window is not defined\" when i import library\nTags: import, console, svelte, apexcharts, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI would like to import apexChart library which using \"window\" property, and i get error in console.\n\n```\n[vite] Error when evaluating SSR module /src/routes/prehled.svelte:\nReferenceError: window is not defined\n```\n\nI tried use a apexCharts after mount, but the error did not disappear.\n\n```\n\n import ApexCharts from 'apexcharts'\n import { onMount } from 'svelte'\n const myOptions = {...myOptions}\n onMount(() => {\n const chart = new ApexCharts(document.querySelector('[data-chart=\"profit\"]'), myOptions)\n chart.render()\n })\n\n```\n\nI tried import a apexCharts when i am sure that browser exist.\n\n```\nimport { browser } from '$app/env'\n if (browser) {\n import ApexCharts from 'apexcharts'\n }\n```\n\nBut i got error \"'import' and 'export' may only appear at the top level\"\n\nI tried disable ssr in svelte.config.js\n\n```\nimport adapter from '@sveltejs/adapter-static';\nconst config = {\n kit: {\n adapter: adapter(),\n prerender: {\n enabled: false\n },\n ssr: false,\n}\n```\n\nI tried to create a component in which I import apexChart library and I created a condition that uses this component only if a browser exists\n\n```\n{ #if browser }\n \n{ /if }\n```\n\nNothing helped.\n\nDoes anyone know how to help me please?\n\n========================================\n\nTop Answer:\nI have found the last option with the Vite plugin to work best with less code in the end but will lose intellisense in vscode and see import highlighted as error (temp workaround at end): https://kit.svelte.dev/faq#how-do-i-use-x-with-sveltekit-how-do-i-use-a-client-side-only-library-that-depends-on-document-or-window\n\n- Install vite plugin: `npm i -D vite-plugin-iso-import`\n\n- Add plugin to svelte.config.js:\n\n```\nkit: {\n vite: {\n plugins: [\n isoImport(),\n ],\n```\n\n- Add plugin to TypeScript config (if you use TS):\n\n```\n\"compilerOptions\": {\n \"plugins\": [{ \"name\": \"vite-plugin-iso-import\" }],\n```\n\n- Use as normal but note the \"?client\" on the import:\n\n```\n\n import { chart } from 'svelte-apexcharts?client';\n import { onMount } from 'svelte'\n let myOptions = {...myOptions}\n onMount(() => {\n myOptions = {...updated options/data}\n });\n\n```\n\nDebugging note:\nTo have import not highlighting as an error temporarily, just:\n\n- `npm run dev`, your project will compile fine, then test in browser to execute at least once.\n\n- remove `?client` now, save and continue debugging as usual.\n\n========================================\n\nCode:\n```text\n[vite] Error when evaluating SSR module /src/routes/prehled.svelte:\nReferenceError: window is not defined\n```\n\n```js\n<script>\n import ApexCharts from 'apexcharts'\n import { onMount } from 'svelte'\n const myOptions = {...myOptions}\n onMount(() => {\n const chart = new ApexCharts(document.querySelector('[data-chart=\"profit\"]'), myOptions)\n chart.render()\n })\n</script>\n```\n\n```js\nimport { browser } from '$app/env'\n if (browser) {\n import ApexCharts from 'apexcharts'\n }\n```\n\n```js\nimport adapter from '@sveltejs/adapter-static';\nconst config = {\n kit: {\n adapter: adapter(),\n prerender: {\n enabled: false\n },\n ssr: false,\n}\n```\n\n```js\n{ #if browser }\n <ProfitChart />\n{ /if }\n```\n\n```html\n<script src=\"https://cdn.jsdelivr.net/npm/apexcharts\"></script>\n```\n\n```js\nonMount(() => {\n const chart = new ApexCharts(container, options)\n chart.render()\n})\n```\n\n```js\nonMount(async () => {\n const ApexCharts = (await import('apexcharts')).default\n const chart = new ApexCharts(container, options)\n chart.render()\n})\n```\n\n```text\nonMount\n```\n\n```text\napp.html\n```\n\n```text\n<svelte:head>\n```\n\n```text\ndocument.querySelector\n```\n\n```text\nkit: {\n vite: {\n plugins: [\n isoImport(),\n ],\n```\n\n```text\n\"compilerOptions\": {\n \"plugins\": [{ \"name\": \"vite-plugin-iso-import\" }],\n```\n\n```html\n<script context=\"module\">\n import { chart } from 'svelte-apexcharts?client';\n import { onMount } from 'svelte'\n let myOptions = {...myOptions}\n onMount(() => {\n myOptions = {...updated options/data}\n });\n</script>\n\n<div use:chart={myOptions} />\n```\n\n```text\nnpm i -D vite-plugin-iso-import\n```\n\n```text\nnpm run dev\n```\n\n```text\n?client\n```\n\n```text\nonMount(async () => {\n const Example = await import('@creator/examplePackage');\n usePackageInJSOrTS(Example.default);\n});\n```\n\n```text\nexport function usePackageInJsOrTs(NeededPackage) { \n let neededPacakge = new NeededPackage();\n}\n```\n\n========================================\n\nComments:\n- The `dyamic` import works perfectly.\n- The `dynamic` import fixed my window not defined error. Thanks!\n- Also checkout this reddit post: reddit.com/r/sveltejs/comments/n508th/comment/gx8sest/…\n- `vite-plugin-iso-import` documentation github.com/bluwy/vite-plugin-iso-import","metadata":{"transformedAt":"2026-08-18T18:33:40.656Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":245,"estimatedTokens":1216}}48{"id":"stack-58110067","source":"stackoverflow","questionId":58110067,"title":"Passing on:click event into dynamically created","tags":["javascript","html","event-handling","svelte","svelte-component"],"text":"Title: Passing on:click event into dynamically created\nTags: javascript, html, event-handling, svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI basically need to be able to trigger something within one or more components (that\nare being dynamically added via svelte:component) when an icon/button within the parent \ncomponent is clicked. e.g. I need to hook the parts denoted with ** below:-\n\n```\n\n let charts = [\n ChartA,\n ChartB,\n ChartC\n ];\n\n{#each charts as chart, i}\n \n \n \n \n \n \n{/each}\n```\n\nI was able to get something working by unsing an array of props but each\ncomponent is notified when the array changes so this is not very clean.\n\nI have searched both Google and StackOverflow as well as asking this question within the Svelte Discord channel with currently no luck.\n\nSvelte Repl showing the problem\n\nThis seems like such a simple requirement but after a couple of days I remain stuck so any advice on how to pass events into dynamic components is much appreciated.\n\n========================================\n\nCode:\n```text\n<script>\n let charts = [\n ChartA,\n ChartB,\n ChartC\n ];\n</script>\n{#each charts as chart, i}\n <div class=\"wrapper\">\n <div class=\"icon\" on:click={**HowToPassClickEventToComponent**}></div>\n <div class=\"content\">\n <svelte:component this={charts[i]} {**clickedEvent**}/>\n </div>\n </div>\n{/each}\n```\n\n```html\n<script>\n import ChartA from './ChartA.svelte'\n import ChartB from './ChartB.svelte'\n import ChartC from './ChartC.svelte'\n let charts = [\n ChartA,\n ChartB,\n ChartC\n ];\n let events = [];\n</script>\n\n<style>\n .icon{\n width:60px;\n height:30px;\n background-color:grey;\n }\n</style>\n\n{#each charts as chart, i}\n <div class=\"wrapper\">\n <div class=\"icon\" on:click={e=>events[i] = e}>Click</div>\n <div class=\"content\">\n <svelte:component this={charts[i]} event={events[i]}/>\n </div>\n </div>\n{/each}\n```\n\n```html\n<script>\n import ChartA from './ChartA.svelte'\n import ChartB from './ChartB.svelte'\n import ChartC from './ChartC.svelte'\n let charts = [\n ChartA,\n ChartB,\n ChartC\n ];\n let instances = []; \n</script>\n\n<style>\n .icon{\n width:60px;\n height:30px;\n background-color:grey;\n }\n</style>\n\n{#each charts as chart, i}\n <div class=\"wrapper\">\n <div class=\"icon\" on:click={e => instances[i].handle(e)}>Click</div>\n <div class=\"content\">\n <svelte:component\n this={charts[i]}\n bind:this={instances[i]}\n />\n </div>\n </div>\n{/each}\n```\n\n```html\n<script>\n let event;\n export function handle(e){\n event = e;\n };\n</script>\n```\n\n```text\nhandle\n```\n\n========================================\n\nComments:\n- Let every component define and add it's own on:click handler. And have a look at\n- I want to avoid the duplicated code within each component by having an outter component supply a toolbar which passes the click event into the child to deal with the click. I didn't think something like this would be so difficult when everything else in Svelte is so easy.\n- Why pass a click event. Every component can handle it's own handler. And if A, B, ... not identical sub somponents you can always code by importing a common js file.\n- And if you have a click event from multiple sources in the parent component you can identify the source using the event target and the action with the nested components uning a prop or store.\n- The components are indeed all different and using a common.js file may help in this specific example but I think there is still a valid use case for wanting to pass the event into the component. Passing a prop would also work but unfortunately this does not work either when using dynamically generated components as shown in the following modified REPL - svelte.dev/repl/fc91e089278848eba782f9ef994f534e?version=3.1‌​2.1\n- I don.t know why your code did not work, but if you use bind like: it works fine.\n- Adding the bind: seems to make the difference but this results in all of the components changing when the button is clicked (due to the single flag variable) which is not what is required and leads back to having the array of props from the original question which is really ugly as each component must check if it was the target of the click. Thanks, and I do appreciate your suggestions.\n- And I see now why your code did not work. You have to use: event={flag} and not event:{flag}\n- Maybe this question returns a helpfull answer: stackoverflow.com/questions/58115156/…\n- Thanks, I will keep my eye on that one as well.\n- Hi Rich, Your 2nd suggestion is perfect for what I need and it is much appreciated. Thank you also for Svelte (which is totally awesome).\n- Yes, very nice.\n- After a lot of searching, this answer showed me that using `export` is necessary when calling functions on child components, finally I can stop banging my head on the keyboard. :)","metadata":{"transformedAt":"2026-08-18T18:33:40.656Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":151,"estimatedTokens":1264}}49{"id":"stack-71475683","source":"stackoverflow","questionId":71475683,"title":"Svelte: update parent state from child","tags":["javascript","svelte"],"text":"Title: Svelte: update parent state from child\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nIn react I can do something like:\n\n`App.jsx`\n\n```\nconst App = () => {\n const [state, setState] = useState(\"old value\")\n\n return (\n <>\n \n \n )\n}\n```\n\n`ChildComponent.jsx`\n\n```\nconst ChildComponent = ({ setState }) => {\n const changeState = () => setState(\"new value\")\n\n return (\n \n Click\n \n )\n}\n```\n\nThen the parent state will be updated.\n\nI don't know how to do the same in Svelte...\n\nI have this:\n\n`index.svelte`\n\n```\n\n import { ChildComponent } from \"@components\"\n\n let state = \"old value\"\n\n \n\n```\n\n`ChildComponent.svelte`\n\n```\n\n export let state\n\n const changeState = () => {\n // I need to do something like:\n state = \"new value\"\n }\n \n\n Click\n\n```\n\nAnd see the new value reflected in the parent.\n\nI wanna to do it without use stores... I don't know if it's possible.\n\nMaybe store is the only way to proceed.\n\nI'm ears\n\n========================================\n\nTop Answer:\nFor those who are coming from `sveltekit2`/ `svelte5` here is the tweak:\n\n`index.svelte`\n\n```\n\n import { ChildComponent } from \"@components\";\n\n let state = $state(\"old value\");\n\n const setState = (value) => state = value;\n\n \n\n```\n\n`ChildComponent.svelte`\n\n```\n\n let {setState} = $props()\n \n\n setState(\"new value\")}>Click\n\n```\n\n========================================\n\nCode:\n```js\nconst App = () => {\n const [state, setState] = useState(\"old value\")\n\n return (\n <>\n <ChildComponent setState={setState} />\n </>\n )\n}\n```\n\n```js\nconst ChildComponent = ({ setState }) => {\n const changeState = () => setState(\"new value\")\n\n return (\n <div>\n <button onClick={changeState}>Click</button>\n </div>\n )\n}\n```\n\n```html\n<script>\n import { ChildComponent } from \"@components\"\n\n let state = \"old value\"\n</script>\n\n<main>\n <ChildComponent {state} />\n</main>\n```\n\n```html\n<script>\n export let state\n\n const changeState = () => {\n // I need to do something like:\n state = \"new value\"\n }\n </script>\n\n<div>\n <button on:click={changeState}>Click</button>\n</div>\n```\n\n```text\nApp.jsx\n```\n\n```text\nChildComponent.jsx\n```\n\n```text\nindex.svelte\n```\n\n```text\nChildComponent.svelte\n```\n\n```html\n<!-- Parent.svelte -->\n<script>\n import Child from './Child.svelte';\n let state = \"initial\";\n</script>\n\n<Child bind:state />\n\n<!-- Child.svelte -->\n<script>\n export let state;\n function changeState() {\n state = \"new value\";\n</script>\n\n<button on:click={changeState}>Click</button>\n```\n\n```html\n<!-- Parent.svelte -->\n<script>\n import Child from './Child.svelte';\n let state = \"initial\"\n \n function handleChange(ev) {\n state = ev.detail.state\n }\n</script>\n\n<Child {state} on:change={handleChange} />\n\n\n<!-- Child.svelte -->\n<script>\n import { createEventDispatcher } from 'svelte';\n export let state\n\n const dispatch = createEventDispatcher()\n\n function changeState() {\n // first argument is the event name\n // second is an object placed in ev.detail\n dispatch('change', { state: \"new value\" });\n }\n</script>\n\n<button on:click={changeState}>Click</button>\n```\n\n```html\n<script>\n import { ChildComponent } from \"@components\";\n\n let state = $state(\"old value\");\n\n const setState = (value) => state = value;\n</script>\n\n<main>\n <ChildComponent {state} />\n</main>\n```\n\n```html\n<script>\n let {setState} = $props()\n </script>\n\n<div>\n <button onclick={() => setState(\"new value\")}>Click</button>\n</div>\n```\n\n```text\nsveltekit2\n```\n\n```text\nsvelte5\n```\n\n```text\nindex.svelte\n```\n\n```text\nChildComponent.svelte\n```\n\n========================================\n\nComments:\n- You're passing a function in your react example, but a string in your Svelte example. If you just replicate your React example it will work fine (or even just pass an object). REPL\n- you're right, It wasn't working for me because I was trying to reassign the variable by value directly in the props. Now I see I have to do it using the setter function from the parent. Thank you!\n- Actually binding values works. I tried before with no success, that's weird. But all good now! Thank you.\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:40.656Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":274,"estimatedTokens":1077}}50{"id":"stack-62185374","source":"stackoverflow","questionId":62185374,"title":"How context=\"module\" works in Svelte and Sapper?","tags":["svelte","sapper"],"text":"Title: How context=\"module\" works in Svelte and Sapper?\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nWhile I was using Sapper to build a project whenever I fetch data from server, preload function is declared inside of script context=\"module\" like this below.\n\n```\n\n export async function preload(page) {\n return await this.fetch(`https://reqres.in/api/users?page=1`)\n .then(res1 => {\n return res1.json()\n }).then(res2 => {\n return { \n notices: res2.data,\n }\n })\n }\n\n```\n\nAccording to the document\n\n```\nA tag with a context=\"module\" attribute runs once when the module first evaluates, rather than for each component instance.\n```\n\nBut what is the meaning of **when the module first evaluates**?\n\nDoes it mean that when a component first rendered? then isn't the same that declaring api fetch function inside of onMount lifecycle method just like the code below?\n\n```\n\n onMount(async() => {\n const res = await fetch(`https://reqres.in/api/users?page=1`);\n const json = await res.json();\n })\n\n```\n\n========================================\n\nTop Answer:\nWhen using Sapper or SvelteKit (equivalent to Next.js in the react world), SSR components don't have access to the window object directly in the tag, so you need to wait until the component is \"hydrated\", or traditionally rendered. This means any libraries that use window, really anything that needs to run in the browser must be done through onMount\n\nWhen using SSR, with tools such as SvelteKit, onMount() does not run on the server. Therefore, your client dependent code (such as local storage access) can be placed in onMount() where it will not throw a server error.\n\nfrom https://www.reddit.com/r/sveltejs/comments/p5p386/trying_to_understand_script_vs_onmount/\n\n========================================\n\nCode:\n```text\n<script context=\"module\">\n export async function preload(page) {\n return await this.fetch(`https://reqres.in/api/users?page=1`)\n .then(res1 => {\n return res1.json()\n }).then(res2 => {\n return { \n notices: res2.data,\n }\n })\n }\n</script>\n```\n\n```text\nA <script> tag with a context=\"module\" attribute runs once when the module first evaluates, rather than for each component instance.\n```\n\n```text\n<script>\n onMount(async() => {\n const res = await fetch(`https://reqres.in/api/users?page=1`);\n const json = await res.json();\n })\n</script>\n```\n\n```js\n// Component.js\n\nconsole.log('evaluating module');\n\nexport class Component {\n constructor() {\n console.log('instantiating component');\n }\n}\n```\n\n```js\nimport { Component } from './Component.js';\n\n// \"evaluating module\" has already been logged. This will only happen once\n// for the entire application, however many modules import Component.js\n\nconst component1 = new Component(); // logs \"instantiating component\"\nconst component2 = new Component(); // logs \"instantiating component\" again\n```\n\n```text\n<script context=\"module\">\n```\n\n```text\n<script>\n```\n\n```text\ncontext=\"module\"\n```\n\n========================================\n\nComments:\n- AFAIK, unlike `onMount` which is called once per component instance, the `context=\"module\"` script is only executed once.\n- You didn't answer how `context='module'` works.","metadata":{"transformedAt":"2026-08-18T18:33:40.656Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":120,"estimatedTokens":799}}51{"id":"stack-67568323","source":"stackoverflow","questionId":67568323,"title":"How can I send secure API requests from SvelteKit app, without showing API keys on the client side?","tags":["javascript","svelte","sveltekit","supabase"],"text":"Title: How can I send secure API requests from SvelteKit app, without showing API keys on the client side?\nTags: javascript, svelte, sveltekit, supabase\nSource: Stack Overflow\n\nQuestion:\nI'm using Supabase for a new Sveltekit app, with this template\n\nCurrently, I'm passing the Supabase keys through on the client side, like this:\n\n```\nconst supabase = createClient(\n import.meta.env.VITE_SUPABASE_URL,\n import.meta.env.VITE_SUPABASE_ANON_KEY\n)\n```\n\nWhat is the simplest way that I can create a secure backend/API, so the application can fetch content from Supabase, without showing Supabase key on the client side?\n\nIs there any functionality built into Sveltekit that enables me to do this? Or would I need to integrate a backend like Rails?\n\n========================================\n\nCode:\n```text\nconst supabase = createClient(\n import.meta.env.VITE_SUPABASE_URL,\n import.meta.env.VITE_SUPABASE_ANON_KEY\n)\n```\n\n```text\nlocals\n```\n\n```text\nload()\n```\n\n```text\n<script context=\"module\">\n```\n\n```text\n<script>\n```\n\n```text\nfetch()\n```\n\n```text\nload()\n```\n\n```text\nload()\n```\n\n```text\nfetch()\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.656Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":61,"estimatedTokens":275}}52{"id":"stack-47030034","source":"stackoverflow","questionId":47030034,"title":"Reasons for using svelte js","tags":["reactjs","web","vue.js","svelte"],"text":"Title: Reasons for using svelte js\nTags: reactjs, web, vue.js, svelte\nSource: Stack Overflow\n\nQuestion:\nI found the Svelte framework these days. What do you think about using it instead of React.js or Vue.js?\n\nI didn't use it at all so I don't understand the deep difference between them. I have read that Svelte much faster, but it doesn't have certain support for state storing like redux and so on. So what can you say about this?\nI tried to find some more info about the advantages and disadvantages but it was in vain.\n\n========================================\n\nComments:\n- This statement isn't true *\"rather than interpreting your application code at run time, your app is converted into ideal JavaScript at build time\"*, this is exactly what vue's single file components are\n- @craig_h I'm afraid you're entirely wrong. Vue's SFCs can be compiled to an *intermediate representation*, which still needs Vue itself in order to do any work. It reduces *some* client-side work (no need to parse the template), but that's all. Svelte's components, by contrast, are converted into raw code. They're completely different ideas.\n- @RichHarris Thanks for clarifying that point, I hadn't considered that but it is a crucial difference, sorry if that came across a bit judgy I hadn't had my morning cup of tea! Anyway, it looks like a great project. Good luck with it :)\n- Thank you for reply! I will try to create a project and test it))\n- @Rich Harris Do you know of any slightly complicated site built with Svetle already ?\n- @MariánZekeŠedaj not off the top of my head — you could ask around in gitter.im/sveltejs/svelte\n- Fast-forward to 2021, the official website of Radio France is being redone in Svelte. Here's the Beta version in Svelte which is still a WIP as of today.\n- Mr @RichHarris, You've made a Beast!, I migrated to Svelte After 3 years using React, The built-in state management system in Svelte is the simplest and powerful system ever built","metadata":{"transformedAt":"2026-08-18T18:33:40.657Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":21,"estimatedTokens":491}}53{"id":"stack-61680363","source":"stackoverflow","questionId":61680363,"title":"SassError: media query expression must begin with '('","tags":["css","reactjs","vue.js","svelte","sass-loader"],"text":"Title: SassError: media query expression must begin with '('\nTags: css, reactjs, vue.js, svelte, sass-loader\nSource: Stack Overflow\n\nQuestion:\nI had this problem even I didn't manage to sleep, guys\n\nmy codes are like these\n\n```\n\n @import '~/assets/scss/main.scss'\n .home_nav{\n nav {\n\n }\n }\n\n```\n\nthe error is\n\nhttps://i.sstatic.net/oSF7k.png\n\nplease, someone, to help me\n\n========================================\n\nTop Answer:\nI had same problem. You are missing semicolon **;** in the end of your import.\n\n```\n**@import \"./common/colors.scss\";**\n\n* {\n margin:0;\n padding:0;\n box-sizing: border-box;\n font-family: \"Open Sans\";\n}\n```\n\n========================================\n\nCode:\n```text\n<style lang=\"scss\" scoped>\n @import '~/assets/scss/main.scss'\n .home_nav{\n nav {\n\n }\n }\n</style>\n```\n\n```text\n<style lang=\"scss\" scoped>\n @import '~/assets/scss/main.scss';\n .home_nav{\n nav {\n\n }\n }\n</style>\n```\n\n```text\n;\n```\n\n```text\n@import '~/assets/scss/main.scss'\n```\n\n```text\nvue.js\n```\n\n```text\nVue\n```\n\n```text\nnode-sass\n```\n\n```text\nsass-loader\n```\n\n```text\nsass\n```\n\n```text\n**@import \"./common/colors.scss\";**\n\n* {\n margin:0;\n padding:0;\n box-sizing: border-box;\n font-family: \"Open Sans\";\n}\n```\n\n========================================\n\nComments:\n- Same problem, thanks! The node-sass parser and the error message could be better... :-D\n- Damn, you saved my time :)","metadata":{"transformedAt":"2026-08-18T18:33:40.657Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":111,"estimatedTokens":357}}54{"id":"stack-61131591","source":"stackoverflow","questionId":61131591,"title":"Can a Svelte component be embedded in a non-Svelte app?","tags":["embed","svelte","svelte-component"],"text":"Title: Can a Svelte component be embedded in a non-Svelte app?\nTags: embed, svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI work in a group that has several projects, and each one is written in a different framework. We would like to have some self-contained widgets whose behavior and appearance are standard, but can be used in any of the systems. I thought Svelte sounded like a good option, because it doesn't require adding a framework on the front end. But I can't find anything that says Svelte is usable within other systems; it has to be an all-Svelte app to have Svelte components.\n\nIs that correct? Or is there some way to embed a Svelte component into another system?\n\n========================================\n\nTop Answer:\nIf you want even wider compatibility and just include the component with a `script` tag, you can use the `document.currentScript` property and compile the Javascript into standalone script with rollup.js or webpack:\n\n```\nimport MyComponent from './MyComponent.svelte';\n\nvar div = document.createElement('DIV');\nvar script = document.currentScript;\nscript.parentNode.insertBefore(div, script);\n\nconst myComponent = new MyComponent({\n target: div,\n props: { propname: 'some value' },\n});\n```\n\nYou can compile a nice package with rollup if you have `rollup-plugin-svelte` and `@rollup/plugin-node-resolve` packages installed into your project. Below is a suitable rollup.config.js for this, added further notes into comments:\n\n```\nimport svelte from 'rollup-plugin-svelte';\nimport resolve from '@rollup/plugin-node-resolve';\n\nexport default {\n input: 'embed.js',\n output: {\n format: 'iife',\n file: 'dist.js',\n sourcemap: false,\n },\n plugins: [\n svelte({ emitCss: false, }),\n resolve({ browser: true, dedupe: ['svelte'] }),\n ],\n}\n```\n\n========================================\n\nCode:\n```js\nconst container = document.querySelector('.container');\n\n//MyComponent is the compiled component\nnew MyComponent({\n target : container\n});\n```\n\n```js\nimport MyComponent from './MyComponent.svelte';\n\nvar div = document.createElement('DIV');\nvar script = document.currentScript;\nscript.parentNode.insertBefore(div, script);\n\nconst myComponent = new MyComponent({\n target: div,\n props: { propname: 'some value' },\n});\n```\n\n```js\nimport svelte from 'rollup-plugin-svelte';\nimport resolve from '@rollup/plugin-node-resolve';\n\nexport default {\n input: 'embed.js',\n output: {\n format: 'iife',\n file: 'dist.js',\n sourcemap: false,\n },\n plugins: [\n svelte({ emitCss: false, }),\n resolve({ browser: true, dedupe: ['svelte'] }),\n ],\n}\n```\n\n```text\nscript\n```\n\n```text\ndocument.currentScript\n```\n\n```text\nrollup-plugin-svelte\n```\n\n```text\n@rollup/plugin-node-resolve\n```\n\n```text\n<svelte:options tag=\"component-name\"/>\n```\n\n========================================\n\nComments:\n- Svelte components can also be compiled to custom elements (aka web components). More here: svelte.dev/docs#Custom_element_API\n- A more in-depth tutorial available on my website with tool specifics. Most stackoverflowers should be adept enough with the above answer though :)","metadata":{"transformedAt":"2026-08-18T18:33:40.657Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":115,"estimatedTokens":782}}55{"id":"stack-78664060","source":"stackoverflow","questionId":78664060,"title":"How do we do \"named slots\" in in Svelte 5?","tags":["javascript","signals","svelte","sveltekit","svelte-5"],"text":"Title: How do we do \"named slots\" in in Svelte 5?\nTags: javascript, signals, svelte, sveltekit, svelte-5\nSource: Stack Overflow\n\nQuestion:\n### Svelte 5 Slots are Confusing\n\nNow, with Svelte 5 at pre-release, I feel I can express some confusion about slots in Svelte 5. In Svelte 4, slot and names slots where done in the following way:\n\n### `ContactCard.svelte`\n\n```\n\n \n \n Unknown name\n \n \n\n \n \n Unknown address\n \n \n\n \n \n Unknown email\n \n \n\n...\n```\n\n### `+page.svelte`\n\n```\n\n import ContactCard from './ContactCard.svelte';\n\n P. Sherman \n\n \n 42 Wallaby Way\n\n Sydney\n \n\n```\n\nPretty easy and straight forward in my humble opinion.\n\n### Svelte 5 **Single Slot** example\n\n### `Component.svelte`\n\n```\n\n let { children } = $props();\n\n {@render children()}\n\n```\n\n### `+page.svelte`\n\n```\n\n import { Component } from '$lib';\n\n ...content...\n\n```\n\nAlso easy...\n\n### My Question...\n\nHow do we do \"named slots\" in this new paradigm\n\n========================================\n\nCode:\n```js\n<article class=\"contact-card\">\n <h2>\n <slot name=\"name\">\n <span class=\"missing\">Unknown name</span>\n </slot>\n </h2>\n\n <div class=\"address\">\n <slot name=\"address\">\n <span class=\"missing\">Unknown address</span>\n </slot>\n </div>\n\n <div class=\"email\">\n <slot name=\"email\">\n <span class=\"missing\">Unknown email</span>\n </slot>\n </div>\n</article>\n\n<style>...</style>\n```\n\n```js\n<script>\n import ContactCard from './ContactCard.svelte';\n</script>\n\n<ContactCard>\n <span slot=\"name\"> P. Sherman </span>\n\n <span slot=\"address\">\n 42 Wallaby Way<br />\n Sydney\n </span>\n</ContactCard>\n```\n\n```js\n<script>\n let { children } = $props();\n</script>\n\n<div>\n {@render children()}\n</div>\n```\n\n```js\n<script>\n import { Component } from '$lib';\n</script>\n\n<Component>\n ...content...\n</Component>\n```\n\n```text\nContactCard.svelte\n```\n\n```text\n+page.svelte\n```\n\n```text\nComponent.svelte\n```\n\n```text\n+page.svelte\n```\n\n```html\n<script>\n import ContactCard from './ContactCard.svelte';\n</script>\n\n<ContactCard>\n {#snippet name()} P. Sherman {/snippet}\n\n {#snippet address()}\n 42 Wallaby Way <br>\n Sydney\n {/snippet}\n</ContactCard>\n```\n\n```html\n<!-- ContactCard.svelte -->\n<script>\n let { name, address } = $props();\n</script>\n\n<div>\n <div class=\"name\">{@render name()}</div>\n <div class=\"address\">{@render address()}</div>\n</div>\n```\n\n```html\n<div class=\"name\">\n {@render name?.()}\n {#if !name}\n ...\n {/if}\n</div>\n```\n\n```html\n<div class=\"name\">\n {#snippet nameUnknown()}...{/snippet}\n {@render (name ?? nameUnknown)()}\n</div>\n```\n\n```html\n{#snippet name()} P. Sherman {/snippet}\n{#snippet address()}\n 42 Wallaby Way <br>\n Sydney\n{/snippet}\n<ContactCard {name} {address} />\n```\n\n```html\n<FancyList items={users}>\n {#snippet children(item)}\n {item.lastName}, {item.firstName}\n {/snippet}\n</FancyList>\n```\n\n```html\n<script lang=\"ts\">\n import type { Snippet } from 'svelte';\n let { name, address }: {\n name: Snippet,\n address?: Snippet,\n } = $props();\n</script>\n```\n\n```html\n<script lang=\"ts\" generics=\"T\">\n import type { Snippet } from 'svelte';\n let { items, itemTemplate }: {\n items: T[],\n itemTemplate: Snippet<[T]>,\n } = $props();\n</script>\n\n<div class=\"list\">\n {#each items as item}\n <div class=\"item\">{@render itemTemplate(item)}</div>\n {/each}\n</div>\n```\n\n```text\n#snippet\n```\n\n```text\nspan\n```\n\n```text\n{#if}\n```\n\n```text\nchildren\n```\n\n```text\nitemTemplate\n```\n\n```text\nSnippet\n```\n\n```text\n'svelte'\n```\n\n```text\n?\n```\n\n========================================\n\nComments:\n- So, they can not be used in layout files.\n- If you are referring to SvelteKit layouts, they never had anything but the default slot anyway.","metadata":{"transformedAt":"2026-08-18T18:33:40.657Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":24,"totalLines":281,"estimatedTokens":955}}56{"id":"stack-61598941","source":"stackoverflow","questionId":61598941,"title":"How to scope querySelector to component in Svelte?","tags":["svelte","svelte-component"],"text":"Title: How to scope querySelector to component in Svelte?\nTags: svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI have this component, andI would like to do some manipulations on its children elements in ways that are not feasible in a state-driven way. So I would like to use a statement and a `querySelector` in it. But how can I scope it to the element? There are multiple instances of the component in the page, so a class or id is not possible. How can I achieve this?\n\nHere's a simplified code:\n\n```\n\n export let value = ''\n export let readonly = true\n\n $: if (value && !readonly){\n // selects the first element in the document, not the one from this instance \n const nd = document.querySelector('.forminput')\n // Do something with nd\n }\n \n\n \n```\n\n========================================\n\nTop Answer:\nBuilding on the answer by Stephane Vanraes, use `bind:this` to bind the top-level element of your component to a variable and then use `querySelector` and `querySelectorAll` on that root element. For example:\n\n```\n\n import { onMount } from 'svelte';\n let root;\n let text;\n let value;\n\n onMount(() => {\n const nd = root.querySelectorAll('.forminput');\n // Do something with nd, such as adding event listeners, styles, etc.\n });\n\n \n \n\n```\n\nYou can then get the full power of `querySelector` scoped to your component.\n\nNote that `root` is properly bound only after the component has been mounted, thus the encapsulation of the code in the `onMount` function.\n\n========================================\n\nCode:\n```js\n<script>\n export let value = ''\n export let readonly = true\n\n $: if (value && !readonly){\n // selects the first element in the document, not the one from this instance \n const nd = document.querySelector('.forminput')\n // Do something with nd\n }\n </script>\n\n <textarea bind:value wrap=\"soft\" rows=\"1\" class=\"forminput\"></textarea>\n```\n\n```text\nquerySelector\n```\n\n```html\n<script>\n let wrapper;\n</script>\n\n<div bind:this=\"{wrapper}\"></div>\n```\n\n```text\nbind:this\n```\n\n```text\nwrapper\n```\n\n```text\n<script>\n import { onMount } from 'svelte';\n let root;\n let text;\n let value;\n\n onMount(() => {\n const nd = root.querySelectorAll('.forminput');\n // Do something with nd, such as adding event listeners, styles, etc.\n });\n</script>\n\n<div bind:this={root}>\n <input type=\"text\" bind:value class=\"forminput\"/>\n <textarea bind:text wrap=\"soft\" rows=\"1\" class=\"forminput\"></textarea>\n</div>\n```\n\n```text\nbind:this\n```\n\n```text\nquerySelector\n```\n\n```text\nquerySelectorAll\n```\n\n```text\nquerySelector\n```\n\n```text\nroot\n```\n\n```text\nonMount\n```\n\n========================================\n\nComments:\n- Answer not clear, please add context.\n- This was useful for doing a simple port of a native HTML page to Svelte. Thanks!\n- This should be the accepted answer IMO as it does not actually answer the original question \"How do I scope `querySelector` to an element/component?\". While Stephane's answer is extremely useful and in most situations the recommended way there are times it won't work, i.e. bind a to a list inside an `{#each ...}` block that changes.\n- @Jadams you can bind in a list using the index or a unique prop `bind:this={inputs[id]` with inputs an array or object in your script tag","metadata":{"transformedAt":"2026-08-18T18:33:40.657Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":138,"estimatedTokens":818}}57{"id":"stack-67803116","source":"stackoverflow","questionId":67803116,"title":"How to type cast Svelte 3 reactive syntax variables?","tags":["typescript","casting","svelte","svelte-3"],"text":"Title: How to type cast Svelte 3 reactive syntax variables?\nTags: typescript, casting, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI don't know how to type Svelte 3 reactive syntax variables.\n\n```\n\n import type { Player, Team } from \"./types\";\n\n import { DEFAULT_PLAYER } from \"./utils\";\n\n $: player = DEFAULT_PLAYER as Player;\n $: team = { search: \"Real\", players: [] } as Team;\n\n```\n\nBut this doesn't work:\n\n```\n'Team' cannot be used as a value because it was imported using 'import type'.ts(1361)\n```\n\nIf I use this instead:\n\n```\n$: team = ({ search: \"Real\", players: [] } as Team);\n```\n\nthe VSCode extension `svelte.svelte-vscode` format it like the first one when I save.\n\nIs this my fault?\n\nIs there a better way to cast those reactive vars?\n\n========================================\n\nTop Answer:\nWhen working with TypeScript in 2023, it is recommended to use the `satisfies` operator for better type safety. Consider the following code snippet:\n\n```\n\n import type { Player, Team } from \"./types\";\n import { DEFAULT_PLAYER } from \"./utils\";\n\n $: player = DEFAULT_PLAYER satisfies Player;\n $: team = { search: \"Real\", players: [] } satisfies Team;\n\n```\n\nThis approach offers improved conciseness and avoids the need for redundant declarations.\n\nPreviously, I encountered issues while using the `let` method, as it didn't provide strict enforcement of object properties. For instance, the following failure is correctly identified:\n\n```\ntype A = { a: string };\nlet a: A;\n$: a = { a: 2 };\n```\n\nHowever, the following case does not cause a type error **even though it should**:\n\n```\ntype A = { a: string };\nlet a: A;\n$: a = { a: 'a', b: 'b' };\n```\n\nThis situation poses a significant problem, as it allows unintended properties to be added to objects.\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n import type { Player, Team } from \"./types\";\n\n import { DEFAULT_PLAYER } from \"./utils\";\n\n $: player = DEFAULT_PLAYER as Player;\n $: team = { search: \"Real\", players: [] } as Team;\n</script>\n```\n\n```text\n'Team' cannot be used as a value because it was imported using 'import type'.ts(1361)\n```\n\n```text\n$: team = ({ search: \"Real\", players: [] } as Team);\n```\n\n```text\nsvelte.svelte-vscode\n```\n\n```text\n<script lang=\"ts\">\n import type { Player, Team } from \"./types\";\n\n import { DEFAULT_PLAYER } from \"./utils\";\n\n let player: Player;\n $: player = DEFAULT_PLAYER;\n let team: Team;\n $: team = { search: \"Real\", players: [] };\n</script>\n```\n\n```text\n<script lang='ts'>\n let team: Team;\n $: team = { search: \"Real\", players: [] }\n</script>\n```\n\n```text\nas\n```\n\n```text\nas\n```\n\n```html\n<script lang=\"ts\">\n import type { Player, Team } from \"./types\";\n\n import { DEFAULT_PLAYER } from \"./utils\";\n\n let team: Team; // added this\n $: player = DEFAULT_PLAYER as Player;\n $: team = { search: \"Real\", players: [] };\n</script>\n```\n\n```html\n<script lang=\"ts\">\n import type { Player, Team } from \"./types\";\n import { DEFAULT_PLAYER } from \"./utils\";\n\n $: player = DEFAULT_PLAYER satisfies Player;\n $: team = { search: \"Real\", players: [] } satisfies Team;\n</script>\n```\n\n```js\ntype A = { a: string };\nlet a: A;\n$: a = { a: 2 };\n```\n\n```js\ntype A = { a: string };\nlet a: A;\n$: a = { a: 'a', b: 'b' };\n```\n\n```text\nsatisfies\n```\n\n```text\nlet\n```\n\n========================================\n\nComments:\n- @Nick answered correctly at the time he did it. But your answer is definitely should be in top now, thanks!\n- This was probably a bug because your last example does cause a type error for me. I downvoted this answer because `satisfies` only affects the value and not the variable, which can create issues in some cases like empty arrays: if you use `let a = [] satisfies SomeType[]`, the type of `a` is `any[]`, not `SomeType[]`.","metadata":{"transformedAt":"2026-08-18T18:33:40.657Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":172,"estimatedTokens":945}}58{"id":"stack-72407572","source":"stackoverflow","questionId":72407572,"title":"Idiomatic way in Svelte to do two way binding with an intermediate transformation","tags":["svelte"],"text":"Title: Idiomatic way in Svelte to do two way binding with an intermediate transformation\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nTwo way binding is great and elegant in Svelte, but a recurrent situation I've come across is needing two way binding with an intermediate transformation that converts types or does some kind of clean up. For example:\n\n- Binding to a select component's prop `value` that has the form `{value, label}`, but its parent just handles a value\n\n- Type conversions, where a `` is also input for some other type (Number, date, custom one), or an input to edit an object as JSON that could also be changed from the outside.\n\n**My question is: Which is a good, idiomatic and simple way of solving this pattern in Svelte?**\n\nThe best reusable solution I've found so far has been to create a *store factory* for one-to-one transformations that returns two stores, `a` and `b` which you can then use and bind to other components:\n\nExample: play with REPL here\n\n```\n// App.svelte\n\n import oneToOne from './oneToOne.js'\n \n const f = x => JSON.stringify({x});\n const fInv = x => {try{return JSON.parse(x).x} catch(err){return NaN}};\n \n let [a, b] = oneToOne(13, f, fInv); \n\nA: \nB: \n```\n\n```\n// oneToOne.js\nimport { writable } from 'svelte/store';\n\nconst identity = x => x;\n\nexport default function oneToOne(val, f = identity, fInv = identity) {\n let fInvB = val;\n let fA = f(val);\n \n const A = writable(fInvB);\n const B = writable(fA);\n \n B.subscribe((b) => { \n if(fA !== b && !(Number.isNaN(fA) && Number.isNaN(b))) { \n fInvB = fInv(b);\n fA = b; \n A.set(fInvB)\n }\n }); \n \n A.subscribe((a) => { \n if(fInvB !== a && !(Number.isNaN(fInvB) && Number.isNaN(a))) { \n fA = f(a); \n fInvB = a; \n B.set(fA)\n }\n }); \n\n return [A, B];\n}\n```\n\nDoes this make sense? Am I missing a simpler way of doing this or avoiding this complexity altogether?\n\n========================================\n\nTop Answer:\nDefining two stores at the same time seems a bit unnecessary, depending on intended semantics. It could also be approached as there being one source and a derived store.\n\n```\n\n import { transformed } from './transform-store.js';\n import { writable } from 'svelte/store';\n\n const number = writable(13);\n const json = transformed(number, {\n in: value => JSON.stringify({ x: value }),\n out: value => { try { return JSON.parse(value).x; } catch(err) { return NaN; } },\n });\n\nNumber to JSON:\n\n```\n\n`transform-store.js`\n\n```\nimport { derived } from 'svelte/store';\n\nexport function transformed(store, options) {\n const identity = x => x;\n const transformIn = options.in ?? identity;\n const transformOut = options.out ?? identity;\n \n const { subscribe } = derived(store, $store => transformIn($store));\n const set = value => store.set(transformOut(value));\n \n return { subscribe, set };\n}\n```\n\nREPL\n\nThe transformed store is essentially a derived store augmented to be writable by defining its own `set` function that modifies the source store.\n\nThis can also be done without stores by using reactive statements and property descriptors:\n\n```\n\n function transformed(get, set) {\n const o = {};\n Object.defineProperty(o, 'value', { get, set });\n \n return o;\n }\n\n let number = 13;\n $: json = transformed(\n () => JSON.stringify({ x: number }),\n value => { try { number = JSON.parse(value).x; } catch(err) { number = NaN; } }, \n )\n\nNumber to JSON:\n\n```\n\nREPL\n\nIdeally there would just be built-in language support for this, though.\n\n========================================\n\nCode:\n```svelte\n// App.svelte\n<script>\n import oneToOne from './oneToOne.js'\n \n const f = x => JSON.stringify({x});\n const fInv = x => {try{return JSON.parse(x).x} catch(err){return NaN}};\n \n let [a, b] = oneToOne(13, f, fInv); \n</script>\n\nA: <input bind:value={$a}/>\nB: <input bind:value={$b}/>\n```\n\n```svelte\n// oneToOne.js\nimport { writable } from 'svelte/store';\n\nconst identity = x => x;\n\nexport default function oneToOne(val, f = identity, fInv = identity) {\n let fInvB = val;\n let fA = f(val);\n \n const A = writable(fInvB);\n const B = writable(fA);\n \n B.subscribe((b) => { \n if(fA !== b && !(Number.isNaN(fA) && Number.isNaN(b))) { \n fInvB = fInv(b);\n fA = b; \n A.set(fInvB)\n }\n }); \n \n A.subscribe((a) => { \n if(fInvB !== a && !(Number.isNaN(fInvB) && Number.isNaN(a))) { \n fA = f(a); \n fInvB = a; \n B.set(fA)\n }\n }); \n\n return [A, B];\n}\n```\n\n```text\nvalue\n```\n\n```text\n{value, label}\n```\n\n```text\n<input type=text>\n```\n\n```text\na\n```\n\n```text\nb\n```\n\n```svelte\n<script>\n let a = 13, b;\n const f = x => b = JSON.stringify({x});\n const fInv = x => {try{a = JSON.parse(x).x} catch(err){a = NaN}};\n \n $: f(a);\n $: fInv(b); \n</script>\n\nA: <input bind:value={a}/>\nB: <input bind:value={b}/>\n```\n\n```text\nin\n```\n\n```text\nout\n```\n\n```text\nf(x)\n```\n\n```text\nfInv(x)\n```\n\n```text\nf(fInv(x)) !== x\n```\n\n```text\nfInv\n```\n\n```text\nNaN\n```\n\n```text\na\n```\n\n```text\nb\n```\n\n```text\n{x: null}\n```\n\n```text\noneToOne.js\n```\n\n```text\nNaN\n```\n\n```text\nNaN\n```\n\n```html\n<script>\n import { transformed } from './transform-store.js';\n import { writable } from 'svelte/store';\n\n const number = writable(13);\n const json = transformed(number, {\n in: value => JSON.stringify({ x: value }),\n out: value => { try { return JSON.parse(value).x; } catch(err) { return NaN; } },\n });\n</script>\n\nNumber to JSON:\n<input bind:value={$number} type=\"number\" />\n<input bind:value={$json} />\n```\n\n```js\nimport { derived } from 'svelte/store';\n\nexport function transformed(store, options) {\n const identity = x => x;\n const transformIn = options.in ?? identity;\n const transformOut = options.out ?? identity;\n \n const { subscribe } = derived(store, $store => transformIn($store));\n const set = value => store.set(transformOut(value));\n \n return { subscribe, set };\n}\n```\n\n```html\n<script>\n function transformed(get, set) {\n const o = {};\n Object.defineProperty(o, 'value', { get, set });\n \n return o;\n }\n\n let number = 13;\n $: json = transformed(\n () => JSON.stringify({ x: number }),\n value => { try { number = JSON.parse(value).x; } catch(err) { number = NaN; } }, \n )\n</script>\n\nNumber to JSON:\n<input bind:value={number} type=\"number\" />\n<input bind:value={json.value} />\n```\n\n```text\ntransform-store.js\n```\n\n```text\nset\n```\n\n```html\n<script>\nlet value = 13\n\nfunction setA(string) {\n value = parseInt(value, 10);\n}\n\nfunction setB(json) {\n value = JSON.parse(json)?.x\n}\n</script>\n\nA: <input value=\"{value}\" on:input={ (e) => setA(e.target.value) }/>\nB: <input value={{ x: value }} on:input={ (e) => setB(e.target.value) }/>\n```\n\n```text\n<select bind:value={() => difficultyMapToCZ[gameInfo.apiResponse.difficulty], /*get*/\n (v) => gameInfo.apiResponse.difficulty = difficultyMapToEN[v] /*set*/}> \n <option>a</option>\n <option>b</option>\n</select>\n```\n\n```text\ndifficultyMapToCZ\n```\n\n```text\ndifficultyMapToEN\n```\n\n```html\n<script>\n let a = $state(13)\n const f = x => JSON.stringify({x});\n const fInv = x => {try{return JSON.parse(x).x} catch(err){return NaN}};\n let internal = {\n get value() { return f(a)},\n set value(newV) { a = fInv(newV) }\n }\n\n</script>\n<input bind:value={internal.value} />\n<input bind:value={a} />\n```\n\n```text\nVD <-f-> IS\n```\n\n========================================\n\nComments:\n- There are also issues on GitHub about this problem: #3937, #7265\n- Great, your `transform-store.js` is definitely a clever improvement over mine! The get/set version, however, doesn't feel very idiomatic to me. I had also missed one of the github issue you mentioned, and there was a very interesting and simple answer I missed there without using stores! I'll reproduce it in an answer of its own because I think it is worth it. In all versions, however, there is an interesting corner case when transformations are asymetrical (NaN case), where my first example does not have reentrancy, but other do. Not sure which would be a reasonable semantic.\n- @Hutzz The get/set is just a workaround. As noted this should just be supported by Svelte directly to obsolete the use of stores, multiple reactive statements or the get/set wrapper.\n- I am not a fan of this approach because it uses multiple dependent reactive statements which makes it harder to track what is going on and it creates more variables in scope that are only there for the transform. In my answer there only is ever one additional variable in scope that fully encapsulates its transform.\n- It is true what you point about the variables, but I'm not sure it outweights having a dependency, two extra imports and store variables around. However, I do agree with the fact that reactive statements pose some issues: the order in which you write them determines whether there is a single reentrant update after updating A or B, depending on the order. Thats the only part that I don't really like...\n- It doesn't make sense if variables are nested inside of HTML. Svelte uses very nested. For instance I want to use column index `{#if parseInt(cell)} {parseInt(cell) * $FilteredColumnsProcess[columnIndex]} {/if}`\n- It's a super valid option, but it obviously defeats the purpose of taking adavantage of Svelte's two way bindings. As you correctly pointed out, that implies adding `onchange` events to custom components which is part of the verbosity I was trying to avoid (even though it is debatable whether it is a good idea to have custom input components that solely rely on the implicit data flow of binding its value).\n- Wouln't it be better to directly use bind function getters/setters in Svelte 5? Like this svelte.dev/playground/… `(...) (...)` You can see the doc here: svelte.dev/docs/svelte/bind#Function-bindings\n- Yeah in my example code that would make sense since you already have the `f` and `fInv` defined. Similar to what Petr L. suggested. Sometimes it is convenient to use the getter/setter approach since you get the nice grouping of the two functions in one object, no need to remember about two different function names. `let internal = { get value() { return JSON.stringify({x});}, set value(newV) { try{a = JSON.parse(x).x} catch(err){return NaN}} }`","metadata":{"transformedAt":"2026-08-18T18:33:40.657Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":394,"estimatedTokens":2596}}59{"id":"stack-59994448","source":"stackoverflow","questionId":59994448,"title":"How to solve (plugin postcss) Error: File to import not found or unreadable: smui-theme. Material UI Svelte project","tags":["sass","material-ui","svelte","rollupjs"],"text":"Title: How to solve (plugin postcss) Error: File to import not found or unreadable: smui-theme. Material UI Svelte project\nTags: sass, material-ui, svelte, rollupjs\nSource: Stack Overflow\n\nQuestion:\nI am integrating Material UI into a Svelte project.\n\nI everything from the documentation, but I get this error when running my project:\n\n```\n!] (plugin postcss) Error: File to import not found or unreadable: smui-theme.\nnode_modules/@smui/tab/_index.scss\nError: File to import not found or unreadable: smui-theme.\n```\n\nWhat can be the problem?\n\n========================================\n\nCode:\n```text\n!] (plugin postcss) Error: File to import not found or unreadable: smui-theme.\nnode_modules/@smui/tab/_index.scss\nError: File to import not found or unreadable: smui-theme.\n```\n\n```text\nimport postcss from 'rollup-plugin-postcss';\n\nexport default {\n ...\n plugins: [\n svelte({\n ...\n }),\n\n ....\n\n postcss({\n extract: true,\n minimize: true,\n use: [\n ['sass', {\n includePaths: [\n './src/theme', <<< ------------ HERE \n './node_modules'\n ]\n }]\n ]\n }),\n ...\n};\n```\n\n```text\n_smui-theme.scss\n```\n\n```text\n_smui-theme.scss\n```\n\n```text\ntheme\n```\n\n```text\nsrc/theme/_smui-theme.scss\n```\n\n```text\npostcss\n```\n\n```text\ntheme\n```\n\n```text\npostcss\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.657Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":81,"estimatedTokens":366}}60{"id":"stack-64959908","source":"stackoverflow","questionId":64959908,"title":"Svelte component onLoad","tags":["javascript","svelte"],"text":"Title: Svelte component onLoad\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nIs there a way to know when a Svelte component has finished loading all its external resources, rather than `onMount`?\n\nIt is similar to the `onload` event of `window`.\n\nEDIT: To clear things up, I would like a component to do something after it fully loads all its images.\n\nEDIT2: I decided to use javascript to load images. In my opinion, this is not the cleanest way to do things, but it works.\nThank you!\n\n========================================\n\nCode:\n```text\nonMount\n```\n\n```text\nonload\n```\n\n```text\nwindow\n```\n\n```html\n<script>\n let waiting = 0\n \n const notifyLoaded = () => {\n console.log('loaded!')\n }\n \n const onload = el => {\n waiting++\n el.addEventListener('load', () => {\n waiting--\n if (waiting === 0) {\n notifyLoaded()\n }\n })\n }\n</script>\n\n<img use:onload src=\"https://place-hold.it/320x120\" alt=\"placeholder\" />\n\n<img use:onload src=\"https://place-hold.it/120x320\" alt=\"placeholder\" />\n```\n\n```js\nexport const createLoadObserver = handler => {\n let waiting = 0\n\n const onload = el => {\n waiting++\n el.addEventListener('load', () => {\n waiting--\n if (waiting === 0) {\n handler()\n }\n })\n }\n \n return onload\n}\n```\n\n```html\n<script>\n import { createLoadObserver } from './util.js'\n \n const onload = createLoadObserver(() => {\n console.log('loaded!!!')\n })\n</script>\n\n<img use:onload src=\"https://place-hold.it/320x120\" alt=\"placeholder\" />\n\n<img use:onload src=\"https://place-hold.it/120x320\" alt=\"placeholder\" />\n```\n\n```text\nutil.js\n```\n\n```text\nApp.svelte\n```\n\n========================================\n\nComments:\n- `handleonload()}\"/>` more info svelte.dev/tutorial/svelte-window\n- Thank you @dagalti! But my problem with this is: when I go to another route and go back, this `on:load` function, unlike `onMount`, is not triggered. Any way to work around this?\n- What do you mean by 'external resources'?\n- For my case: images.\n- That's exactly what I needed! Thank you!\n- I want to use a pattern like this. However, I don't know the image src URLs until runtime.","metadata":{"transformedAt":"2026-08-18T18:33:40.657Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":102,"estimatedTokens":563}}61{"id":"stack-72579031","source":"stackoverflow","questionId":72579031,"title":"How to Fetch Data inside SvelteKit Component that Is Not a Page","tags":["svelte","sveltekit","svelte-component"],"text":"Title: How to Fetch Data inside SvelteKit Component that Is Not a Page\nTags: svelte, sveltekit, svelte-component\nSource: Stack Overflow\n\nQuestion:\n*SvelteKit v1.0.0-next.324*\n\nI have a SvelteKit component that is used in multiple places in my app, and it needs to fetch its own data from one of my endpoints.\n\nI read this question that states I can't have a `load` function unless it's a page. Assuming I cannot make this a page and import it into another page, I need to be able to fetch data into this component on its own.\n\n```\n\nimport { onMount } from 'svelte'\nimport type { Aircraft } from '$lib/models'\n \nlet aircrafts: Aircraft[]\n\nonMount(async() => {\n aircrafts = await (await fetch('/aircrafts')).json()\n console.log(aircrafts) //\n \n{aircrafts.length} Aircraft\n\n //My `/aircrafts` endpoint returns data just fine, and the `console.log` shows the data. But down in my HTML, `aircrafts.length` shows `undefined Aircraft`.\n\nI assume this is because `onMount` happens after the props are set and the data isn't actually getting updated.\n\nHow can I pull data into a standalone component?\n\n========================================\n\nTop Answer:\nThis issue you are having is that you need to get the data asynchronously and **THEN** render it to the page. Svelte makes this easy with the `await` markups helper.\n\nThe example case looks like this:\n\n```\n{#await promise}\n ...waiting\n\n{:then number}\n The number is {number}\n\n{:catch error}\n {error.message}\n\n{/await}\n```\n\nThe `number` in the above example is the *result* of the resolved promise.\n\nSo you your markup, you can try this:\n\n```\n\n async function getAircrafts() {\n const res = await fetch('/aircrafts');\n const values = await res.json();\n\n return values;\n }\n \n // NOTE await not used here! \n let aircraftsPromise = getAircrafts();\n\n \n{#await aircraftsPromise }\n ...waiting\n\n{:then aircrafts}\n {aircrafts.length} Aircraft\n\n{:catch error}\n {error.message}\n\n{/await}\n```\n\nWhat this does is give you a UI state for while the promise is running, as `aircraftsPromise`, then a state that passes the *result* of that promise for use in the markup, in `aircrafts`. Any errors hit the third UI state and get rendered.\n\nIn the `{:then ... }` block you are interacting with the resolved values, which is your array that you are looking for. You can then do whatever you want with it.\n\n**EDIT** I forgot to link to the documentation on this. Official Svelte docs on the await blocks are here.\n\n**EDIT 2**\n\nAfter revisiting this and also needing something similar in a project, I came across a way to add reactivity to the promise using an IIFE. This takes advantage of the svelte syntax to update the value of the promise based on a change in parameter used to calculate the promise, for example if you needed to update state based on an ID for an aircraft.\n\n```\n\n export let id: string; // Mutating this will cause function below to re-run\n\n $: aircraftPromise = (async function getAircraftById(aircraftID: string) {\n // Asuming API has a route for '/aircrafts/id'\n // and 'id' is a url path param\n const res = await fetch('/aircrafts/' + aircraftID);\n const value = await res.json();\n\n return value;\n // Note IIFE call with id variable after closing the function below\n // This makes the promise reactive based on 'id'\n })(id) \n \n\n \n{#await aircraftsPromise }\n ...waiting\n\n{:then aircrafts}\n {aircrafts.length} Aircraft\n\n{:catch error}\n {error.message}\n\n{/await}\n```\n\nThis allows the entire component to be reactive to the `id` prop and provides a location for loading state display to take place easily. I've also found many other situations where the same pattern applies.\n\n========================================\n\nCode:\n```html\n<script lang=\"ts\">\nimport { onMount } from 'svelte'\nimport type { Aircraft } from '$lib/models'\n \nlet aircrafts: Aircraft[]\n\nonMount(async() => {\n aircrafts = await (await fetch('/aircrafts')).json()\n console.log(aircrafts) //<-- This works\n})\n</script>\n \n<p>{aircrafts.length} Aircraft</p> //<-- undefined Aircraft\n```\n\n```text\nload\n```\n\n```text\n/aircrafts\n```\n\n```text\nconsole.log\n```\n\n```text\naircrafts.length\n```\n\n```text\nundefined Aircraft\n```\n\n```text\nonMount\n```\n\n```html\n<script lang=\"ts\">\nimport type { Aircraft } from '$lib/models'\n \nlet aircrafts: Aircraft[]\n\nasync function getAircrafts() {\n const result = await fetch('/aircrafts')\n return result.json()\n}\n</script>\n\n{#await getAircrafts()}\n <p>Loading aircrafts...</p>\n{:then aircrafts}\n <p>{aircrafts.length} Aircraft</p>\n{:catch error}\n <p>Error loading aircrafts: {error.message}</p>\n{/await}\n```\n\n```text\naircrafts.length\n```\n\n```text\naircrafts\n```\n\n```text\n{#await}\n```\n\n```text\nonMount\n```\n\n```js\n{#await promise}\n <p>...waiting</p>\n{:then number}\n <p>The number is {number}</p>\n{:catch error}\n <p style=\"color: red\">{error.message}</p>\n{/await}\n```\n\n```text\n<script lang=\"ts\">\n\n async function getAircrafts() {\n const res = await fetch('/aircrafts');\n const values = await res.json();\n\n return values;\n }\n \n // NOTE await not used here! \n let aircraftsPromise = getAircrafts();\n\n</script>\n \n{#await aircraftsPromise }\n <p>...waiting</p>\n{:then aircrafts}\n <p>{aircrafts.length} Aircraft</p>\n{:catch error}\n <p style=\"color: red\">{error.message}</p>\n{/await}\n```\n\n```text\n<script lang=\"ts\">\n\n export let id: string; // Mutating this will cause function below to re-run\n\n $: aircraftPromise = (async function getAircraftById(aircraftID: string) {\n // Asuming API has a route for '/aircrafts/id'\n // and 'id' is a url path param\n const res = await fetch('/aircrafts/' + aircraftID);\n const value = await res.json();\n\n return value;\n // Note IIFE call with id variable after closing the function below\n // This makes the promise reactive based on 'id'\n })(id) \n \n</script>\n \n{#await aircraftsPromise }\n <p>...waiting</p>\n{:then aircrafts}\n <p>{aircrafts.length} Aircraft</p>\n{:catch error}\n <p style=\"color: red\">{error.message}</p>\n{/await}\n```\n\n```text\nawait\n```\n\n```text\nnumber\n```\n\n```text\naircraftsPromise\n```\n\n```text\naircrafts\n```\n\n```text\n{:then ... }\n```\n\n```text\nid\n```\n\n```text\n{aircrafts?.length ?? ''}\n\n{aircrafts ? aircrafts.length : ''}\n\n{#if aircrafts}{aircrafts.length}{/if}\n```\n\n```text\n<script>\n\n let todos // 'forever' undefined\n\n async function fetchTodos() { \n const response = await fetch('https://jsonplaceholder.typicode.com/todos/')\n return await response.json()\n }\n</script>\n\n{#await fetchTodos() then todos}\n <h1>{todos.length} todos!</h1>\n{/await}\n\n<button on:click={() => console.log(todos)}>log todos</button>\n```\n\n```text\n<script>\n import { onMount } from 'svelte'\n\n let todos\n\n async function initTodos() { \n const response = await fetch('https://jsonplaceholder.typicode.com/todos/')\n todos = await response.json()\n }\n</script>\n\n{#await initTodos() then whatever}\n <h1>{todos.length} todos!</h1>\n{/await}\n```\n\n```text\n<p>{*length when loaded*} Aircraft</p>\n```\n\n```text\n<script>\n import { onMount } from 'svelte'\n\n let todos\n \n onMount(async() => {\n todos = await fetchTodos()\n })\n\n async function fetchTodos() {\n const response = await fetch('https://jsonplaceholder.typicode.com/todos/')\n return await response.json() \n }\n</script>\n\n<h1>{todos ? todos.length : ''} todos!</h1>\n\n<h1>{todos?.length ?? ''} todos!</h1>\n\n<h1>{#if todos}{todos.length}{/if} todos!</h1>\n\n<h1>{#await fetchTodos() then todos}{todos.length}{/await} todos!</h1>\n```\n\n```text\n{#await}\n```\n\n```text\naircrafts\n```\n\n```text\n@sveltejs/kit@1.0.0-next.350\n```\n\n```text\n(@sveltejs/adapter-auto@1.0.0-next.50)\n```\n\n```text\nlet aircrafts\n```\n\n```text\nundefined\n```\n\n```text\naircrafts.length\n```\n\n```text\n{#await}\n```\n\n```text\n{#await}\n```\n\n```text\n{#await}\n```\n\n```text\nload()\n```\n\n```text\n$page.data\n```\n\n```text\npage\n```\n\n```text\n$app/stores\n```\n\n```text\nfetch()\n```\n\n```text\nonMount()\n```\n\n```text\n/aircrafts/+page.svelte\n```\n\n```text\n/aircrafts/+page.server(.js/.ts)\n```\n\n```text\naircrafts\n```\n\n========================================\n\nComments:\n- Your answer is essentially the same as the other. I had to flip a coin and pick one. 😅Thanks for your help!\n- All good, although I was the first to post ;) More importantly though, wanted to help you get going.\n- Thanks you. very good answer. The reactive method is also interesting.\n- Does the `await` markup work with SSR? On the client side does svelte need to fetch data again?\n- @Tacaza now that Sveltekit introduced streaming of promises, I'm not sure if that works. It should still work as intended but will require some experimentation to understand.\n- Wow, this is way more elegant than what I was doing. I really like it. Thank you!\n- *\"And since `aircrafts` is not reactive\"* - is there a SvelteKit config/mode where that's true? For the \"basic start template\" I think it's not?\n- You make some great points, thank you! I actually did end up needing `aircrafts` to be reactive so that I could update it after the initial `getAircrafts()` function loads. I was also able to eliminate the `.length` issue simply by initializing when declaring: `let aircrafts: Aircraft[] = []`\n- @CliftonLabrum Yes, starting with `let aircrafts = []` works too. It could be argued though, that the visual switch from zero to the final value is not optimal and if the zero is displayed, you can't tell if it's still loading or if that's the final fetched value and, if not handled otherwise, you'd also see the 0 if the value couldn't be fetched\n- Imagine, in the page, someone selects an item from a drop-down, which makes a variable on the page change, which then causes another component on the page to have a different id... the component might need to fetch data for that identifier. One might argue that one should create a page instead of a component for this, but it isn't unimaginable for someone to want to do this.","metadata":{"transformedAt":"2026-08-18T18:33:40.657Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":45,"totalLines":446,"estimatedTokens":2478}}62{"id":"stack-59231590","source":"stackoverflow","questionId":59231590,"title":"Svelte: What does $: mean?","tags":["javascript","svelte"],"text":"Title: Svelte: What does $: mean?\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nHere is the snippet of a Svelte component:\n\n```\n\n let radius = 10;\n $: area = Math.PI * radius ** 2;\n\n // ...\n\n```\n\nCould somebody explain what is the purpose of `$:` before the `area` variable? Thanks in advance.\n\n========================================\n\nTop Answer:\nIt is called reactive declaration. Just like your components gets re-rendered whenever an update occurs, the same happens for the reactive declaration.\n\n```\n\n let radius = 10;\n area = Math.PI * radius ** 2;\n\n // ...\n\n```\n\nThis sets the area to be Math.PI * 10 **2, but lets say later a function changes radius to 20. Then area will not change and stay as it is.\nThis is where reactive declaration comes in handy. If the radius changes the area is calculated again and is changed.\n\n========================================\n\nCode:\n```js\n<script>\n let radius = 10;\n $: area = Math.PI * radius ** 2;\n\n // ...\n</script>\n```\n\n```text\n$:\n```\n\n```text\narea\n```\n\n```text\n<script>\n let radius = 10;\n area = Math.PI * radius ** 2;\n\n // ...\n</script>\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.657Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":63,"estimatedTokens":278}}63{"id":"stack-75071352","source":"stackoverflow","questionId":75071352,"title":"Reading the body of a request in hooks.server in sveltekit","tags":["typescript","svelte","sveltekit"],"text":"Title: Reading the body of a request in hooks.server in sveltekit\nTags: typescript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI want to read the body of a request in my hooks.server.ts\nimport type { Handle } from '@sveltejs/kit';\n\n```\nexport const handle = (async ({ event, resolve }) => {\n console.log(event.request.body);\n \n const response = await resolve(event);\n return response;\n}) satisfies Handle;\n```\n\nThis gives me\n\n```\nReadableStream { locked: false, state: 'readable', supportsBYOB: false }\n```\n\nIf i read it\n\n```\nconst reader = request.body.getReader();\nlet text;\nlet result;\nwhile (!(result = await reader.read()).done) {\n text += result.value;\n}\nconsole.log(text);\nconsole.log(request.body);\n```\n\nAnd then log the body, i get:\n\n```\nReadableStream { locked: true, state: 'closed', supportsBYOB: false }\n```\n\nThis leads to the actuall call I want to do to thrown an error\n\nTypeError: Body is unusable\nat specConsumeBody (/home/hp/git/booking/node_modules/undici/lib/fetch/body.js:492:11)\nat Request.json (/home/hp/git/booking/node_modules/undici/lib/fetch/body.js:359:14)\n\nHow can I read the body in hooks?\n\n========================================\n\nTop Answer:\nI got the error `TypeError: Body is unusable` when trying to debug a POST request with a JSON body because I did await the request twice.\n\n```\nconsole.log(await request.text()) // X only this is logged\nconsole.log(await request.json()) // --> throws error\n```\n\nInstead, only await the request once!\n\n```\nconsole.log(await request.json()) // logs, no error\n```\n\n========================================\n\nCode:\n```text\nexport const handle = (async ({ event, resolve }) => {\n console.log(event.request.body);\n \n const response = await resolve(event);\n return response;\n}) satisfies Handle;\n```\n\n```text\nReadableStream { locked: false, state: 'readable', supportsBYOB: false }\n```\n\n```text\nconst reader = request.body.getReader();\nlet text;\nlet result;\nwhile (!(result = await reader.read()).done) {\n text += result.value;\n}\nconsole.log(text);\nconsole.log(request.body);\n```\n\n```text\nReadableStream { locked: true, state: 'closed', supportsBYOB: false }\n```\n\n```text\nclone()\n```\n\n```text\nRequest\n```\n\n```text\nconsole.log(await request.text()) // X only this is logged\nconsole.log(await request.json()) // --> throws error\n```\n\n```text\nconsole.log(await request.json()) // logs, no error\n```\n\n```text\nTypeError: Body is unusable\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.657Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":117,"estimatedTokens":604}}64{"id":"stack-64858904","source":"stackoverflow","questionId":64858904,"title":"How to trigger a function when there is a value change in subscribed store in Svelte?","tags":["svelte","svelte-3","svelte-component","svelte-store"],"text":"Title: How to trigger a function when there is a value change in subscribed store in Svelte?\nTags: svelte, svelte-3, svelte-component, svelte-store\nSource: Stack Overflow\n\nQuestion:\nOne of my components is subscribed to a variable in a store. Whenever there is a change in that store var, I want to trigger a function.\n\nstores.js\n\n```\nimport { writable } from \"svelte/store\"; \n export const comparedProducts = writable([1,2,3]);\n```\n\nComponent.svelte\n\n```\nimport { comparedProducts } from \"../stores.js\";\n \n //if there is a change in $comparedProducts trigger this function eg. ([1,2])\n const someFunction = () => {\n //do something\n }\n```\n\n========================================\n\nTop Answer:\nin componenet.svelte\n\n```\nimport { comparedProducts } from \"../stores.js\";\n \n //if there is a change in $comparedProducts trigger this function eg. ([1,2])\n const someFunction = () = >{\n // do something\n }\n \n // stores can be subscribed to using .subscribe()\n // each new value will trigger the callback supplied to .subscribe()\n \n let unsubscribeStore = comparedProducts.subscribe((currentValue) => {\n //currentValue == $comparedProducts\n someFunction()\n })\n\n // call unsubscribeStore() after finishing to stop listening for new values\n```\n\n========================================\n\nCode:\n```svelte\nimport { writable } from \"svelte/store\"; \n export const comparedProducts = writable([1,2,3]);\n```\n\n```svelte\nimport { comparedProducts } from \"../stores.js\";\n \n //if there is a change in $comparedProducts trigger this function eg. ([1,2])\n const someFunction = () => {\n //do something\n }\n```\n\n```svelte\nimport { comparedProducts } from \"../stores.js\";\n$: $comparedProducts, run();\n\nfunction run(){\n //do something here\n}\n```\n\n```svelte\nimport { comparedProducts } from \"../stores.js\";\n \n //if there is a change in $comparedProducts trigger this function eg. ([1,2])\n const someFunction = () = >{\n // do something\n }\n \n // stores can be subscribed to using .subscribe()\n // each new value will trigger the callback supplied to .subscribe()\n \n let unsubscribeStore = comparedProducts.subscribe((currentValue) => {\n //currentValue == $comparedProducts\n someFunction()\n })\n\n // call unsubscribeStore() after finishing to stop listening for new values\n```\n\n```text\nimport { writable } from \"svelte/store\"; \nexport const count = writable(0);\n```\n\n```text\nimport { count } from \"../store.js\";\n$: if($count > 0) { foo($count) }\n\n \nfunction foo($count) {\n console.log($count)\n}\n```\n\n```js\n$: $comparedProducts, (() => {\n // do something here\n})();\n```\n\n```js\n$: someFunction = () => { /* ... */ }\n$: someFunction();\n```\n\n========================================\n\nComments:\n- Not sure why this would deserve a downvote. I think it's clean & in the spirit of Svelte..\n- Actually, when the value of the store is falsy, this will not work. You'll need a comma instead of a logical AND: `$: $comparedProducts, run();` This will make sure the `run` function is always executed, regardless the value of the store.","metadata":{"transformedAt":"2026-08-18T18:33:40.657Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":125,"estimatedTokens":768}}65{"id":"stack-67422216","source":"stackoverflow","questionId":67422216,"title":"SvelteKit - load() not called from component but works as a Page","tags":["svelte","svelte-3","sveltekit"],"text":"Title: SvelteKit - load() not called from component but works as a Page\nTags: svelte, svelte-3, sveltekit\nSource: Stack Overflow\n\nQuestion:\nIf the file test.svelte below is a Page in /routes, it successfully calls load() and populates the template with the JSON array it retrieves when I access it via http://localhost:3000/test. If I move this file to /lib and import it as a component in /routes/index.svelte, the load() method of the component never runs when I go to http://localhost:3000.\n\n**test.svelte**\n\n```\n\n /**\n * @type {import('@sveltejs/kit').Load}\n */\n export async function load({ fetch }) {\n const url = '/api/announcement'\n const res: Response = await fetch(url)\n\n if (res.ok) {\n const sections: Announcement[] = await res.json()\n return {\n props: {\n sections\n }\n }\n }\n\n return {\n status: res.status,\n error: new Error(`Could not load ${url}`)\n }\n }\n\n export let sections: Announcement[] = []\n\n {#each sections as section}\n \n {section.title}\n\n {section.description}\n \n\n {/each}\n\n```\n\nHere is routes/index.svelte that tries to load it as a component from /lib:\n\n```\n\n import Test from '$lib/test.svelte'\n\n .container\n Test\n\n```\n\nSeems like I'm doing something obviously wrong but I'm new to Svelte and SvelteKit. While I considered retrieving the data in routes/index.svelte and pass it down to the component, I was hoping to encapsulate the data retrieval in the component to keep it simpler.\n\n========================================\n\nTop Answer:\nAdding a little bit of more visualization to the `Stephane's` answer above.\n\nFor example: If you have a main page and you need to redirect to the `/login`\n\n```\nsrc/\n└── routes/\n ├── +page.svelte // Entry Point\n ├── +page.js // Js file of your entry point\n └── login/\n └── +page.svelte // Login page\n```\n\n`.svelte`: Defines the component's user interface and behavior.\n\n`.js or .ts`: Handles data loading logic, redirects, and other functionality before rendering the component.\n\nAnd, in your `.js` file you just need to add the load function\n\n```\nimport { redirect } from '@sveltejs/kit';\n\nexport const load = async () => {\n throw redirect(307, '/login');\n};\n```\n\n========================================\n\nCode:\n```text\n<script context=\"module\" lang=\"ts\">\n /**\n * @type {import('@sveltejs/kit').Load}\n */\n export async function load({ fetch }) {\n const url = '/api/announcement'\n const res: Response = await fetch(url)\n\n if (res.ok) {\n const sections: Announcement[] = await res.json()\n return {\n props: {\n sections\n }\n }\n }\n\n return {\n status: res.status,\n error: new Error(`Could not load ${url}`)\n }\n }\n</script>\n\n<script lang=\"ts\">\n export let sections: Announcement[] = []\n</script>\n\n<template>\n {#each sections as section}\n <p>\n {section.title}<br/>\n {section.description}\n </p>\n {/each}\n</template>\n```\n\n```text\n<script context=\"module\" lang=\"ts\">\n import Test from '$lib/test.svelte'\n</script>\n\n<template lang=\"pug\">\n .container\n Test\n</template>\n```\n\n```html\n<script context=\"module\">\n import _load from './loader.js';\n export const load = _load;\n</script>\n```\n\n```text\nonMount\n```\n\n```text\nload\n```\n\n```text\n+page.js\n```\n\n```text\n+layout.js\n```\n\n```text\nsrc/\n└── routes/\n ├── +page.svelte // Entry Point\n ├── +page.js // Js file of your entry point\n └── login/\n └── +page.svelte // Login page\n```\n\n```text\nimport { redirect } from '@sveltejs/kit';\n\nexport const load = async () => {\n throw redirect(307, '/login');\n};\n```\n\n```text\nStephane's\n```\n\n```text\n/login\n```\n\n```text\n.svelte\n```\n\n```text\n.js or .ts\n```\n\n```text\n.js\n```\n\n========================================\n\nComments:\n- Thanks - found that one-liner last night in the docs. Was originally thinking my announcements component could get its own data and sounds like I can still do this with onMount(). But is this a pattern I should avoid? My announcements component just displays data that is not changing very frequently.\n- easiest way is to just pass the data with `setContext` and `getContext`\n- this answer makes me sad :'(\n- @stephane Could you elaborate on how to use `onMount` in this situation?","metadata":{"transformedAt":"2026-08-18T18:33:40.658Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":209,"estimatedTokens":1045}}66{"id":"stack-70034450","source":"stackoverflow","questionId":70034450,"title":"How do I add a version number to a SvelteKit/Vite app?","tags":["javascript","build","svelte","vite","sveltekit"],"text":"Title: How do I add a version number to a SvelteKit/Vite app?\nTags: javascript, build, svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a system in my SvelteKit app where it shows you info about the current app version (ideally a Git commit hash and description) on a certain page. I tried using Vite's define feature to do this at build time but it doesn't seem to work. How do I add something like this?\n\nHere's an example of what I tried to do:\n\nVite config in svelte.config.js\n\n```\nvite: () => ({\n define: {\n '__APP_VERSION__': JSON.stringify('testfornow')\n }\n})\n```\n\nindex.svelte:\n\n```\n\n const version: string = __APP_VERSION__;\n\nCurrent App version: {version}\n\n```\n\n========================================\n\nTop Answer:\nThis is how I managed to make it work:\n\n- Get the package.json data as explained in the SvelteKit FAQ, and load it as a constant in Vite config:\n\n```\n// svelte.config.js\n\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\n \nconst file = fileURLToPath(new URL('package.json', import.meta.url));\nconst json = readFileSync(file, 'utf8');\nconst pkg = JSON.parse(json);\n\nconst config = {\n kit: {\n // ...\n vite: {\n define: {\n '__APP_VERSION__': JSON.stringify(pkg.version),\n }\n },\n },\n // ...\n};\n```\n\n- Use the variable in any svelte file:\n\n```\n\n### Version: {__APP_VERSION__}\n\n```\n\nQuite similar to your example, hope it helps!\n\n### EDIT: Be aware, config changed after @sveltejs/kit@1.0.0-next.359:\n\nAfter a breaking change on @sveltejs/kit@1.0.0-next.359, Vite config must be included in its own file:\n\n```\n// vite.config.js\n\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\n \nconst file = fileURLToPath(new URL('package.json', import.meta.url));\nconst json = readFileSync(file, 'utf8');\nconst pkg = JSON.parse(json);\n\nconst config = {\n define: {\n '__APP_VERSION__': JSON.stringify(pkg.version),\n }\n // ...\n};\n```\n\nAnd the `config.kit.vite` prop must be removed from the `svelte.config.js` file.\n\n========================================\n\nCode:\n```js\nvite: () => ({\n define: {\n '__APP_VERSION__': JSON.stringify('testfornow')\n }\n})\n```\n\n```html\n<script lang=\"ts\">\n const version: string = __APP_VERSION__;\n</script>\n\n<p>Current App version: {version}</p>\n```\n\n```text\nconst config = {\n ...\n kit: {\n ...\n version: {\n name: process.env.npm_package_version\n }\n }\n}\n```\n\n```text\nimport { version, dev } from '$app/environment';\n...\nconsole.log(`Client version: ${version}`);\n```\n\n```js\nimport { exec } from 'child_process'\nimport { promisify } from 'util'\n\n// Get current tag/commit and last commit date from git\nconst pexec = promisify(exec)\nlet [version, lastmod] = (\n await Promise.allSettled([\n pexec('git describe --tags || git rev-parse --short HEAD'),\n pexec('git log -1 --format=%cd --date=format:\"%Y-%m-%d %H:%M\"'),\n ])\n).map(v => JSON.stringify(v.value?.stdout.trim()))\n\n/** @type {import('vite').UserConfig} */\nconst config = {\n define: {\n __VERSION__: version,\n __LASTMOD__: lastmod,\n },\n ...\n```\n\n```js\n// App version\ndeclare const __VERSION__: string\n// Date of last commit\ndeclare const __LASTMOD__: string\n```\n\n```html\n<script context=\"module\" lang=\"ts\">\n const versionInfo = `Version ${__VERSION__}, ${__LASTMOD__}`\n</script>\n\n<div>{versionInfo}</div>\n```\n\n```text\nvite.config.js\n```\n\n```text\napp.d.ts\n```\n\n```text\n__VERSION__\n```\n\n```text\n__LASTMOD__\n```\n\n```js\n// svelte.config.js\n\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\n \nconst file = fileURLToPath(new URL('package.json', import.meta.url));\nconst json = readFileSync(file, 'utf8');\nconst pkg = JSON.parse(json);\n\nconst config = {\n kit: {\n // ...\n vite: {\n define: {\n '__APP_VERSION__': JSON.stringify(pkg.version),\n }\n },\n },\n // ...\n};\n```\n\n```html\n<h2>Version: {__APP_VERSION__}</h2>\n```\n\n```js\n// vite.config.js\n\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\n \nconst file = fileURLToPath(new URL('package.json', import.meta.url));\nconst json = readFileSync(file, 'utf8');\nconst pkg = JSON.parse(json);\n\nconst config = {\n define: {\n '__APP_VERSION__': JSON.stringify(pkg.version),\n }\n // ...\n};\n```\n\n```text\nconfig.kit.vite\n```\n\n```text\nsvelte.config.js\n```\n\n========================================\n\nComments:\n- Can you add an example of how to actually use `__VERSION__` inside a Svelte component? As it stands, your answer is only halfway there.\n- @NatoBoram you can use it like this: `const version = __VERSION__;`.\n- This worked as far as compilation and usage goes, but do you know how to get typescript to stop reporting that \"**APP_VERSION** is not defined\"?\n- Place the following comment above the line when the variable is used:\n- @TomaszPlonka Yes, this is what I do too for now.\n- Hm, that didn't work for me for some reason. But you did point me in the right direction, so I instead assigned `__APP_VERSION__` to another component-local variable with `// @ts-ignore` above it, and that did the trick 👍\n- @DigitalNinja There's a note in the define section of the vite config object documentation that suggests to \"... add ... type declarations in the env.d.ts or vite-env.d.ts file to get type checks and Intellisense.\" e.g. `declare const __APP_VERSION__: string`\n- Note that the keys of `define` are replaced in the code directly with their value. If it has a string value and you try to assign it to a variable then you'll have to add quotes in your code as well, e.g. you can do `const value = \"__APP_VERSION__\"`, but not `const value = __APP_VERSION__` (as it will then look for variable in the local scope with a name matching the value you defined).\n- For completeness, for vanilla Svelte it's {window.__APP_VERSION__}\n- perfect for me, and with minimum extra code\n- As of Dec 2023 this should be the selected answer","metadata":{"transformedAt":"2026-08-18T18:33:40.658Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":250,"estimatedTokens":1470}}67{"id":"stack-61105696","source":"stackoverflow","questionId":61105696,"title":"Error: {#each} only iterates over array-like objects. -- Javascript & Svelte","tags":["javascript","svelte","ghost-blog","sapper"],"text":"Title: Error: {#each} only iterates over array-like objects. -- Javascript & Svelte\nTags: javascript, svelte, ghost-blog, sapper\nSource: Stack Overflow\n\nQuestion:\n```\n\n import GhostContentAPI from '@tryghost/content-api';\n\n // const api = 'http://localhost/posts';\n const api = new GhostContentAPI({\n url: 'http://localhost',\n key: '95a0aadda51e5d621abd2ee326',\n version: \"v3\"\n });\n\n export async function preload({ params, query }) {\n try {\n const response = await api.posts.browse({ limit: 5, fields: 'title, slug' });\n return {\n posts: response\n }\n } catch(err) {\n console.log('Error');\n }\n }\n\n export let posts;\n\n Blog\n\n### Recent posts\n\n {#each posts as post}\n \n {post.title}\n \n {/each}\n\n```\n\nI'm using vanilla JavaScript and Svelte to simply fetch a list of blog posts, which are objects from the Ghost Blog Rest API. The Ghost API function works fine and pulls the correct objects, but the problem begins when trying to use Svelte's `{#each}` block to display each object because they aren't in an array and I cannot figure out how to fix it. Here's the exact error message in the console:\n\n`Error: {#each} only iterates over array-like objects.`\n\nWriting a `console.log(response)` after the `const response` declaration outputs the attached image, but only if I comment out the `{#each}` block first.\n\nI'm guessing I simply need to move the 5 objects into an array, but I also don't understand why the `console.log` above only works when the HTML is commented out.\n\nhttps://i.sstatic.net/a27Jy.png\n\n========================================\n\nTop Answer:\nI was facing a similar issue. This happened while working with Firebase Firestore and by comparing the erroneous value with the prototype given in the official svelte documentation, I came to a conclusion.\n\nhttps://i.sstatic.net/ntCyQ.png\n\nSo I simply used the javascript `Object.values()` method on the retrieved object and `{#each} only iterates over array-like objects` error was gone.\n\n========================================\n\nCode:\n```text\n<script context=\"module\">\n import GhostContentAPI from '@tryghost/content-api';\n\n // const api = 'http://localhost/posts';\n const api = new GhostContentAPI({\n url: 'http://localhost',\n key: '95a0aadda51e5d621abd2ee326',\n version: \"v3\"\n });\n\n export async function preload({ params, query }) {\n try {\n const response = await api.posts.browse({ limit: 5, fields: 'title, slug' });\n return {\n posts: response\n }\n } catch(err) {\n console.log('Error');\n }\n }\n</script>\n\n<script>\n export let posts;\n</script>\n\n<svelte:head>\n <title>Blog</title>\n</svelte:head>\n\n<h1>Recent posts</h1>\n<ul>\n {#each posts as post}\n <li>\n <a rel='prefetch' href='blog/{post.slug}'>{post.title}</a>\n </li>\n {/each}\n</ul>\n```\n\n```text\n{#each}\n```\n\n```text\nError: {#each} only iterates over array-like objects.\n```\n\n```text\nconsole.log(response)\n```\n\n```text\nconst response\n```\n\n```text\n{#each}\n```\n\n```text\nconsole.log\n```\n\n```text\nexport let posts;\n```\n\n```text\nexport let posts = [];\n```\n\n```text\nconst array = [];\nlet newArray = [e.detail, ...array];\n```\n\n```text\nDispatching\n```\n\n```text\nObject.values()\n```\n\n```text\n{#each} only iterates over array-like objects\n```\n\n```text\n<tbody class=\"uk-text-left\">\n <!-- {@debug calendarEventList} -->\n {#if calendarEventList}\n {#each calendarEventList as event}\n <tr>\n <td>{calendarEventList.items[1].summary}</td>\n <td>{calendarEventList.items[1].start.dateTime}</td>\n <td>{calendarEventList.items[1].end.dateTime}</td>\n <td>{calendarEventList.items[1].creator.email}</td>\n \n </tr>\n {/each}\n {/if}\n </tbody>\n```\n\n```text\n<tbody class=\"uk-text-left\">\n <!-- {@debug calendarEventList} -->\n {#if calendarEventList}\n {#each calendarEventList.items as event}\n <tr>\n <td>{event.summary}</td>\n <td>{event.start.dateTime}</td>\n <td>{event.end.dateTime}</td>\n <td>{event.creator.email}</td>\n </tr>\n {/each}\n {/if}\n </tbody>\n```\n\n```text\n{\n\"kind\": \"calendar#events\",\n\"etag\": \"\\\"p334fwehgbta5ve0g\\\"\",\n\"summary\": \"Svelte StackOverflow\",\n\"updated\": \"2022-04-11T10:44:38.077Z\",\n\"timeZone\": \"Europe/Dublin\",\n\"accessRole\": \"reader\",\n\"defaultReminders\": [],\n\"nextSyncToken\": \"CMj8_xxxx_cCEAAHSHDHD8-LRAQ==\",\n\"items\": [\n {\n \"kind\": \"calendar#event\",\n \"etag\": \"\\\"3299347666786000\\\"\",\n \"id\": \"5rqm5kq33ghd9tuhsktjhoisdvho\",\n \"status\": \"confirmed\",\n \"htmlLink\": \"https://www.google.com/calendar/event?eid=Npw\",\n \"created\": \"2022-04-11T10:43:53.000Z\",\n \"updated\": \"2022-04-11T10:43:53.393Z\",\n \"summary\": \"Call Back Customer\",\n \"creator\": {\n \"email\": \"abc@gmail.com\"\n },\n \"organizer\": {\n \"email\": \"m04@group.calendar.google.com\",\n \"displayName\": \"Svelte StackOverflow\",\n \"self\": true\n },\n \"start\": {\n \"dateTime\": \"2022-04-11T07:15:00+01:00\",\n \"timeZone\": \"Europe/Dublin\"\n },\n \"end\": {\n \"dateTime\": \"2022-04-11T08:15:00+01:00\",\n \"timeZone\": \"Europe/Dublin\"\n },\n \"iCalUID\": \"5rqophoiosktsnibmno@google.com\",\n \"sequence\": 0,\n \"eventType\": \"default\"\n },\n {\n \"kind\": \"calendar#event\",\n \"etag\": \"\\\"3299347756154000\\\"\",\n \"id\": \"78flukdyhjjki16ola\",\n \"status\": \"confirmed\",\n \"htmlLink\": \"https://www.google.com/calendar/event?eid=NzhjAZw\",\n \"created\": \"2022-04-11T10:44:25.000Z\",\n \"updated\": \"2022-04-11T10:44:38.077Z\",\n \"summary\": \"Maintenance at pharma company x\",\n \"creator\": {\n \"email\": \"abc@gmail.com\"\n },\n \"organizer\": {\n \"email\": \"a2gopnm04@group.calendar.google.com\",\n \"displayName\": \"Svelte StackOverflow\",\n \"self\": true\n },\n \"start\": {\n \"dateTime\": \"2022-04-14T08:00:00+01:00\",\n \"timeZone\": \"Europe/Dublin\"\n },\n \"end\": {\n \"dateTime\": \"2022-04-14T09:00:00+01:00\",\n \"timeZone\": \"Europe/Dublin\"\n },\n \"iCalUID\": \"78flukukccb2go6asrlki16ola@google.com\",\n \"sequence\": 0,\n \"eventType\": \"default\"\n }\n]\n```\n\n========================================\n\nComments:\n- Try echoing out the `posts.length` in your template to see what it is. I wonder if you are running into an async issue.\n- @Taplar interesting... logging `response.length` returns `5`, but logging `posts.length` after it is exported returns `Cannot read property 'length' of undefined`.\n- Or do `console.log(JSON.stringify(posts, null, 2))` instead. See weird array behaviour in javascript for more about what that \"i\" shows when you hover over it.\n- @HereticMonkey that actually returned everything perfectly, in an array...interesting. It is a string, but close.\n- Depends on where you run the code, I expect. For instance, run that just before your `{#each}` in the template and you may get something different. I don't know svelte or ghost or sapper, but typically there's a way of telling the template that the array will be filled asynchronously. Maybe if you just did `export let posts = [];`?\n- @HereticMonkey making that change actually triggers `catch` in the statement above.\n- Shows you what I know :). I'll let the svelte experts take over. Good luck.\n- @HereticMonkey actually, that worked! I had a typo causing the catch. Thank you!\n- The tutorial does \"suggests\" initializing soon-to-be-array variables with `[]` although it doesn't give a clue why we should do it nor it gives any warning for not doing it.\n- Note to self: When using `{#await}`, use a dummy promise instead of `[]`.\n- That works if you have an array as import, but if you have a structure with the array within it, you need to force the array when undefined right inside the each statement: ~~~ {#each importedThing.fields || [] as field, i} {field.fieldName} {/each}","metadata":{"transformedAt":"2026-08-18T18:33:40.658Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":272,"estimatedTokens":2021}}68{"id":"stack-64367485","source":"stackoverflow","questionId":64367485,"title":"How can I read an attribute value of a svelte component","tags":["svelte"],"text":"Title: How can I read an attribute value of a svelte component\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\n**Component.svelte**\n\n```\n\n export let hiddenStatus;\n\n```\n\n**App.svelte**\n\n```\n\n import Component from \"./Component.svelte\";\n\n{Component.hiddenStatus}\n```\n\nWhen I try to get that attribute value of `hiddenStatus` it displays as `undefined`. How can I solve this?\n\n========================================\n\nCode:\n```html\n<script>\n export let hiddenStatus;\n</script>\n\n<div class:hidden={hiddenStatus}></div>\n```\n\n```html\n<script>\n import Component from \"./Component.svelte\";\n</script>\n\n<Component hiddenStatus={true}/>\n{Component.hiddenStatus}\n```\n\n```text\nhiddenStatus\n```\n\n```text\nundefined\n```\n\n```html\n<!-- Component.svelte -->\n<script>\n export let hiddenStatus;\n</script>\n\n<div class:hidden={hiddenStatus}></div>\n\n<!-- App.svelte -->\n<script>\n import { onMount } from \"svelte\";\n import Component from \"./Component.svelte\";\n\n let component;\n \n onMount(() => {\n console.log(component.hiddenStatus);\n });\n</script>\n\n<Component hiddenStatus={true} bind:this={component}/>\n```\n\n```text\nbind:this\n```\n\n```text\naccessors\n```\n\n```text\ntrue\n```\n\n```text\n<svelte:options accessors/>\n```\n\n========================================\n\nComments:\n- For those wondering about the alternative to *\"read[ing] directly from the component instance\"*, it's binding to the specific prop, i.e. `<Component bind:hiddenStatus={myVar}` or the shorthand `<Component bind:hiddenStatus`.","metadata":{"transformedAt":"2026-08-18T18:33:40.658Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":95,"estimatedTokens":371}}69{"id":"stack-66873724","source":"stackoverflow","questionId":66873724,"title":"How to conditional add and remove `use:` property in Svelte 3?","tags":["svelte","svelte-3"],"text":"Title: How to conditional add and remove `use:` property in Svelte 3?\nTags: svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nIs there a way to elegantly and conditionally add and remove `use:` property in Svelte 3?\n\nExample:\n\n```\n\n import {classes} from \"./functions.js\"\n\n export let originalClasses\n\nButton\n```\n\nIs there a way to add or remove `use:classes` if `originalClasses` is true?\n\n========================================\n\nTop Answer:\nGiven that you have no control over the `classes` function, one way would be to wrap the action with one of your own:\n\n```\nimport classes from '....'\nfunction classesWrap(node, useDefault = true) {\n useDefault && classes(node);\n \n return {\n update(useDefault) {\n useDefault && classes(node);\n }\n }\n}\n```\n\nand then use this action instead: ``\n\nThis works, kind of, when `originalClasses` is false, it will not set the default ones, and when it is true it will set them. When it starts as false and turns true it will also apply them (thanks to the `update`) **However** it seems that once an action is attached it cannot be removed again (which is logical as actions are supposed to run when the element gets mounted). This means that turning from *true* to *false* will not change anything, it will keep the default classes.\n\nThere are two (really bad) workarounds for this:\n\n- add some extra code to the update function to remove the classes yourself:\n\n```\nupdate(useDefault) {\n useDefault && classes(node);\n !useDefault && node.classList.remove(...node.classList);\n}\n```\n\n(but this removes **all** classes, also those you might have added yourself)\n\n- a second option is to wrap the element with a `{#key}` block based on `originalClasses` this will force a re-render whenever it changes.\n\n```\n{#key originalClasses}\n ...\n{/key}\n```\n\nBut this can be **very** expensive if this *div* has a lot of content, maybe for a one line element it might be ok.\n\n(note: you don't need the *update* function anymore)\n\nOf course this assumes that `originalClasses` can and will change, if you are 100% sure it will **never ever** change, just use the wrapper without update or key blocks.\n\n========================================\n\nCode:\n```html\n<script>\n import {classes} from \"./functions.js\"\n\n export let originalClasses\n</script>\n\n<button use:classes>Button</button>\n```\n\n```text\nuse:\n```\n\n```text\nuse:classes\n```\n\n```text\noriginalClasses\n```\n\n```js\n//functions.js\nexport default function classes(node,options){\n if(options){\n node.className=\"myClass\";\n }\n console.log(node);\n}\n```\n\n```js\nimport classes from '....'\nfunction classesWrap(node, useDefault = true) {\n useDefault && classes(node);\n \n return {\n update(useDefault) {\n useDefault && classes(node);\n }\n }\n}\n```\n\n```js\nupdate(useDefault) {\n useDefault && classes(node);\n !useDefault && node.classList.remove(...node.classList);\n}\n```\n\n```html\n{#key originalClasses}\n <div use:classesWrap={originalClasses}>...</div>\n{/key}\n```\n\n```text\nclasses\n```\n\n```text\n<div use:classesWrap={originalClasses}>\n```\n\n```text\noriginalClasses\n```\n\n```text\nupdate\n```\n\n```text\n{#key}\n```\n\n```text\noriginalClasses\n```\n\n```text\noriginalClasses\n```\n\n```text\n<script>\n import {classes} from \"./functions.js\"\n\n export let originalClasses\n\n const conditionalAction = originalClasses ? classes : ()=>{};\n</script>\n\n<button use:conditionalAction>Button</button>\n```\n\n```text\nuse\n```\n\n```text\nbutton\n```\n\n```text\noriginalClasses\n```\n\n```text\ntrue\n```\n\n```text\n<MyComponent originalClasses={true} />\n```\n\n```text\nclasses\n```\n\n```text\noriginalClasses\n```\n\n```text\nfalse\n```\n\n```text\nbutton\n```\n\n```text\n()=>{}\n```\n\n========================================\n\nComments:\n- This method works very well today in svelte 5 world. Upvoting for it's clean and easy to implement. Only small change nowadays you should use a $derived rune `let conditionalAction = $derived(condition ? action : () => {})`","metadata":{"transformedAt":"2026-08-18T18:33:40.662Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":214,"estimatedTokens":977}}70{"id":"stack-61565251","source":"stackoverflow","questionId":61565251,"title":"Output Single HTML File from Svelte Project","tags":["svelte","rollup","rollupjs","svelte-3"],"text":"Title: Output Single HTML File from Svelte Project\nTags: svelte, rollup, rollupjs, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI can't find any example anywhere online that shows how to (or if we can) output a single HTML file from a Svelte project using Rollup (not Webpack), containing all CSS and JS injected inline (and not as URLs in script).\n\n========================================\n\nTop Answer:\ninliner can help\n\nlimit: inliner cant handle `defer` scripts\n\nso in your `public/index.html` template file\n\nmove\n\n```\n\n \n \n```\n\nto **after** the `` tag, like\n\n```\n\n \n\n```\n\nnow run inliner\n\n```\nnpm i -D inliner\nnpm run build\nnpm run start &\nsleep 5 # wait for webserver to start\n\nnpx inliner \\\n http://localhost:5000/index.html \\\n >build/index-inlined.html\n```\n\n========================================\n\nCode:\n```js\nimport svelte from 'rollup-plugin-svelte';\nimport fs from 'fs';\nimport path from 'path';\n\nfunction inlineSvelte(template, dest) {\n return {\n name: 'Svelte Inliner',\n generateBundle(opts, bundle) {\n const file = path.parse(opts.file).base\n const code = bundle[file].code\n const output = fs.readFileSync(template, 'utf-8')\n bundle[file].code = output.replace('%%script%%', () => code)\n }\n }\n}\n\nexport default {\n input: 'src/main.js',\n output: {\n format: 'iife',\n file: './public/index.html',\n name: 'app'\n },\n plugins: [\n svelte({\n }),\n inlineSvelte('./src/template.html')\n ]\n};\n```\n\n```html\n<html>\n <head>\n <script>%%script%%</script>\n </head>\n <body></body>\n</html>\n```\n\n```html\n<head>\n <script defer src=\"/build/bundle.js\"></script>\n </head>\n```\n\n```html\n</body>\n <script src=\"/build/bundle.js\"></script>\n</html>\n```\n\n```sh\nnpm i -D inliner\nnpm run build\nnpm run start &\nsleep 5 # wait for webserver to start\n\nnpx inliner \\\n http://localhost:5000/index.html \\\n >build/index-inlined.html\n```\n\n```text\ndefer\n```\n\n```text\npublic/index.html\n```\n\n```text\n</body>\n```\n\n```js\n// rollup.config.js\nimport svelte from 'rollup-plugin-svelte'\nimport resolve from '@rollup/plugin-node-resolve'\n\nexport default {\n input: 'Static.svelte',\n output: {\n file: 'static.html'\n },\n plugins: [\n svelte(),\n resolve(),\n {\n generateBundle(options, bundle) {\n const name = path.parse(options.file).base // static.html\n const module = bundle[name].facadeModuleId // Static.svelte\n // We ignore the bundle[name].code generated by other plugins\n // and load the input module explicitly instead.\n require('svelte/register')\n const Static = require(module).default\n bundle[name].code = Static.render().html\n }\n }\n ]\n}\n```\n\n```js\n// static.js\nrequire('svelte/register')\nconst Static = require('Static.svelte').default\nconsole.log(Static.render().html)\n```\n\n```js\n// package.json\n{ ...\n \"scripts\": {\n \"build\": \"node static.js > static.html\"\n }\n}\n```\n\n```text\nSvelte 3\n```\n\n```text\n*-svelte\n```\n\n```text\nJavascript\n```\n\n```text\nnpm\n```\n\n```js\nimport svelte from 'rollup-plugin-svelte'\nimport commonjs from '@rollup/plugin-commonjs'\nimport resolve from '@rollup/plugin-node-resolve'\nimport dev from 'rollup-plugin-dev' // 开发服务器\nimport cleanupDir from 'rollup-plugin-cleanup-dir'\nimport terser from '@rollup/plugin-terser' // 代码压缩\nimport livereload from 'rollup-plugin-livereload'\nimport sveltePreprocess from 'svelte-preprocess'\nimport typescript from '@rollup/plugin-typescript'\nimport css from 'rollup-plugin-css-only'\nimport htmlInsert from 'rollup-plugin-html-insert'\nconst production = !process.env.ROLLUP_WATCH\n\nexport default {\n input: 'src/main.ts',\n output: {\n dir: 'dist',\n format: 'iife',\n name: 'app',\n sourcemap: !production,\n entryFileNames: '[name].iife.[hash].js'\n },\n plugins: [\n svelte({\n preprocess: sveltePreprocess({ sourceMap: !production }),\n compilerOptions: {\n // enable run-time checks when not in production\n dev: !production\n }\n }),\n // we'll extract any component CSS out into\n // a separate file - better for performance\n css({ output: 'bundle.css' }),\n\n // If you have external dependencies installed from\n // npm, you'll most likely need these plugins. In\n // some cases you'll need additional configuration -\n // consult the documentation for details:\n // https://github.com/rollup/plugins/tree/master/packages/commonjs\n resolve({\n browser: true,\n dedupe: ['svelte']\n }),\n commonjs(),\n typescript({\n sourceMap: !production,\n inlineSources: !production\n }),\n htmlInsert({}),\n dev({\n dirs: ['dist']\n }),\n // Watch the `public` directory and refresh the\n // browser on changes when not in production\n !production && livereload('dist'),\n\n // If we're building for production (npm run build\n // instead of npm run dev), minify\n production && terser(),\n\n production && cleanupDir()\n ],\n watch: {\n clearScreen: false\n }\n}\n```\n\n```text\nrollup-plugin-html-insert\n```\n\n========================================\n\nComments:\n- rollup does not generate or output a html file (though there are some plugins that do), so your probably going to have the do it some other way (gulp maybe? gulp-iinline), or write your own rollup plugin (or find a rollup plugin that does what you want, both html output and inline script / css, I could not find one).\n- Thank you, it's not about performance but rather a constraint","metadata":{"transformedAt":"2026-08-18T18:33:40.662Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":262,"estimatedTokens":1375}}71{"id":"stack-70613169","source":"stackoverflow","questionId":70613169,"title":"Sveltekit: Styling active links with $page.path","tags":["css","routes","svelte","sveltekit"],"text":"Title: Sveltekit: Styling active links with $page.path\nTags: css, routes, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm working on a sveltekit app with a sidenav containing links. I can't get the active class styling on my links to work properly.\n\nThe links are components in **NavLink.svelte**:\n\n```\n\n import { page } from '$app/stores';\n import Icon from '$lib/Icon.svelte';\n export let title;\n export let href;\n\n \n\na.active {\n background-color: rgba(0,0,0,0.24);\n\n```\n\nThese links are used in **SideNav.svelte**:\n\n```\n\n import NavLink from '$lib/NavLink.svelte';\n\n \n \n \n \n \n\n```\n\nAnd finally, the sidenav is loaded in my **__layout.svelte**:\n\n```\n\n```\n\nNow when I click one of my sidenav links, I am routed to the proper page but my NavLink is not styled with the `.active` class. If I inspect the link, however, devtools shows me this: `` and the other links have `active:false`.\n\nSo it looks like the function is working, but my active style is not applied (the background color). What am I missing?\n\nI tried moving the Active class code to the SideNav component instead of the NavLink component and observed the same behavior. I could not figure it out, so I found a new method that works just fine.\n\nIn my **NavLink.svelte**:\n\n```\n\n import {onMount} from \"svelte\";\n import Icon from '$lib/Icon.svelte';\n\n let currentPath;\n onMount(() => {\n currentPath = window.location.pathname;\n });\n export let title;\n export let href;\n\n \n\n```\n\nAnd the rest of the code is the same. Now my links get the proper styling. It's worth noting that they simply have `` and not ``. Why wasn't it working with the other method?\n\n========================================\n\nTop Answer:\nTo achieve this in the latest version of SvelteKit, after the introduction of some breaking changes, you can do:\n\n```\n\n```\n\n`$page.url` returns something like:\n\n```\nURL { \n href: \"http://localhost:5173/accounts/login\", \n origin: \"http://localhost:5173\", \n protocol: \"HTTP:\", \n username: \"\", \n password: \"\", \n host: \"localhost:5173\", \n hostname: \"localhost\", \n port: \"5173\", \n pathname: \"/accounts/login\", \n search: \"\" \n}\n```\n\nYou can then compare `$page.url.pathname` with the `href` of the anchor tag.\n\n========================================\n\nCode:\n```text\n<script>\n import { page } from '$app/stores';\n import Icon from '$lib/Icon.svelte';\n export let title;\n export let href;\n</script>\n\n<a {href} class=\"link\" class:active={$page.path == href}>\n <Icon {title} />\n</a>\n\n<style>\na.active {\n background-color: rgba(0,0,0,0.24);\n</style>\n```\n\n```text\n<script>\n import NavLink from '$lib/NavLink.svelte';\n</script>\n\n<nav class=\"container\">\n <div id=\"links\">\n <NavLink href=\"/link1\" title=\"icon1\" />\n <NavLink href=\"/link2\" title=\"icon2\" />\n <NavLink href=\"/link3\" title=\"icon3\" />\n </div>\n</nav>\n```\n\n```text\n<SideNav />\n<slot />\n<Footer />\n```\n\n```text\n<script>\n import {onMount} from \"svelte\";\n import Icon from '$lib/Icon.svelte';\n\n let currentPath;\n onMount(() => {\n currentPath = window.location.pathname;\n });\n export let title;\n export let href;\n</script>\n\n<a {href} class:active={currentPath == href}>\n <Icon {title} />\n</a>\n```\n\n```text\n.active\n```\n\n```text\n<a class=\"link active:true\">\n```\n\n```text\nactive:false\n```\n\n```text\n<a class=\"active\">\n```\n\n```text\n<a class=\"active:true\">\n```\n\n```text\n<a {href} class:active=\"{$page.path.includes(href)}\">\n```\n\n```html\n<a {href} class:active={$page.url.pathname === href}>\n```\n\n```json\nURL { \n href: \"http://localhost:5173/accounts/login\", \n origin: \"http://localhost:5173\", \n protocol: \"HTTP:\", \n username: \"\", \n password: \"\", \n host: \"localhost:5173\", \n hostname: \"localhost\", \n port: \"5173\", \n pathname: \"/accounts/login\", \n search: \"\" \n}\n```\n\n```text\n$page.url\n```\n\n```text\n$page.url.pathname\n```\n\n```text\nhref\n```\n\n```text\n<a\n class:active={$page.url.pathname.split(\"/\")[1] ===item.href.split(\"/\")[1]}\n href={item.href}>\n {item.label}\n</a>\n```\n\n```text\na.active {\n background-color:red;\n }\n```\n\n```text\n<a href=\"/catalogue/123\" class:active={$page.route.id === '/catalogue/[id]'}>catalogue</a>\n```\n\n```text\n$page.route.id\n```\n\n```text\n/catalogue/123\n```\n\n```text\n$page.url.pathname\n```\n\n```text\n/catalogue/123\n```\n\n```text\n$page.route.id\n```\n\n```text\n/catalogue/[id]\n```\n\n```text\nitem = [{ link: '/hello/world/about', title: 'About }, ...]\n```\n\n```html\n<a href={item.link} class:active={$page.url.pathname === item.link}>{item.title}</a>\n```\n\n```text\nexport function isActive(page: Page<Record<string, string>>, path: string) {\n const pathname = page.url.pathname;\n return pathname === path;\n}\n```\n\n```html\n<a href={item.link} class:active={isActive($page, item.link)}>{item.title}</a>\n```\n\n```text\n$page\n```\n\n```text\n$page.url.pathname\n```\n\n```text\nitem.link\n```\n\n```text\n.navbar > a {\n color: white;\n}\n.active {\n color: blue;\n}\n```\n\n```text\na {\n color: white;\n}\n.active {\n color: blue;\n}\n```\n\n```text\n(.class > element) + .active\n```\n\n========================================\n\nComments:\n- I figured it out.... I think I just forgot to include quotes. D'oh. Working code (that also accounts for sub-pages) for the NavLink is: ``\n- I think the properties of `$page` might have changed since this was posted. What worked for me was `$page.url.pathname` rather than `$page.path`\n- In sveltekit 1.0 and later it's $page.url.pathname.includes(href)\n- Also two birds / one stone and comply with accessibility by assigning it to [ aria-current='page'] e.g. aria-current={$page.url.pathname === '/dashboard' ? 'page' : undefined} and using the css selector a[aria-current='page'] { ... style ... }","metadata":{"transformedAt":"2026-08-18T18:33:40.662Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":313,"estimatedTokens":1402}}72{"id":"stack-62445987","source":"stackoverflow","questionId":62445987,"title":"Svelte, on:click event inside each block triggers on page load","tags":["events","onclick","each","svelte","pageload"],"text":"Title: Svelte, on:click event inside each block triggers on page load\nTags: events, onclick, each, svelte, pageload\nSource: Stack Overflow\n\nQuestion:\nThe problem is that in svelte on:click triggers on page load for some reason. Can anybody explain to me why it's happening and how to prevent it so it only triggers when you actually check the box. This only happens if on:click is inside each block.\n\n```\n\n function handleClick(number) {\n alert(number)\n }\n let numbers = [1,2,3,4,5,6]\n\n{#each numbers as number}\n \n{/each}\n```\n\nYou can look at it here\n\n========================================\n\nCode:\n```text\n<script>\n function handleClick(number) {\n alert(number)\n }\n let numbers = [1,2,3,4,5,6]\n</script>\n{#each numbers as number}\n <input type=checkbox on:click={handleClick(number)}>\n{/each}\n```\n\n```html\n<p>{a} + {b} = {sum(a, b)}</p>\n```\n\n```html\n<input type=checkbox on:click={() => handleClick(number)}>\n```\n\n```text\non:click\n```\n\n```text\nsum\n```\n\n========================================\n\nComments:\n- Ty for the correct reply. Luckily as soon as I wrote the question I understood the problem and solved it in my project.","metadata":{"transformedAt":"2026-08-18T18:33:40.662Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":56,"estimatedTokens":287}}73{"id":"stack-61106423","source":"stackoverflow","questionId":61106423,"title":"How to put a Svelte app in a docker container?","tags":["node.js","docker","svelte"],"text":"Title: How to put a Svelte app in a docker container?\nTags: node.js, docker, svelte\nSource: Stack Overflow\n\nQuestion:\nThe title pretty much says it all. I am very new to web development. \n\nI created a Svelte app using `npx degit sveltejs/template ...`. Now I run it locally using `npm run dev` or `npm start`.\n\nTo my understanding, this is a Node server, but adapting their official tutorial didn't get me very far.\n\nI found a blog post about this, but it doesn't quite explain how to dockerize an existing Svelte app, instead points to a fork of the official template.\n\n========================================\n\nTop Answer:\nI noticed the answers are quite outdated and not what i needed, Let me help abit.\n\nThe main problem i faced was in deploying a svelte/sveltekit app with docker using a dockerfile for `production` and `optimized for production` as well.\n\nUsing the Dockerfile provided above one would have to update it to look like this:\n\nfor my instance i will make use of `pnpm` though, other package managers like `yarn` and `npm` can be used as well.\n\n```\nFROM node:jod-alpine AS build \n\nENV NODE_ENV=production \n\nWORKDIR /app\n\nCOPY package.json ./\nCOPY pnpm-lock.yaml ./\n\n# pnpm must be installed as it doesn't come with the default image\nRUN npm i -g pnpm\nRUN pnpm i\nCOPY . ./\nRUN pnpm build\n\n# Don't run production as root\nFROM gcr.io/distroless/nodejs22-debian12:nonroot AS prod \nWORKDIR /app\n\nENV NODE_ENV=production\nCOPY --from=installer /app/build ./build\nCOPY package.json .\nEXPOSE 3000\nCMD [ \"build\"]\n\n# ENV HOST is not needed though you can uncomment it if needed\n# ENV HOST=0.0.0.0\n# EXPOSE 4173\n\n# node is not needed as distroless:nonroot doesn't need node to be specified as user \nCMD [\"build\"]\n```\n\n**package.json{scripts}** \n\nthis is the script section for the package.json\n\n```\n\"scripts\": {\n \"dev\": \"vite dev\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\",\n \"check\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json\",\n \"check:watch\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch\",\n \"test:unit\": \"vitest run\",\n \"test:ui\": \"vitest --ui\",\n \"test:integration\": \"playwright test\",\n \"coverage\": \"vitest run --coverage\",\n \"lint\": \"prettier --check . && eslint .\",\n \"format\": \"prettier --write .\"\n},\n```\n\n**Note**: I would advice to only use `npm run preview` / `pnpm preview` only in local environment to ensure that the production version used will look the same,\nin Production after `pnpm build` only make use of `node build` which is optimized for production.\n\n========================================\n\nCode:\n```text\nnpx degit sveltejs/template ...\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm start\n```\n\n```text\nFROM node:14-alpine\n\nWORKDIR /usr/src/app\n\nCOPY rollup.config.js ./\nCOPY package*.json ./\n\nRUN npm install\n\nCOPY ./src ./src\nCOPY ./public ./public\n\nRUN npm run-script build\n\nEXPOSE 5000\n\nENV HOST=0.0.0.0\n\nCMD [ \"npm\", \"start\" ]\n```\n\n```text\n$ docker build -t svelte/myapp .\n```\n\n```text\n$ docker run -p 5000:5000 svelte/myapp\n```\n\n```text\nDockerfile\n```\n\n```text\npackage.json\n```\n\n```text\nFROM node:19 as build\n\nENV NODE_ENV=production \n\n\nWORKDIR /app\n\nCOPY package.json ./\nCOPY package-lock.json ./\nRUN npm install\nCOPY . ./\nRUN npm run build\n\n\nFROM node:19-alpine3.16\n\nWORKDIR /app\nCOPY --from=build /app .\n\n\nENV HOST=0.0.0.0\nEXPOSE 4173\nCMD [\"npm\",\"run\", \"preview\",\"--\", \"--host\", \"0.0.0.0\"]\n```\n\n```text\nPORT 4173\n```\n\n```text\nEXPOSE 4173\n```\n\n```text\n--host 0.0.0.0\n```\n\n```none\nFROM node:jod-alpine AS build \n\nENV NODE_ENV=production \n\nWORKDIR /app\n\nCOPY package.json ./\nCOPY pnpm-lock.yaml ./\n\n# pnpm must be installed as it doesn't come with the default image\nRUN npm i -g pnpm\nRUN pnpm i\nCOPY . ./\nRUN pnpm build\n\n# Don't run production as root\nFROM gcr.io/distroless/nodejs22-debian12:nonroot AS prod \nWORKDIR /app\n\nENV NODE_ENV=production\nCOPY --from=installer /app/build ./build\nCOPY package.json .\nEXPOSE 3000\nCMD [ \"build\"]\n\n# ENV HOST is not needed though you can uncomment it if needed\n# ENV HOST=0.0.0.0\n# EXPOSE 4173\n\n# node is not needed as distroless:nonroot doesn't need node to be specified as user \nCMD [\"build\"]\n```\n\n```json\n\"scripts\": {\n \"dev\": \"vite dev\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\",\n \"check\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json\",\n \"check:watch\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch\",\n \"test:unit\": \"vitest run\",\n \"test:ui\": \"vitest --ui\",\n \"test:integration\": \"playwright test\",\n \"coverage\": \"vitest run --coverage\",\n \"lint\": \"prettier --check . && eslint .\",\n \"format\": \"prettier --write .\"\n},\n```\n\n```text\nproduction\n```\n\n```text\noptimized for production\n```\n\n```text\npnpm\n```\n\n```text\nyarn\n```\n\n```text\nnpm\n```\n\n```text\nnpm run preview\n```\n\n```text\npnpm preview\n```\n\n```text\npnpm build\n```\n\n```text\nnode build\n```\n\n========================================\n\nComments:\n- Apologies for only now getting around to try your suggested solution. Thanks!\n- Can you modify your answer adding the steps to execute a build every time? Otherwise one would have to build manually before each Docker build. This is the code I ended up using. ``` FROM node:14-alpine WORKDIR /usr/src/app COPY rollup.config.js ./ COPY package*.json ./ RUN npm install COPY ./src ./src COPY ./public ./public RUN npm run-script build EXPOSE 5000 ENV HOST=0.0.0.0 CMD [ \"npm\", \"start\" ] ```\n- @ticofab i am failing to get any page back all I get Is 404 error from the docker image i have deployed on my was what could be the cause of it ?\n- @ticofab, I have managed to get the app to work from my the docker image on was but I see that it's failing to create the build folder in the public folder I have tried to change the commands in the docker file but its an issue still\n- Has anyone managed to make this work with Watch enabled on Rollup? I've mounted the /src directory in as a Volume and verified that the files inside the container are updated, but the `npm run dev` Rollup process which has watch enabled, is not reacting to the changes to the file.\n- @GarethOates Are you using Windows as host by any chance?\n- Yes I am. I'm guessing that's the problem?\n- My understanding is that Windows Hosts + Docker have problems with reloading/watching tasks like Rollup and Webpack. Could be completely FUD... Maybe make sure -you have the latest Docker version installed...\n- @GarethOates my current workaround (on windows with docker toolbox) is to run rollup on the host and sirv in the docker container in parallel and mirroring the src/ and public dirs as docker volumes. (Alternatively, mirroring public/ to a basic webserver container should be a simpler workaround.)\n- There is documentation for that: svelte-recipes.netlify.app/publishing\n- I have seen cases where they deploy the svelte app behind nginx. I am not sure what is better production wise.\n- Doesn't work. Show err: `failed to load config from /app/vite.config.ts error during build:` I'm using pnpm\n- I think you forgot to add the run command\n- @baldazi Which run... npm run or docker run?\n- @baldazi Build with `docker build -t website .` Run with `docker run -p 3000:3000 website`","metadata":{"transformedAt":"2026-08-18T18:33:40.662Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":276,"estimatedTokens":1782}}74{"id":"stack-45406206","source":"stackoverflow","questionId":45406206,"title":"How can I set a boolean attribute dynamically in Svelte?","tags":["svelte"],"text":"Title: How can I set a boolean attribute dynamically in Svelte?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nFirst attempt:\n\n```\nSave2\n```\n\ncauses an error during compile:\n\n```\nbundling...\n🚨 (svelte plugin) Error: (28:75) Expected >\n26: \n27: \n28: Save2\n ^\n```\n\nThe best I could come up with:\n\n```\n{{#if isDirty(item)}}\n Save\n{{else}}\n Save\n{{/if}}\n```\n\n========================================\n\nCode:\n```text\n<button type=\"submit\" class=\"button\" {{#if isDirty(item)}}disabled{{/if}}>Save2</button>\n```\n\n```text\nbundling...\n🚨 (svelte plugin) Error: (28:75) Expected >\n26: <div class=\"row\">\n27: <!-- FIXME Can't set an attribute dynamically? -->\n28: <button type=\"submit\" class=\"button\" {{#if isDirty(item)}}disabled{{/if}}>Save2</button>\n ^\n```\n\n```text\n{{#if isDirty(item)}}\n <button type=\"submit\" class=\"button\" disabled>Save</button>\n{{else}}\n <button type=\"submit\" class=\"button\">Save</button>\n{{/if}}\n```\n\n```js\n<button type=\"submit\" class=\"button\" disabled='{isDirty(item)}'>Save</button>\n```\n\n```text\ndisabled\n```\n\n========================================\n\nComments:\n- It is important that the `isDirty(item)` function only works if called with a parameter which is bound. In the example (and demo) above, that variable is `item`. So, simple a function like `isDirty()` wouldn't work.","metadata":{"transformedAt":"2026-08-18T18:33:40.662Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":68,"estimatedTokens":351}}75{"id":"stack-77518443","source":"stackoverflow","questionId":77518443,"title":"Disable certain a11y warnings globally in sveltekit","tags":["accessibility","svelte","sveltekit"],"text":"Title: Disable certain a11y warnings globally in sveltekit\nTags: accessibility, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nSveltekit has very strict a11y checks, for instance you can't just add `on:click` to a div.\n\nI can suppress it on a per-line bases, e.g.:\n\n```\n\n```\n\nBut how can I disable it globally?\n\n========================================\n\nTop Answer:\nI added `warningFilter` to `svelte.config.js`. And it worked.\n\n```\nconst config = {\n kit: {\n adapter: adapter()\n ...\n },\n compilerOptions: {\n warningFilter: (warning) => {\n const ignore = [\n 'a11y_media_has_caption',\n 'a11y_no_redundant_roles',\n 'a11y_consider_explicit_label',\n 'a11y_no_noninteractive_tabindex',\n 'a11y_click_events_have_key_events',\n 'a11y_no_static_element_interactions',\n 'a11y_no_noninteractive_element_interactions',\n ]\n return !ignore.includes(warning.code)\n },\n }\n};\n```\n\n========================================\n\nCode:\n```html\n<!-- svelte-ignore a11y-click-events-have-key-events -->\n<!-- svelte-ignore a11y-no-static-element-interactions -->\n<div on:click={handleClick}></div>\n```\n\n```text\non:click\n```\n\n```json\n\"svelte.plugin.svelte.compilerWarnings\": {\n \"a11y-click-events-have-key-events\": \"ignore\",\n \"a11y-no-static-element-interactions\": \"ignore\"\n}\n```\n\n```json\n\"rules\": {\n \"svelte/valid-compile\": [\"error\", { \"ignoreWarnings\": true }]\n}\n```\n\n```bash\nsvelte-check --fail-on-warnings --compiler-warnings \"a11y-click-events-have-key-events:ignore,a11y-no-static-element-interactions:ignore\"\n```\n\n```json\n\"scripts\": {\n ...\n \"check\": \"bash svelte-check.sh\",\n ...\n}\n```\n\n```js\nconst config = {\n onwarn: (warning, handler) => {\n // suppress warnings on `vite dev` and `vite build`; but even without this, things still work\n if (warning.code === \"a11y-click-events-have-key-events\") return;\n if (warning.code === \"a11y-no-static-element-interactions\") return;\n handler(warning);\n },\n kit: { adapter: adapter() },\n};\n```\n\n```text\n.vscode/settings.json\n```\n\n```text\nvalid-compile\n```\n\n```text\nplugin:svelte/recommended\n```\n\n```text\nsvelte-check\n```\n\n```text\nsvelte-check\n```\n\n```text\n--fail-on-warnings\n```\n\n```text\npackage.json\n```\n\n```text\nsvelte-check.sh\n```\n\n```text\npackage.json\n```\n\n```text\nvite dev\n```\n\n```text\nvite build\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nvite.config.js\n```\n\n```js\nconst config = {\n onwarn: (warning, handler) => {\n if (warning.code.startsWith('a11y-')) return;\n handler(warning);\n }\n};\n```\n\n```text\nsvelte.config.js\n```\n\n```bash\nsed -i 's/warn(pos, warning) {$/\\0 if (warning.code.includes(\"a11y\")) { return; }/' node_modules/svelte/compiler.cjs\n```\n\n```text\n# Execute this under your project root\n(Get-Content -Path \"node_modules\\svelte\\compiler.cjs\") -replace 'warn\\(pos, warning\\) {\\$', '$& if (warning.code.includes(\"a11y\")) { return; }' | Set-Content -Path \"node_modules\\svelte\\compiler.cjs\"\n```\n\n```json\n\"svelte.plugin.svelte.compilerWarnings\": {\n \"css-unused-selector\": \"ignore\",\n \"unused-export-let\": \"ignore\",\n \"a11y-aria-attributes\": \"ignore\",\n \"a11y-incorrect-aria-attribute-type\": \"ignore\",\n \"a11y-unknown-aria-attribute\": \"ignore\",\n \"a11y-hidden\": \"ignore\",\n \"a11y-autocomplete-valid\": \"ignore\",\n \"a11y-misplaced-role\": \"ignore\",\n \"a11y-no-static-element-interactions\": \"ignore\",\n \"a11y-unknown-role\": \"ignore\",\n \"a11y-no-abstract-role\": \"ignore\",\n \"svelte-ignore a11y-autofocus\": \"ignore\",\n \"a11y-no-redundant-roles\": \"ignore\",\n \"a11y-role-has-required-aria-props\": \"ignore\",\n \"a11y-accesskey\": \"ignore\",\n \"a11y-autofocus\": \"ignore\",\n \"a11y-misplaced-scope\": \"ignore\",\n \"a11y-positive-tabindex\": \"ignore\",\n \"a11y-invalid-attribute\": \"ignore\",\n \"a11y-missing-attribute\": \"ignore\",\n \"a11y-img-redundant-alt\": \"ignore\",\n \"a11y-label-has-associated-control\": \"ignore\",\n \"a11y-media-has-caption\": \"ignore\",\n \"a11y-distracting-elements\": \"ignore\",\n \"a11y-structure\": \"ignore\",\n \"a11y-mouse-events-have-key-events\": \"ignore\",\n \"a11y-missing-content\": \"ignore\",\n \"a11y-click-events-have-key-events\": \"ignore\",\n \"a11y-no-noninteractive-element-interactions\": \"ignore\"\n },\n```\n\n```js\nconst config = {\n preprocess: vitePreprocess(),\n onwarn: (warning, handler) => {\n if (warning.code.startsWith('a11y-')) return\n if (warning.code === 'missing-exports-condition') return\n if (warning.code === 'a11y-no-static-element-interactions') return\n if (warning.code === 'svelte-ignore a11y-autofocus') return\n if (warning.code.startsWith('css-unused-selector')) return\n handler(warning)\n },\n kit: {\n adapter: adapter(),\n },\n}\n```\n\n```text\nrole=\"presentation\"\n```\n\n```text\nrole=\"none\"\n```\n\n```text\nconst config = {\n kit: {\n adapter: adapter()\n ...\n },\n compilerOptions: {\n warningFilter: (warning) => {\n const ignore = [\n 'a11y_media_has_caption',\n 'a11y_no_redundant_roles',\n 'a11y_consider_explicit_label',\n 'a11y_no_noninteractive_tabindex',\n 'a11y_click_events_have_key_events',\n 'a11y_no_static_element_interactions',\n 'a11y_no_noninteractive_element_interactions',\n ]\n return !ignore.includes(warning.code)\n },\n }\n};\n```\n\n```text\nwarningFilter\n```\n\n```text\nsvelte.config.js\n```\n\n========================================\n\nComments:\n- Your third reason is not valid, buttons can have any size, it does not matter and the style is completely flexible. Just use a button.\n- some members of sveltejs team think a11y is political correctness, although a11y is not important for your project, in the case, these warnings just torment developers\n- Just a small note for copy/pasters like me: `\"ignoreWarnings\": false` should actually be `\"ignoreWarnings\": true` if you want eslint to leave you alone\n- @ryanovas you're right! I edited.\n- It seems that only warnings at build time can be suppressed\n- I do not know why but in my case, I had to use underscore \"a11y_click_events_have_key_events\" instead of hyphen \"a11y-click-events-have-key-events\".\n- it's 2024 and it seems the right place to put the error handling is in `compilerOptions.warningFilter` and use underscores instead of dashes as innomatic mentioned above.\n- Probably not a good idea to suppress all a11y warnings. This may work but it's bad practice.\n- That one is working. I think this is the proper way to deal with the issue. Tried configs but they stopped working for me.\n- I tried all of the other suggestions on this page and this is the only one that worked with the latest versions of Svelte/SvelteKit as of January 2025.\n- Only this solution will work with svelte kit 2.0 and svelte 5.0 in march 2025\n- agreed, this is what works for svelte as of April 2025 \"@sveltejs/kit\": \"^2.16.0\", \"@sveltejs/vite-plugin-svelte\": \"^5.0.0\", \"svelte\": \"^5.0.0\", \"svelte-check\": \"^4.0.0\", \"typescript\": \"^5.0.0\", \"vite\": \"^6.2.5\"\n- Can be made more generic with `warningFilter: (warning) => !warning.code.startsWith(\"a11y_\")`.","metadata":{"transformedAt":"2026-08-18T18:33:40.662Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":273,"estimatedTokens":1799}}76{"id":"stack-63255453","source":"stackoverflow","questionId":63255453,"title":"Running svelte dev on server","tags":["javascript","node.js","server","svelte"],"text":"Title: Running svelte dev on server\nTags: javascript, node.js, server, svelte\nSource: Stack Overflow\n\nQuestion:\nI am running svelte like this on my server:\n\n```\n$ npm run dev\n\n Your application is ready~! 🚀\n\n - Local: http://localhost:5000\n\n────────────────── LOGS ──────────────────\n```\n\nWhich is great. However, when I try to access through my public ip, the bundle is not found. I.E. When I type `:5000` into the browser. It doesn't show up. The port is open and accessible. Is there any way to achieve this?\n\nThe request just fails. But shouldn't it work if it's running on localhost:5000? I have set up a node server and I can indeed access it on port 5000, but it doesn't serve the files properly like `npm run dev` does.\n\n========================================\n\nTop Answer:\nActually, the message:\n\n```\nYour application is ready~!\n\n - Local: http://localhost:5000\n - Network: Add `--host` to expose\n```\n\nis telling you to put `--host` in`sirv public` instead of`rollup -c -w` which is a bit of a confusing message.\n\n```\n\"scripts\": {\n \"build\": \"rollup -c\",\n \"dev\": \"rollup -c -w\",\n \"start\": \"sirv public --host\"\n },\n```\n\n========================================\n\nCode:\n```text\n$ npm run dev\n\n\n Your application is ready~! 🚀\n\n - Local: http://localhost:5000\n\n────────────────── LOGS ──────────────────\n```\n\n```text\n<publicIP>:5000\n```\n\n```text\nnpm run dev\n```\n\n```sh\nHOST=0.0.0.0 npm run dev\n```\n\n```text\n\"scripts\": {\n \"build\": \"rollup -c\",\n \"dev\": \"HOST=0.0.0.0 rollup -c -w\",\n \"start\": \"sirv public\"\n },\n```\n\n```text\nHOST=0.0.0.0\n```\n\n```text\ndev\n```\n\n```text\npackage.json\n```\n\n```text\nHOST=0.0.0.0\n```\n\n```text\nnpm run dev\n```\n\n```bash\n# with Node.js\nnpm run dev -- --host\n\n# with Bun.sh\nbun run dev -- --host\n```\n\n```text\nYour application is ready~!\n\n - Local: http://localhost:5000\n - Network: Add `--host` to expose\n```\n\n```json\n\"scripts\": {\n \"build\": \"rollup -c\",\n \"dev\": \"rollup -c -w\",\n \"start\": \"sirv public --host\"\n },\n```\n\n```text\n--host\n```\n\n```text\nsirv public\n```\n\n```text\nrollup -c -w\n```\n\n```text\n\"scripts\": {\n \"dev\": \"svelte-kit dev\",\n \"special\": \"svelte-kit dev --host 0.0.0.0\",\n \"build\": \"svelte-kit build\",\n \"preview\": \"svelte-kit preview\",\n \"lint\": \"eslint --ignore-path .gitignore .\"\n },\n```\n\n```text\nC:\\Program Files\\nodejs\\npm.cmd run-script special -- --open\n\n> sveltekit_demo_app@0.0.1 special\n> svelte-kit dev --host 0.0.0.0 \"--open\"\n\n SvelteKit v1.0.0-next.118\n\n network: http://192.168.1.14:3000\n network: http://192.168.56.1:3000\n network: http://169.254.131.201:3000\n local: http://localhost:3000\n```\n\n```json\n{\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\",\n}\n```\n\n```text\npackege.json\n```\n\n========================================\n\nComments:\n- Can you just tell me how you figured that out?\n- I thought svelte used `sirv` in the back, so I googled how to do it for `sirv`. I'm still not sure it really uses sirv, it might just be a lucky standard, that's why the *possible source* is there\n- While I LOVE Svelte, its little things like this that makes it so frustrating!\n- They should add a link to @Treedbox's answer in that message that OP quoted. I tried a whole lot of stuff before discovering this, and now it works.\n- `-H` is the same.","metadata":{"transformedAt":"2026-08-18T18:33:40.662Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":176,"estimatedTokens":823}}77{"id":"stack-61569655","source":"stackoverflow","questionId":61569655,"title":"Svelte: Event forwarding with dispatcher vs passing in handling function, which is best practice?","tags":["svelte"],"text":"Title: Svelte: Event forwarding with dispatcher vs passing in handling function, which is best practice?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nLet's say an Outer component contains an Inner component, and we want an event from the Inner component to be propagated to the Outer component. Without using the store, there are 2 ways to do this:\n\n### Method 1: Event forwarding using dispatcher\n\nInner.svelte: Use Svelte's dispatcher to dispatch a repackaged version of the original event:\n\n```\n\nconst dispatcher = createEventDispatcher();\n\nfunction callDispatcher(e) {\n dispatcher(\"mymsg\", {\n foo: e.target.value\n });\n}\n```\n\nOuter.svelte: Listen for Inner's dispatched event:\n\n```\n\nfunction handler(e) {\n alert(e.detail.foo);\n}\n```\n\n### Method 2: Pass Outer's handler directly to Inner\n\nInner.svelte: Accepts handler passed in by Outer:\n\n```\nexport let externalHandler;\n\n```\n\nOuter.svelte: When Inner event of interest occurs, it will call Outer's handler:\n\n```\n\nfunction handler(e) {\n alert(e.target.value);\n}\n```\n\n### Question\n\nWhich one is a better practice? Method 1's dispatcher seems to be an unnecessary middle-layer that not only adds more code but also loses the original event information. But strangely, the Svelte tutorial mentions Method 1 instead of Method 2.\n\n========================================\n\nTop Answer:\nI find using **function prop** much simpler, more idiomatic, and does the job elegantly most of the time for me.\n\n```\n\n Click me\n\n```\n\nThe only case I use **event forwarding** is when I need to do... well... *event forwarding*. :) (from deeply nested component)\n\n```\n\n dispatch('customEvent')}>\n Click me\n\n```\n\nReference: https://www.donielsmith.com/blog/2020-04-21-props-vs-event-dispatcher-svelte-3/\n\n*Disclaimer: I'm new to Svelte, coming from React.* 🥳\n\n========================================\n\nCode:\n```js\n<input type=\"text\" on:input={callDispatcher} />\n\nconst dispatcher = createEventDispatcher();\n\nfunction callDispatcher(e) {\n dispatcher(\"mymsg\", {\n foo: e.target.value\n });\n}\n```\n\n```js\n<Inner on:mymsg={handler} />\n\nfunction handler(e) {\n alert(e.detail.foo);\n}\n```\n\n```js\nexport let externalHandler;\n<input type=\"text\" on:input={externalHandler} />\n```\n\n```js\n<Inner externalHandler={handler} />\n\nfunction handler(e) {\n alert(e.target.value);\n}\n```\n\n```html\n<Child clickHandler=\"{childClick}\" />\n<button on:click=\"{buttonClick}\">click</button>\n```\n\n```html\n<Child on:click=\"{childClick}\" />\n<button on:click=\"{buttonClick}\">click</button>\n```\n\n```text\ncreateEventDispatcher\n```\n\n```text\n.detail\n```\n\n```text\n<Thing1 {onClick} />\n```\n\n```html\n<!-- App.svelte -->\n<Button onClick={handleClick}></Button>\n\n<!-- Button.svelte -->\n<button on:click={onClick}>\n Click me\n</button>\n```\n\n```html\n<!-- App.svelte -->\n<Outer on:customEvent={handleCustomEvent} />\n\n<!-- Outer.svelte -->\n<Inner on:customEvent />\n\n<!-- Inner.svelte -->\n<Button on:customEvent />\n\n<!-- Button.svelte -->\n<button on:click={() => dispatch('customEvent')}>\n Click me\n</button>\n```\n\n========================================\n\nComments:\n- passing in handler functions is how React requires events to be handled - Svelte is a thin layer over the DOM - in the DOM one attaches an *arbitrary* number of listeners to an element. The element that the listener is attached to doesn't care that you are or aren't listening - it fires the events regardless. You can do what you want with those events with as many listeners as you want. I can't remember the last time I passed an event handler prop in Svelte after I realised how to leverage the event-driven approach - I learnt this via the Lit docs: lit.dev/docs/components/events\n- Thanks, good point. I had been wondering though, whether using the dispatcher method puts events into a queue to be actually emitted later, as opposed to immediate handling in the \"callback in props\" method whereby the callback is immediately run.\n- Not entirely sure, but afaik the dispatcher is a simple wrapper around createEvent, so it will be immediate as well\n- Agree, the only advantage of event forwarding is to avoid prop drilling through deeply nested components.\n- Event forwarding allows one to work with events in an event-driven manner, similarly to the DOM - you fire an event, and whoever wants to subscribe subscribes. *Listeners* are far more flexibly than explicitly passing down a single handler - you can attach an arbitrary number of listeners to an event: e.g. a request has succeeded - change the content + fire a new event + schedule a new request + call your grandmother - each defined in their own event handlers attached as separate listeners: svelte.dev/docs/element-directives#on-eventname. Function props are a React idiom, not Svelte!","metadata":{"transformedAt":"2026-08-18T18:33:40.662Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":169,"estimatedTokens":1182}}78{"id":"stack-68479217","source":"stackoverflow","questionId":68479217,"title":"How to load environment variables in Svelte using Vite or Svite","tags":["environment-variables","svelte","vite","dotenv"],"text":"Title: How to load environment variables in Svelte using Vite or Svite\nTags: environment-variables, svelte, vite, dotenv\nSource: Stack Overflow\n\nQuestion:\nI've been trying to figure out best practices on implementing environment variables for API configurations in Svelte App. As far as I know, We have to use either Vite or Svite to make it work. Can anyone help me find a solution please ??\n\n========================================\n\nTop Answer:\nThere seems to be some confusion around the security issues, but it's actually quite simple.\n\n**If you want to use insensitive information, proceed like this:**\n\n- create an `.env` and/or `.env.local`, `.env.production` file, read more here https://vitejs.dev/guide/env-and-mode.html#env-files\n\n- name your variable `VITE_` for example `VITE_API_URL` to store where your backend location is. That's not sensitive information so it's ok to expose this through your svelte app to the internet.\n\n- you can then access this directly inside of the script tags in svelte like this: `import.meta.env.VITE_API_URL`\n\n**If you have sensitive information:**\n\nThen you shouldn't expose it in a svelte client... PLEASE don't do something like suggested in Saad's answer and expose your API key to the public! Instead you'll need a server to securely hold that information, but how to setup a server is then again a different topic.\n\n========================================\n\nCode:\n```text\n├── sveltekit-project/ // Root\n| ├── src/\n| | ├── lib/\n| | | ├── env.js\n| | | ├── other.js\n| | | ... \n| | | \n| | ├── routes/\n| | | ├── main.svelte\n| | | ...\n| | ├── app.html\n| | ...\n| ├── .env\n```\n\n```text\n/** /src/lib/env.js **/\nimport dotenv from 'dotenv'\n\ndotenv.config()\n\nexport const env = process.env\n```\n\n```text\n/** /src/lib/other.js **/\nimport { env } from '$lib/env'\n\nconst secret = env.YOUR_SECRET\n```\n\n```text\n$lib\n```\n\n```text\nVITE_*\n```\n\n```text\nVITE_SENDGRID_API_KEY=SG.9999999999....999999999999\n```\n\n```text\nexport const ENV_OBJ = {\n SENDGRID_API_KEY: import.meta.env.VITE_SENDGRID_API_KEY,\n TEST: \"test, test, test\"\n};\n```\n\n```text\nimport { ENV_OBJ } from '$lib/env'\n// console.log(\"API Key.test: \", ENV_OBJ.TEST);\nsgMail.setApiKey(ENV_OBJ.SENDGRID_API_KEY);\n```\n\n```text\nVITE_\n```\n\n```text\nimport.meta.env.VITE_SECRET_PASSWORD\n```\n\n```text\n.env\n```\n\n```text\nsendgrid.env\n```\n\n```text\nenv.js\n```\n\n```text\nVITE_API_KEY=8465313163463435434353535\n```\n\n```text\nheaders: {\n \"X-RapidAPI-Key\": import.meta.env.VITE_API_KEY\n }\n```\n\n```text\n.env\n```\n\n```text\n.env.local\n```\n\n```text\n.env.production\n```\n\n```text\nVITE_<some name>\n```\n\n```text\nVITE_API_URL\n```\n\n```text\nimport.meta.env.VITE_API_URL\n```\n\n========================================\n\nComments:\n- Did you get an answer/solution specifically for svelte not sveltekit? Facing similar issue with Vite 4/Svelte. With Vite 3.x I was using dotenv and process.env and worked fine. Now, that works locally but not when deployed.\n- Your answer is useful for SvelteKit. But unfortunately I'm seeking solutions for Vanilla Svelte. If you can, help me with this. By the way thanks a lot for the detailed answer.\n- Found this, and helped me understand a bit more: vadosware.io/post/pattern-for-env-in-sveltekit\n- This seems to have disappeared from the FAQ for some reason\n- How is this the accepted answer? Although it might be useful for SvelteKit, the question was for Svelte only.\n- Do not do this. Everything that has the VITE_* prefix may be exposed in the client bundle. vitejs.dev/guide/env-and-mode.html#env-files \"Since any variables exposed to your Vite source code will end up in your client bundle, VITE_* variables should not contain any sensitive information.\"\n- Thanks a lot @Kansuler , your comment saved my @ss , I don't know how the f did I miss that security notice in vite docs when I first learnt about env vars. I came here by luck as well while searching how to access env vars in `.svelte` files :)\n- Normally I’d delete this answer, but as @a3k has shown, it’s a valuable warning of what not to do. Perhaps a “Warning, do not do this” edit to my original response might be appropriate.\n- Be aware that this variable will show up in the client bundle, and so anybody can access to your API key.\n- import.meta.env. works but when running tests with `jest unit` it fails.","metadata":{"transformedAt":"2026-08-18T18:33:40.662Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":151,"estimatedTokens":1090}}79{"id":"stack-74938552","source":"stackoverflow","questionId":74938552,"title":"How to not reset the form on submit with `use:enhance` in Svelte?","tags":["forms","svelte","sveltekit","progressive-enhancement"],"text":"Title: How to not reset the form on submit with `use:enhance` in Svelte?\nTags: forms, svelte, sveltekit, progressive-enhancement\nSource: Stack Overflow\n\nQuestion:\nI have a form that updates a product's information using a form with `use:enhance` and actions defined in `+page.server.ts` - However, whenever I submit the form, `use:enhance` resets the form elements and they all become blank, which is unexpected as the value for these elements is specified by `$page.data.product`, and the docs state that `use:enhance` runs `invalidateAll`.\n\nNonetheless, is there a way to stop this reset from occurring within the `use:enhance` function?\n\nhttps://i.sstatic.net/aw0zS.png\n\n========================================\n\nTop Answer:\nIf you return a function from the `use:enhance` action, that function will be called when you get a response from the form submit. This function in turn gets an `update` function which takes an option `reset` that you can give the value `false` to not reset the form:\n\n```\n\n import { enhance } from '$app/forms'\n\n {\n return async ({ update }) => {\n await update({ reset: false });\n };\n }}\n>\n \n Submit\n\n```\n\n========================================\n\nCode:\n```text\nuse:enhance\n```\n\n```text\n+page.server.ts\n```\n\n```text\nuse:enhance\n```\n\n```text\n$page.data.product\n```\n\n```text\nuse:enhance\n```\n\n```text\ninvalidateAll\n```\n\n```text\nuse:enhance\n```\n\n```html\n<script>\n import { enhance } from '$app/forms';\n</script>\n\n<form\n method=\"POST\"\n use:enhance={() => {\n return async ({ update }) => {\n update({ reset: false });\n };\n }}>\n <input type=\"text\" name=\"name\" />\n <button>Submit</button>\n</form>\n```\n\n```text\nreset: false\n```\n\n```text\nupdate\n```\n\n```text\nenhance\n```\n\n```html\n<script>\n import { enhance } from '$app/forms'\n</script>\n\n<form\n method=\"POST\"\n use:enhance={() => {\n return async ({ update }) => {\n await update({ reset: false });\n };\n }}\n>\n <input type=\"text\" name=\"name\" />\n <button>Submit</button>\n</form>\n```\n\n```text\nuse:enhance\n```\n\n```text\nupdate\n```\n\n```text\nreset\n```\n\n```text\nfalse\n```\n\n========================================\n\nComments:\n- Where are the API docs covering the `reset` argument?\n- @AndreyMikhaylov-lolmaus kit.svelte.dev/docs/types#public-types-submitfunction - You can see it in the type definition of the `SubmitFunction` argument provided to `use:enhance` here\n- It's in the reference section of the docs: svelte.dev/docs/kit/$app-forms#enhance\n- Where are the API docs covering the `reset` argument?\n- Great question - as far as I could tell there weren't any yet, which is what made finding this feature particularly tricky :)","metadata":{"transformedAt":"2026-08-18T18:33:40.663Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":133,"estimatedTokens":656}}80{"id":"stack-75137950","source":"stackoverflow","questionId":75137950,"title":"TypeError: Fetch failed in SvelteKit server-side rendering - Express does not show a proper TypeScript stack trace","tags":["javascript","typescript","express","svelte","sveltekit"],"text":"Title: TypeError: Fetch failed in SvelteKit server-side rendering - Express does not show a proper TypeScript stack trace\nTags: javascript, typescript, express, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am checking the logs of the SvelteKit SSR server using adapter-node.\n\nI have customised the `server.js` to use Express instead of Polka, though not sure if this matters.\n\nThere are apparent errors which I believe is when `fetch()` tries to read data from backend API and fails for some reason.\n\nThis is the console output from I get using `docker`:\n\n```\nfrontend | TypeError: fetch failed\nfrontend | at fetch (file:///app/build/handler.js:17895:14)\nfrontend | at async Object.fetch (file:///app/build/server/index.js:2273:12)\nfrontend | at async fetch (file:///app/build/server/index.js:991:24)\nfrontend | at async Promise.all (index 0)\nfrontend | at async load (file:///app/build/server/chunks/6-0becfa88.js:8:56)\nfrontend | at async load_data (file:///app/build/server/index.js:1088:16)\nfrontend | at async file:///app/build/server/index.js:1887:18\n```\n\nThis stack trace is unusable, because it lacks the information of what was the function / source code that called `fetch()`. Not sure if this is because of how Node.js / Express works, or because lack of TypeScript source map support in some part of the stack or something else. A SvelteKit project has dozens of functions called `load()` because that is what every router endpoint has.\n\nWhat would be a way to make these errors, and SvelteKit error handling in general, more descriptive - e.g. to show the proper caller mapped to its TypeScript source file, the failed page name, failed URL in `fetch()` and so on? This would then help to diagnose the underlying problem of what could be wrong with the API calls that fail.\n\n========================================\n\nTop Answer:\nYou can define `handleFetch()` inside `src/hooks.server.ts`. Then log both the requested URL and page from there:\n\n```\n// src/hooks.server.js\n\n/** @type {import('@sveltejs/kit').HandleFetch} */\nexport function handleFetch({ event, request, fetch }) {\n\n let fetchResult;\n try {\n fetchResult = await fetch(request);\n } catch (error) {\n // Log info from event and request here.\n }\n\n return fetchResult;\n}\n```\n\n========================================\n\nCode:\n```text\nfrontend | TypeError: fetch failed\nfrontend | at fetch (file:///app/build/handler.js:17895:14)\nfrontend | at async Object.fetch (file:///app/build/server/index.js:2273:12)\nfrontend | at async fetch (file:///app/build/server/index.js:991:24)\nfrontend | at async Promise.all (index 0)\nfrontend | at async load (file:///app/build/server/chunks/6-0becfa88.js:8:56)\nfrontend | at async load_data (file:///app/build/server/index.js:1088:16)\nfrontend | at async file:///app/build/server/index.js:1887:18\n```\n\n```text\nserver.js\n```\n\n```text\nfetch()\n```\n\n```text\ndocker\n```\n\n```text\nfetch()\n```\n\n```text\nload()\n```\n\n```text\nfetch()\n```\n\n```text\nconst config = {\n ...\n build:{\n sourcemap: true // Config vite to generate sourcemap when bundling.\n },\n ...\n}\n```\n\n```text\nnode index.js --enable-source-maps\n```\n\n```text\nvite.config.xx\n```\n\n```text\nsourcemap\n```\n\n```text\nsrc\n```\n\n```text\nbuild\n```\n\n```text\n// src/hooks.server.js\n\n/** @type {import('@sveltejs/kit').HandleFetch} */\nexport function handleFetch({ event, request, fetch }) {\n\n let fetchResult;\n try {\n fetchResult = await fetch(request);\n } catch (error) {\n // Log info from event and request here.\n }\n\n return fetchResult;\n}\n```\n\n```text\nhandleFetch()\n```\n\n```text\nsrc/hooks.server.ts\n```\n\n========================================\n\nComments:\n- This has been a bit of a pain point for me as well. Debugging the built code for Node.js is pretty tricky. You can comb through the built code and you might find some esbuild tags that could point you in the right direction.\n- async is a tool of a devil and the root cause of undebuggabilty. However, SvelteKit is now 1.0 and more and more people face this issue. Well-known or de facto standard solutions should be developing as we speak.\n- Thank you Leftium. This is quite excessive logging. Would you know if there is more generic solution available that would simply show the descriptive stack trace where the fetch() failed?\n- You can wrap `fetch()` in a try block and only log when it fails. I updated my answer. If fetch() doesn't throw an error, just check for the error status and log accordingly. @MikkoOhtamaa\n- Unfortunately, there is an open issue with Vite (and thus SvelteKit) that prevents source maps from being loaded: github.com/vitejs/vite/issues/3288\n- 🥲 oh snap - manual logging decoration it is then\n- That issue is about debugging. Server-side runtime stack traces use source maps just fine for me. I didn't need to specifically enable them in `vite.config` (that controls generation of client-side source maps), but I did need to put the `--enable-source-maps` *before* the script name, i.e.: `node --enable-source-maps build/`","metadata":{"transformedAt":"2026-08-18T18:33:40.663Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":153,"estimatedTokens":1257}}81{"id":"stack-71276448","source":"stackoverflow","questionId":71276448,"title":"Svelte - non-trivial intermediate variable within each loop","tags":["svelte","svelte-component"],"text":"Title: Svelte - non-trivial intermediate variable within each loop\nTags: svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nHow can I create variables inside Svelte's HTML like in React, or is it not at all how I am supposed to use Svelte. I know the example below is trivial but I'm thinking of a case where I really need some heavy logic for `subArray` (could not use a one liner)\n\n**React**\n\n```\n\n {myArray.map((item) => {\n const subArray = item.items.filter(i = i > 0) // \n```\n\n**Svelte**\n\n```\n\n {#each myArray as item}\n \n {#each as subItem}\n ...\n {/each}\n \n {/each}\n\n```\n\n========================================\n\nTop Answer:\nIf it's not too complicated you can directly modify the array inside `{#each}`\n\n```\n\n let myArray = [\n {id: 1, items: [-2,-1,0,1,2]},\n {id: 2, items: [-20,-10,0,10,20]},\n {id: 3, items: [-222,-111,0,111,222]},\n ]\n\n {#each myArray as item}\n \n {item.id}:\n {#each item.items.filter(item => item >= 0) as subItem}\n {subItem}, \n {/each}\n \n {/each}\n\n```\n\nor you could use the new `{@const}` directive\n\n```\n\n {#each myArray as item}\n {@const filteredItems = item.items.filter(i => i > 0)} \n \n {item.id}:\n {#each filteredItems as subItem}\n {subItem}, \n {/each}\n \n {/each}\n\n```\n\nAnd if it's even more complicated, why not extract the logic into a function\n\n```\nfunction complicatedModification(arr) {\n return arr.filter(item => item > 0)\n }\n\n...\n {#each complicatedModification(item.items) as subItem}\n {subItem}, \n {/each}\n...\n```\n\nHere's a REPL with all the options\n\n========================================\n\nCode:\n```js\n<ul>\n {myArray.map((item) => {\n const subArray = item.items.filter(i = i > 0) // <- how can I have an intermediate variable like this in Svelte?\n return <li>{subArray.map(...)}</li>\n }}\n</ul>\n```\n\n```html\n<ul>\n {#each myArray as item}\n <li>\n {#each <complex-logic> as subItem}\n ...\n {/each}\n </li>\n {/each}\n</ul>\n```\n\n```text\nsubArray\n```\n\n```js\n<ul>\n {#each myArray as item}\n {@const subArray = item.items.filter(i => i > 0)}\n <li>\n {#each subArray as subItem}\n ...\n {/each}\n </li>\n {/each}\n</ul>\n```\n\n```text\n{@const}\n```\n\n```text\n<script>\n let myArray = [\n {id: 1, items: [-2,-1,0,1,2]},\n {id: 2, items: [-20,-10,0,10,20]},\n {id: 3, items: [-222,-111,0,111,222]},\n ]\n</script>\n\n<ul>\n {#each myArray as item}\n <li>\n {item.id}:\n {#each item.items.filter(item => item >= 0) as subItem}\n {subItem}, \n {/each}\n </li>\n {/each}\n</ul>\n```\n\n```text\n<ul>\n {#each myArray as item}\n {@const filteredItems = item.items.filter(i => i > 0)} \n <li>\n {item.id}:\n {#each filteredItems as subItem}\n {subItem}, \n {/each}\n </li>\n {/each}\n</ul>\n```\n\n```text\nfunction complicatedModification(arr) {\n return arr.filter(item => item > 0)\n }\n</script>\n\n...\n {#each complicatedModification(item.items) as subItem}\n {subItem}, \n {/each}\n...\n```\n\n```text\n{#each}\n```\n\n```text\n{@const}\n```\n\n========================================\n\nComments:\n- I think the Svelte way would be to create `array of subArray` (possibly reactively with `$:`) in `` and do `{#each array as subArray}`.\n- I thought so too, but this gives an error? Have a look at my answer...\n- @Corrl see my comment to your answer ;)\n- `{@const` is what I was looking for\n- The error is possibly because you reuse the `item` variable name in your lambda?\n- Thank you both, I hadn't header about @const. The function is likely what I'll use.","metadata":{"transformedAt":"2026-08-18T18:33:40.663Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":195,"estimatedTokens":882}}82{"id":"stack-57354001","source":"stackoverflow","questionId":57354001,"title":"How to focus on input field loaded from component in Svelte?","tags":["input","autofocus","svelte"],"text":"Title: How to focus on input field loaded from component in Svelte?\nTags: input, autofocus, svelte\nSource: Stack Overflow\n\nQuestion:\nAfter loading the component that has input filed inside it. How can I focus on that particular field?\n\n**TextField.svelte**\n\n```\n\n export let label = ''\n export let name = ''\n export let placeholder = ''\n export let value = ''\n\n {label}\n \n \n\n```\n\n**App.svelte**\n\n```\n\n import TextField from './TextField'\n import {onMount} from 'svete'\n\n onMount(() => {\n // This line is funny.. I know\n document.querySelector('[name=\"firstname\"]').focus()\n })\n\n```\n\n========================================\n\nTop Answer:\nYou have several typos actually in the `App.svelte`.\n\nFirst, importing the component.\n\n```\nimport TextField from './TextField'\n```\n\nThat should be:\n\n```\nimport TextField from './TextField.svelte';\n```\n\nSecond, the Svelte package itself.\n\n```\nimport {onMount} from 'svete'\n```\n\nThat should be:\n\n```\nimport { onMount } from 'svelte';\n```\n\nOkay, now we are ready to code.\n\nSince `autofocus` attribute should be avoided, we may use Tholle's answer as reference.\n\nIn the `TextField.svelte`, you handle the *autofocus*.\n\n```\n\n import { onMount } from 'svelte';\n\n export let focused = false;\n export let label = '';\n export let name = '';\n export let placeholder = '';\n export let value = '';\n\n let elm;\n\n onMount(function() {\n elm.focus();\n });\n\n {label}\n \n \n\n```\n\nIn the `App.svelte`, you call the component.\n\n```\n\n import TextField from './TextField.svelte';\n\n```\n\nThe demo available on the Svelte REPL.\n\nThe difference between my answer and Tholle's is that `focus()` should be executed in the `TextField` component since it is component specific functionality.\n\n========================================\n\nCode:\n```text\n<script>\n\n export let label = ''\n export let name = ''\n export let placeholder = ''\n export let value = ''\n\n</script>\n\n<div class=\"field\">\n <label for={name}>{label}</label>\n <input {placeholder} type=\"text\" {name} bind:value={value} >\n <slot></slot>\n</div>\n```\n\n```text\n<script>\n import TextField from './TextField'\n import {onMount} from 'svete'\n\n onMount(() => {\n // This line is funny.. I know\n document.querySelector('[name=\"firstname\"]').focus()\n })\n\n</script>\n\n<TextField label=\"First Name\" name=\"firstname\" />\n```\n\n```html\n<!-- TextField.svelte -->\n<script>\n export let label = '';\n export let name = '';\n export let placeholder = '';\n export let value = '';\n export let ref = null;\n</script>\n\n<div class=\"field\">\n <label for={name}>{label}</label>\n <input {placeholder} type=\"text\" {name} bind:value={value} bind:this={ref} >\n <slot></slot>\n</div>\n\n<!-- App.svelte -->\n<script>\n import TextField from './TextField.svelte';\n import { onMount } from 'svelte';\n \n let ref;\n \n onMount(() => {\n ref.focus(); \n }); \n</script>\n\n<TextField label=\"First Name\" name=\"firstname\" bind:ref />\n```\n\n```text\nbind:this\n```\n\n```text\n<script>\n\n export let label = ''\n export let name = ''\n export let placeholder = ''\n export let value = ''\n\n</script>\n\n<div class=\"field\">\n <label for={name}>{label}</label>\n <input {placeholder} type=\"text\" {name} bind:value={value} autofocus > // <-- here\n <slot></slot>\n</div>\n```\n\n```text\nautofocus\n```\n\n```js\nimport TextField from './TextField'\n```\n\n```js\nimport TextField from './TextField.svelte';\n```\n\n```js\nimport {onMount} from 'svete'\n```\n\n```js\nimport { onMount } from 'svelte';\n```\n\n```js\n<script>\n import { onMount } from 'svelte';\n\n export let focused = false;\n export let label = '';\n export let name = '';\n export let placeholder = '';\n export let value = '';\n\n let elm;\n\n onMount(function() {\n elm.focus();\n });\n</script>\n\n<div class=\"field\">\n <label for={name}>{label}</label>\n <input {placeholder} type=\"text\" {name} bind:value={value} bind:this={elm}/>\n <slot/>\n</div>\n```\n\n```js\n<script>\n import TextField from './TextField.svelte';\n</script>\n\n<TextField label=\"First Name\" name=\"firstname\" focused/>\n<TextField label=\"Last Name\" name=\"lastname\" focused/>\n```\n\n```text\nApp.svelte\n```\n\n```text\nautofocus\n```\n\n```text\nTextField.svelte\n```\n\n```text\nApp.svelte\n```\n\n```text\nfocus()\n```\n\n```text\nTextField\n```\n\n========================================\n\nComments:\n- My question has typos. See below answer for reference.\n- Does this answer your question? How to focus on newly added inputs in Svelte?\n- Nowadays that'll trigger a warning: `A11y: Avoid using autofocussvelte(a11y-autofocus)`. So as the OP stated, probably not the way to go.\n- Have you tried this code? `ref.focus()` doesn't seem to work for me whereas I'm able to change other properties of element using `ref`.\n- What is 'ref' short for? It might be clearer to use a better variable name.\n- @mikemaccana - ref just short for reference, but it's commonly used in this context so for the sake of an example should be fine.\n- @Lissy93 what is `ref` a reference to? An element (just guessing)? It would be clearer to use `textfield` or `textfieldElement` or some other full word.\n- Not editing my question for silly typos so that the precious lines you wrote remain relevant :)\n- Notice that it's not the `autofocus` attribute that should be avoided, but rather *autofocus* itself, which is what this answer does anyway. All this does is get rid of the warning. Also, you should have an `await tick()` before calling focus otherwise your element may not exist. Lastly, you probably wanted to check for `if (focused)` before calling `elm.focus()`, otherwise that prop is useless.\n- You'd think the autofocus attribute would be encouraged, and then screen readers could simply *ignore* it. But I guess simple solutions are also discouraged. :)","metadata":{"transformedAt":"2026-08-18T18:33:40.663Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":282,"estimatedTokens":1424}}83{"id":"stack-61966179","source":"stackoverflow","questionId":61966179,"title":"Run a Svelte app from file:// with no server","tags":["javascript","svelte","svelte-3"],"text":"Title: Run a Svelte app from file:// with no server\nTags: javascript, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI need to run a Svelte app and be able to execute it without a server. \nWith other frameworks this is possible as it is just javascript but I can't find a way to just click my index.html and run my app built with Svelte\n\n========================================\n\nTop Answer:\nIf you're using Svelte (not SvelteKit) and has a single page only. You can use https://github.com/richardtallent/vite-plugin-singlefile to merge everything into one file on build, and it will then work through file://\n\n========================================\n\nCode:\n```text\n<link rel='icon' type='image/png' href='/favicon.png'>\n<link rel='stylesheet' href='global.css'>\n<link rel='stylesheet' href='/build/bundle.css'>\n\n<script defer src='/build/bundle.js'></script>\n```\n\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset='utf-8'>\n <meta name='viewport' content='width=device-width,initial-scale=1'>\n\n <title>Svelte app</title>\n\n <link rel='icon' type='image/png' href='favicon.png'>\n <link rel='stylesheet' href='global.css'>\n <link rel='stylesheet' href='build/bundle.css'>\n\n <script defer src='build/bundle.js'></script>\n</head>\n\n<body>\n</body>\n\n</html>\n```\n\n```text\nbuild\n```\n\n```text\nexecution\n```\n\n```text\nnpm run build\n```\n\n```text\npublic.html\n```\n\n```text\n/\n```\n\n========================================\n\nComments:\n- Hi vector. One of the answer posters below. We’d like clarification whether you mean to 1. Run the svelte app with roll up and build it (with npm etc) And then run the app WITHOUT a server (ie locally via file) ... Or, 2. Run and build svelte app WITHOUT server (including not running node on the build step)\n- Option 1 : Run the already built app locally via file://\n- Sure you can. I build android apps who are just html/css/js files embeded in a webwiew so this is a file:// protocol. Just write relative path in the index.html file to the bundle.css and bundle.js.\n- The post asks if they can run a svelte app without a http server. The screenshot clearly shows the create-svelte-app template on the browser with file://.\n- This was the first thing I did and it didn't work. Just now I've realized that I was using a router (github.com/jacwright/svelte-navaid) and this was causing the issues. I have switched to using hash-based routing and it solved the problem. Even though your answer did not solve my issue it is indeed the answer to what I wrote in the question and I will accept it as valid, thanks.\n- @DenisTsoi Let me just delete all my comments because extended comments on StackOverflow isn't good.","metadata":{"transformedAt":"2026-08-18T18:33:40.663Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":76,"estimatedTokens":668}}84{"id":"stack-72753092","source":"stackoverflow","questionId":72753092,"title":"How to proxy on Svelte-kit in dev mode","tags":["svelte","vite","sveltekit"],"text":"Title: How to proxy on Svelte-kit in dev mode\nTags: svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am trying to redirect for local development my requests to `/api/**` to my backend server.\n\nSo a request to `http://localhost:3000/api/upload` goes to `http://localhost:8080/api/upload`.\n\nI cannot find any `svelte.config.js` configuration, to get this to work for dev. Also `svelte-kit dev` does not provide this configuration (or I cannot find it).\n\nDoes anyone know how to do so in svelte-kit?\n\n========================================\n\nTop Answer:\nHere's the Typescript version (for those that need that).\n\n**vite.config.ts** (usually found at root)\n\n```\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\n\n// Docs: https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [svelte()],\n server: {\n proxy: {\n '/api': 'http://localhost:8080'\n }\n }\n})\n```\n\n========================================\n\nCode:\n```text\n/api/**\n```\n\n```text\nhttp://localhost:3000/api/upload\n```\n\n```text\nhttp://localhost:8080/api/upload\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nsvelte-kit dev\n```\n\n```js\nconst config = {\n // ...\n server: {\n proxy: {\n '/api': 'http://localhost:8080',\n },\n },\n};\n```\n\n```text\nvite.config.js\n```\n\n```text\nserver.proxy\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\n\n// Docs: https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [svelte()],\n server: {\n proxy: {\n '/api': 'http://localhost:8080'\n }\n }\n})\n```\n\n========================================\n\nComments:\n- In 2022 it's moved to `vite.config.js`, as you can see in svelte.kit docs.\n- @gyurielf the answer says exactly this, so your comment adds nothing.\n- @Coreus: That is because I updated it accordingly.\n- Do not edit the answer based whether you use single or double quotes. People's preferences are different and such edits are thus as biased as the answer.\n- I only see javascript","metadata":{"transformedAt":"2026-08-18T18:33:40.663Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":100,"estimatedTokens":507}}85{"id":"stack-72436530","source":"stackoverflow","questionId":72436530,"title":"Does SvelteKit relies on NodeJS?","tags":["svelte","sveltekit"],"text":"Title: Does SvelteKit relies on NodeJS?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nSvelteKit provides a \"skeleton\" for multi-page app, of which two features are particularly interesting for me: 1) a routing system (src/routes); 2) server-side rendering.\n\nMy question is: does SvelteKit rely on NodeJS? I use Go as backend server, which works well with VueJS frontend. I just simply copy the output of webpack (the dist folder) to my go source tree and compile it into a single executable.\n\nDoes that work with SvelteKit?\n\n**EDIT**\n\nBackground: I am primarily a Go programmer. Before I know Svelte, I purely uses Bootstrap + vanilla JS for frontend development. I've tried VueJS, but give up. The purpose of this question is to ask: **is it worth to learn SvelteKit or just Svelte?**\n\nIn another word, SSR is \"nice to have\" for me. However if the \"routing\" architecture does not work without Node, then I feel I'd better just go with Svelte, or, is there any other reason to choose SvelteKit?\n\n========================================\n\nTop Answer:\nThe server-side routing and rendering features of SvelteKit are tied to its implementation, which is in Node.\n\nIn particular, server-side rendering of Svelte components will unavoidably depend on Node at some level, because the Svelte compiler is written in TypeScript.\n\nSvelteKit is intended to be an all-in-one solution for web applications, but you can configure it instead to output a pre-rendered static site (see LeoDog896's answer), with client-side routing intact.\n\nIt should be trivial to set up a Go server to serve the static site so that routing works as expected. The only missing piece would be SSR, which is strongly tied to SvelteKit's own server implementation.\n\n========================================\n\nCode:\n```js\nimport adapter from '@sveltejs/adapter-static';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n kit: {\n adapter: adapter(),\n prerender: {\n default: true\n }\n }\n};\n\nexport default config;\n```\n\n```text\n@sveltejs/adapter-static@next\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nimport adapter from '@sveltejs/adapter-static';\n```\n\n```text\nprerender\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nnpm run build\n```\n\n```text\nbuild\n```\n\n========================================\n\nComments:\n- Technically, JS/TS does not directly imply Node, the latter could for example also run in Deno. But often there are dependencies on various NPM packages which are only compatible with Node.\n- True, I could have highlighted this distinction, though I took the question to be whether or not some kind of ECMAScript runtime is required.","metadata":{"transformedAt":"2026-08-18T18:33:40.663Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":80,"estimatedTokens":666}}86{"id":"stack-73831370","source":"stackoverflow","questionId":73831370,"title":"vitest crypto.randomUUID() is not a function","tags":["javascript","node.js","testing","svelte","vitest"],"text":"Title: vitest crypto.randomUUID() is not a function\nTags: javascript, node.js, testing, svelte, vitest\nSource: Stack Overflow\n\nQuestion:\n### vite.config.ts\n\n```\nimport { sveltekit } from '@sveltejs/kit/vite';\n\nconst config = {\n plugins: [sveltekit()],\n test: {\n include: ['**/*.spec.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],\n environment: 'jsdom',\n globals: true,\n setupFiles: 'src/setupTests.ts'\n }\n};\n\nexport default config;\n```\n\n### src/setupTests.ts\n\n```\nimport '@testing-library/jest-dom/extend-expect';\n```\n\n### MyComponent.svelte\n\n```\nonMount(() => {\n postElementId = crypto.randomUUID();\n ...\n});\n```\n\n### Error\n\n```\nTypeError: crypto.randomUUID is not a function\n```\n\nI've got a component that uses the crypto api to create a random id and works as intended, but when I want to test it, everytime I do this error pops up, any help is appreciated!\n\n========================================\n\nTop Answer:\nJust checking, did you:\n\n`import crypto from 'node:crypto';`\n\nat some point?\n\n========================================\n\nCode:\n```text\nimport { sveltekit } from '@sveltejs/kit/vite';\n\nconst config = {\n plugins: [sveltekit()],\n test: {\n include: ['**/*.spec.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],\n environment: 'jsdom',\n globals: true,\n setupFiles: 'src/setupTests.ts'\n }\n};\n\nexport default config;\n```\n\n```text\nimport '@testing-library/jest-dom/extend-expect';\n```\n\n```text\nonMount(() => {\n postElementId = crypto.randomUUID();\n ...\n});\n```\n\n```text\nTypeError: crypto.randomUUID is not a function\n```\n\n```text\ntest: {\n setupFiles: [\n './test/_setup/globalSetup.js'\n ],\n...\n```\n\n```text\nimport {randomUUID} from 'node:crypto';\nwindow.crypto.randomUUID = randomUUID;\n```\n\n```text\nwindow.crypto.randomUUID() is not a function\n```\n\n```text\nsetupFiles\n```\n\n```text\nglobalSetup.js\n```\n\n```text\nimport crypto from 'node:crypto';\n```\n\n```text\nvite-plugin-node-polyfills\n```\n\n========================================\n\nComments:\n- No, I'm using the built-in API :)\n- Yes, `environment: 'jsdom'` indicates a browser, not a nodejs environment. I'm experiencing this too.\n- Currently (May 5, 2023), the 'jsdom' environment is missing some crypto functionality, resulting in this error. There is an open issue for this on the jsdom Github repo, including a welcome from one of the maintainers for folks to submit a PR. There are also several workarounds listed there that may work. Specifically for vitest, Predrag's answer here is an awesome workaround in the interim - please upvote.\n- I got this to work for my unittest. Added the import in my spec.ts, added the window.crypto.randomUUID = randomUUID; in the beforeEach and now i can call window.crypto.randomUUID() in my test. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:40.663Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":129,"estimatedTokens":683}}87{"id":"stack-70927735","source":"stackoverflow","questionId":70927735,"title":"Pass variable up from page to svelte layout via slot","tags":["svelte","svelte-3","sveltekit"],"text":"Title: Pass variable up from page to svelte layout via slot\nTags: svelte, svelte-3, sveltekit\nSource: Stack Overflow\n\nQuestion:\nSo I can't figure a way to pass a variable up in my `__layout` variable from the component displayed in the ``.\n\nI tried a few things, using `bind:` or `let:` on the slot but it doesn't work. I get `'myvar' is not a valid binding` or ` cannot have directives`.\n\nI also tried to export or not the variable on the layout, but I really cannot make it work...\n\nHere is what I have:\n\n```\n\nexport let myvar = undefined;\n\n \n Layout myvar: {myvar}\n\n \n\n```\n\n```\n\nimport MyComponent from \"$lib/my_component.svelte\";\nexport let myvar;\nlet a_list_of_things = [1,2,3,4]\n\n {#each a_list_of_things as thing}\n \n {/each}\n mypage myvar: {myvar}\n\n \n\n```\n\n```\n\nimport IconButton from '@smui/icon-button'\n\nexport let myvar;\nexport let thing;\n\n myvar='something'} >\n autorenew\n \n\n```\n\nSo the main goal is to have an equivalent to `bind:myvar=myvar` on the layout level (for the ``.\n\nI tried understanding the documentation about it without much success, it seems to be more about the component slot than the layout one.\n\nI found this other question which advise to use a store in sapper (the old name for sveltekit) not sure it is up to date with the last version of sveltekit, is this the way to go ? Or is there another way ?\n\nSomeone else advise using a context. What do you think ?\n\nWhy do i need this ?\n\nSo I have the structure of my app like this:\n\n```\n__layout\n ├─ header (menu)\n ├─ my_page ()\n │ └ my_component (many)\n └ interactive banner\n```\n\nThat display it like so:\n\n```\n[ Header Menu ]\n\nContent of the page\n - component 1\n - component 2\n - component n\n\n[ Current component: 2 ] The `component` define what the interactive banner should display. Also clicking on the `interactive banner` can change the state displayed in the `components`\n\n========================================\n\nTop Answer:\nI give below an example with named slots, also unnamed ->\n\n**In Slot.svelte**\n\n```\n\n let content ='lorem'\n\n{content}\n\n```\n\n**In Parent component**\n\n```\n\n import Data from './Slot.svelte'\n let newData=' new content'\n\n \n \n \n {newData} \n \n\n \n```\n\n*And exmaple for unnamed slot ->*\n\n**In Slot.svelte**\n\n```\n\n let content ='lorem'\n \n \n \n {content}\n \n```\n\n**In Parent component**\n\n```\n\n import Data from './Slot.svelte'\n let newData=' new content'\n\n \n \n\n \n {newData}\n \n```\n\n========================================\n\nCode:\n```html\n<!-- __layout.svelte -->\n<script>\nexport let myvar = undefined;\n</script>\n\n<main>\n <slot myvar={myvar}></slot>\n <p>Layout myvar: {myvar}</p> <!-- << This will stay undefined -->\n</main>\n```\n\n```html\n<!-- mypage.svelte -->\n<script>\nimport MyComponent from \"$lib/my_component.svelte\";\nexport let myvar;\nlet a_list_of_things = [1,2,3,4]\n</script>\n\n<main>\n {#each a_list_of_things as thing}\n <MyComponent bind:myvar={myvar} thing={thing}/> <!-- The variable is binded here -->\n {/each}\n <p>mypage myvar: {myvar}</p> <!-- << This will get the good value -->\n</main>\n```\n\n```html\n<!-- my_component.svelte -->\n<script>\nimport IconButton from '@smui/icon-button'\n\nexport let myvar;\nexport let thing;\n</script>\n\n<div>\n <IconButton class=\"material-icons\" on:click={() => myvar='something'} >\n autorenew\n </IconButton> <!-- << We change the value on:click here -->\n\n</div>\n```\n\n```text\n__layout\n ├─ header (menu)\n ├─ my_page (<slot>)\n │ └ my_component (many)\n └ interactive banner\n```\n\n```text\n[ Header Menu ]\n\nContent of the page\n - component 1\n - component 2\n - component n\n\n[ Current component: 2 ] << Updated when click on an elem in the component\n```\n\n```text\n__layout\n```\n\n```text\n<slot>\n```\n\n```text\nbind:\n```\n\n```text\nlet:\n```\n\n```text\n'myvar' is not a valid binding\n```\n\n```text\n<slot> cannot have directives\n```\n\n```text\nbind:myvar=myvar\n```\n\n```text\n<slot></slot>\n```\n\n```text\ncomponent\n```\n\n```text\ninteractive banner\n```\n\n```text\ncomponents\n```\n\n```js\n// src/lib/message.js\nimport { writable } from 'svelte/store';\n\nexport default writable('Default message');\n```\n\n```svelte\n<!-- src/routes/__layout.svelte -->\n<script>\n import message from '$lib/message';\n</script>\n\n<slot />\n<p>{$message}</p>\n```\n\n```text\n<!-- src/routes/index.svelte -->\n<script>\n import message from '$lib/message';\n\n function update() {\n $message = 'New message';\n }\n</script>\n\n<h1>Hello World</h1>\n\n<button on:click={update}>Update message</button>\n```\n\n```text\n<script>\n let content ='lorem'\n</script>\n\n\n<slot name='named-slot' >\n{content}\n</slot>\n```\n\n```text\n<script>\n import Data from './Slot.svelte'\n let newData=' new content'\n</script>\n\n \n <Data> \n <svelte:fragment slot='named-slot' let:newData={content}>\n {newData} \n </svelte:fragment>\n\n </Data>\n```\n\n```text\n<script>\n let content ='lorem'\n </script>\n \n <slot >\n {content}\n </slot>\n```\n\n```text\n<script>\n import Data from './Slot.svelte'\n let newData=' new content'\n</script>\n \n \n\n <Data let:newData={content}> \n {newData}\n </Data>\n```\n\n========================================\n\nComments:\n- But this doesn't work with a layout, has the slot is defined by the route ? or Am I missing something ?\n- Thanks a lot, that worked ! Could you add an explanation of the magic behind please ? I think it is important to understand why we do things...\n- In `message.js` we create and export Svelte store. Any component can import and subscribe to the store with the `$store` syntax. When the store is updated, anyone subscribing to the store will be notified. This allows us to update the store in `index.svelte` and automatically receive the new value in `__layout.svelte`. I highly recommend going through the Svelte tutorial on stores if you haven't already, since they're an important Svelte concept.\n- This answer clearly gives a solution, but is it the only solution? Is there a way to bind to a or doesn't that work at all?","metadata":{"transformedAt":"2026-08-18T18:33:40.663Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":343,"estimatedTokens":1465}}88{"id":"stack-66959301","source":"stackoverflow","questionId":66959301,"title":"Svelte - Extend standard html elements with typescript","tags":["typescript","svelte"],"text":"Title: Svelte - Extend standard html elements with typescript\nTags: typescript, svelte\nSource: Stack Overflow\n\nQuestion:\nI would like to define my custom component and specify which kind of \"standard component\" I would to extend.\n\nThis to consume VSCode intellisense for all standard attributes of the extended component without re-define all attributes.\n\nThis is what I would to do:\n\n```\n\n // Error: Cannot redeclare block-scoped variable '$$props'\n export let $$props: svelte.JSX.HTMLAttributes;\n\n // OR\n\n // Error: Cannot redeclare block-scoped variable '$$restProps'\n export let $$restProps: svelte.JSX.HTMLAttributes;\n\n export let myCustomProp: string;\n\n{myCustomProp}\n```\n\nTo explain better what I would like to do, I post the same case in React with Typescript:\n\n```\nimport React from 'react';\n\ntype Props = {\n myCustomProp: string;\n} & React.ButtonHTMLAttributes;\nexport default function ({ myCustomProp, ...rest }: Props) {\n return (\n \n {myCustomProp}\n {rest.children}\n \n );\n}\n```\n\n========================================\n\nTop Answer:\nThis worked for me with `@render` and `$props` runes\n\n**button.svelte**\n\n```\n\n import { type HTMLButtonAttributes } from 'svelte/elements';\n\n interface ButtonProps extends HTMLButtonAttributes {\n mycustomProp: string;\n }\n\n let { children, mycustomProp, ...rest }: ButtonProps = $props();\n\n {mycustomProp}\n {@render children?.()}\n\n```\n\n**usage**\n\n```\n\n import Button from 'button.svelte';\n\nbeep\n```\n\n========================================\n\nCode:\n```html\n<script lang=\"ts\">\n // Error: Cannot redeclare block-scoped variable '$$props'\n export let $$props: svelte.JSX.HTMLAttributes<HTMLButtonElement>;\n\n // OR\n\n // Error: Cannot redeclare block-scoped variable '$$restProps'\n export let $$restProps: svelte.JSX.HTMLAttributes<HTMLButtonElement>;\n\n export let myCustomProp: string;\n</script>\n\n<button {...$$restProps}>{myCustomProp}<slot /></button>\n```\n\n```js\nimport React from 'react';\n\ntype Props = {\n myCustomProp: string;\n} & React.ButtonHTMLAttributes<HTMLButtonElement>;\nexport default function ({ myCustomProp, ...rest }: Props) {\n return (\n <button {...rest}>\n {myCustomProp}\n {rest.children}\n </button>\n );\n}\n```\n\n```html\n<script lang=\"ts\">\n import type { HTMLButtonAttributes } from 'svelte/elements'\n\n interface $$Props extends HTMLButtonAttributes {\n myCustomProp: string\n }\n\n export let myCustomProp: string\n</script>\n\n<button {...$$restProps}>\n {myCustomProp}\n <slot />\n</button>\n```\n\n```html\n<script lang=\"ts\">\n import Button from './Button.svelte'\n\n let disabled = false\n</script>\n\n<Button myCustomProp='foo' {disabled}>Click Me</Button>\n```\n\n```text\nexport let myCustomProp: $$Props[\"myCustomProp\"]\n```\n\n```text\nsvelte/elements\n```\n\n```text\ninterface $$Props\n```\n\n```text\nButton.svelte\n```\n\n```text\n+page.svelte\n```\n\n```text\n$$Props\n```\n\n```html\n<script lang=\"ts\">\n import { type HTMLButtonAttributes } from 'svelte/elements';\n\n interface ButtonProps extends HTMLButtonAttributes {\n mycustomProp: string;\n }\n\n let { children, mycustomProp, ...rest }: ButtonProps = $props();\n</script>\n\n<button {...rest}>\n {mycustomProp}\n {@render children?.()}\n</button>\n```\n\n```text\n<script lang=\"ts\">\n import Button from 'button.svelte';\n</script>\n\n<Button mycustomProp=\"custom\">beep</Button>\n```\n\n```text\n@render\n```\n\n```text\n$props\n```\n\n```js\nimport('svelte/elements').SvelteHTMLElements['div']\n```\n\n```text\n<script lang=\"ts\">\n let {\n customProp,\n ...props\n }: { customProp: string } & import('svelte/elements').SvelteHTMLElements['img'] = $props()\n</script>\n\n<span>{customProp}</span>\n<img {...props} />\n```\n\n```text\n<script lang=\"ts\" generics=\"T extends keyof import('svelte/elements').SvelteHTMLElements\">\n let {\n tag,\n customProp,\n ...props\n }: { tag: T, customProp: string } & import('svelte/elements').SvelteHTMLElements[T] = $props()\n</script>\n\n<svelte:element this={tag} {...props} />\n```\n\n========================================\n\nComments:\n- I had a similar kind of issue, maybe the discussion on github will help you: github.com/sveltejs/svelte/issues/6067\n- Thanks, same needs. No solutions for now\n- Is this really the best way to do this? In this example you have duplicated type definitions, e.g you define `myCustomProp` inside the interface, and then again you must export it with type defintion from the script tag\n- Is it the best way? I'm not sure, but it appears to be the only way to do it from what I've seen, that said you could define the type and then use it for both definitions if you had a more complex type scenario. If you know a better way let me know :)\n- github.com/sveltejs/language-tools/issues/2016 Opened an Issue about this , DX can definetly be improved\n- FYI: it is important for the type import to be declared exactly as shown. `import {type HTMLButtonAttributes} ...` results in error: `[vite] Internal server error: No known conditions for \"./elements\" specifier in \"svelte\" package`\n- In Svelte v5 we won't need to do this anymore and can just type the `$props` rune, thankfully!","metadata":{"transformedAt":"2026-08-18T18:33:40.663Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":232,"estimatedTokens":1271}}89{"id":"stack-67921198","source":"stackoverflow","questionId":67921198,"title":"Sveltekit and SSR","tags":["server-side-rendering","svelte","sveltekit"],"text":"Title: Sveltekit and SSR\nTags: server-side-rendering, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI need a bit of help understanding SSR in the context of sveltekit. I noticed that the `load` method is called both on the server and the client and I cannot wrap my head around this. I guess it is needed to initialize the state of the client-side component, but why not just pass the props resulting from the SSR to the client?\n\nWhat if a database request needs to be done during SSR? Now that same database request is repeated from the client? What if that is not even possible? I understand that I can use `browser` from `$app/env` to run different code on the server and in the browser but what props do I return? Is there any way to pass data from the server-side invocation of `load` to the client-side invocation?\n\n========================================\n\nCode:\n```text\nload\n```\n\n```text\nbrowser\n```\n\n```text\n$app/env\n```\n\n```text\nload\n```\n\n```html\n<script context=\"module\">\n export async function load({ fetch }) {\n const data = await fetch('/data.json').then(r => r.json());\n const model = create_model(data);\n\n return {\n props: { model }\n };\n }\n</script>\n\n<script>\n export let model;\n</script>\n\n<h1>{$model.title}</h1>\n```\n\n```html\n<script context=\"module\">\n export async function load({ fetch }) {\n const compressed = await fetch('/compressed-data.json').then(r => r.json());\n const data = decompress(compressed);\n\n return {\n props: { data }\n };\n }\n</script>\n```\n\n```text\nload\n```\n\n```text\nload\n```\n\n```text\nfetch\n```\n\n```text\nload\n```\n\n```text\nload\n```\n\n```text\nfetch\n```\n\n========================================\n\nComments:\n- +1 Thanks a lot! The use of an endpoint and the fact that fetches from `load` are essentially only done on the server and then cached really clears things up for me.\n- But what if you need to fetch with urql or apollo... then how do you pass the data? It does not use fetch...\n- I find ssr with svelte kit to be useless unless you doing unauthenticated routes. If you use localStorage for your jwt then you cant make authenticated requests to api using ssr.","metadata":{"transformedAt":"2026-08-18T18:33:40.664Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":90,"estimatedTokens":536}}90{"id":"stack-60529034","source":"stackoverflow","questionId":60529034,"title":"Svelte Custom element API","tags":["svelte","svelte-3","svelte-component"],"text":"Title: Svelte Custom element API\nTags: svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI have doubts about how to create a Custom element API. I have followed the documentation, but I get the following warning:\n\nThe 'tag' option is used when generating a custom element. Did you\nforget the 'customElement: true' compile option? (Link.svelte: 1:16)\n\nREPL\n\nI have marked `customElement: true` in compiler options.\n\nI'm lost, can anyone help me?\n\n========================================\n\nTop Answer:\nTo eliminate the linter's error on `` this line in my myComponent.svelte, I added the compilerOptions to the **svelte.config.js** and not any other files:\n\n```\nexport default {\n preprocess: vitePreprocess(),\n compilerOptions: {\n customElement: true,\n },\n}\n```\n\nThe error was exactly the same as in the question above.\n\n========================================\n\nCode:\n```text\ncustomElement: true\n```\n\n```js\nplugins: [\n svelte({\n compilerOptions: {\n customElement: true,\n ...\n }\n ...\n }),\n ...\n ]\n```\n\n```text\n<svelte:options tag=\"what-ever\" />\n\n<script>\n // make sure component Foo is available, but we don't import\n // it... we'll use it with it's tag <my-foo /> (see bellow)\n import './Foo.svelte'\n export let name = 'World'\n</script>\n\n<p>Hello, {name}!</p>\n\n<my-foo {name} />\n\n<style>\n p { color: skyblue; }\n</style>\n```\n\n```text\n<svelte:options tag=\"my-foo\" />\n\n<script>\n export let name\n</script>\n\n<p>I am {name}</p>\n```\n\n```html\n<script defer src='/build/bundle.js'></script>\n```\n\n```js\ndocument.body.querySelector('#container').innerHTML = '<what-ever>Foo</what-ever>'\n```\n\n```html\n<body>\n <what-ever>foo</what-ever>\n</body>\n```\n\n```js\nimport App from './App.svelte';\n\n// NOT needed with custom elements\n//const app = new App({\n// target: document.body,\n// props: {\n// name: 'world'\n// }\n//});\n\nexport default app;\n```\n\n```text\ncustomElement: true\n```\n\n```text\n<svelte:options tag=\"what-ever\" />\n```\n\n```text\nFoo.svelte\n```\n\n```text\ntag\n```\n\n```text\nimport './Foo.svelte'\n```\n\n```text\nbundle.js\n```\n\n```text\nbundle.js\n```\n\n```text\n<div>\n```\n\n```text\n<strong>\n```\n\n```text\nindex.html\n```\n\n```text\n.js\n```\n\n```text\nApp\n```\n\n```text\n.svelte\n```\n\n```text\nmain.js\n```\n\n```text\nbundle.js\n```\n\n```text\nmain.js\n```\n\n```text\nexport default {\n preprocess: vitePreprocess(),\n compilerOptions: {\n customElement: true,\n },\n}\n```\n\n```text\n<svelte:options tag=\"what-ever\" />\n```\n\n```html\n<svelte:options customElement=\"my-component\" />\n<script>\n export let name = 'World';\n</script>\n\n<style>\n h1 {\n color: royalblue;\n }\n</style>\n\n<h1>Hello {name}!</h1>\n```\n\n```text\nimport { compile } from 'svelte/compiler';\nimport fs from 'fs/promises';\n\nconst inputFile = 'MyComponent.svelte';\nconst outputFile = 'MyComponent.js';\n\nasync function build() {\n const source = await fs.readFile(inputFile, 'utf8');\n const { js } = compile(source, {\n customElement: true, // Enables custom element compilation\n filename: inputFile,\n });\n\n await fs.writeFile(outputFile, js.code);\n console.log(`Compiled ${inputFile} to ${outputFile}`);\n}\n\nbuild();\n```\n\n```text\n$ npm i svelte\n$ nodejs build.js\n```\n\n```text\nimport 'svelte/internal/disclose-version';\nimport 'svelte/internal/flags/legacy';\nimport * as $ from 'svelte/internal/client';\n\nvar root = $.template(`<h1 class=\"svelte-11kgty1\"> </h1>`);\n\nconst $$css = {\n hash: 'svelte-11kgty1',\n code: 'h1.svelte-11kgty1 {color:royalblue;}'\n};\n\nexport default function MyComponent($$anchor, $$props) {\n $.push($$props, false);\n $.append_styles($$anchor, $$css);\n\n let name = $.prop($$props, 'name', 12, 'World');\n var h1 = root();\n var text = $.child(h1);\n\n $.reset(h1);\n $.template_effect(() => $.set_text(text, `Hello ${name() ?? ''}!`));\n $.append($$anchor, h1);\n\n return $.pop({\n get name() {\n return name();\n },\n set name($$value) {\n name($$value);\n $.flush_sync();\n }\n });\n}\n\ncustomElements.define('my-component', $.create_custom_element(MyComponent, { name: {} }, [], [], true));\n```\n\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Svelte Custom Element</title>\n <script type=\"importmap\">\n {\n \"imports\": {\n \"svelte/\": \"https://esm.run/svelte/\"\n }\n }\n </script>\n <script src=\"MyComponent.js\" type=\"module\"></script>\n\n</head>\n<body>\n <p>The source code should be between this: </p>\n\n <my-component name=\"Svelte\"></my-component>\n \n <p>and this</p>\n</body>\n</html>\n```\n\n```text\n$ npx http-server .\n```\n\n```text\nMyComponent.svelte\n```\n\n```text\nbuild.js\n```\n\n```text\nMyComponent.js\n```\n\n========================================\n\nComments:\n- Are you just seeing this in the REPL, or locally as well?\n- In both. Although I solved the problem by including `` in App.svelte.\n- Regarding your statement \"you can't mix and match custom element components with normal components\", this repo has a workaround: github.com/jawish/svelte-customelement-rollup\n- I disagree with the statement, that regular Svelte components and custom element components cannot be mixed. Just define two subsequent svelte plugin blocks in the rollup.config.json. One for each kind of component. These have to use include or exclude statements to make sure to only include the desired files. See github.com/sveltejs/rollup-plugin-svelte.\n- This worked for my scenario, I am using typescript.","metadata":{"transformedAt":"2026-08-18T18:33:40.664Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":35,"totalLines":316,"estimatedTokens":1380}}91{"id":"stack-62097466","source":"stackoverflow","questionId":62097466,"title":"How to use Font Awesome 5 with Svelte/Sappe","tags":["font-awesome","svelte","sapper"],"text":"Title: How to use Font Awesome 5 with Svelte/Sappe\nTags: font-awesome, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI am writing a Server Side Rendered app with Svelte/Sapper and I am having trouble using Font Awesome fonts.\n\nI am using the following to load the font:\n\n```\n\n import Icon from \"svelte-awesome\";\n import { faTimes } from \"@fortawesome/free-solid-svg-icons/faTimes\";\n\n```\n\nThe error I am seeing is:\n\" is not a valid SSR component. You may need to review your build config to ensure that dependencies are compiled, rather than imported as pre-compiled modules\"\n\nIs there a solution to this?\n\n========================================\n\nTop Answer:\nAfter spending 5 hours trying to figure it out, finally here's the simplest way to use Fontawesome icons in Sveltekit (also works in **production** environment):\n\nInstall the fontawesome package\n\n```\nnpm install @fortawesome/fontawesome-free\n```\n\nImport the css file containing all icons in the component or page where you need it. (Can also be imported in `+layout.ts` to apply to multiple pages)\n\n```\nimport '@fortawesome/fontawesome-free/css/all.min.css'\n```\n\nYou can now use your icons in the simple classical way:\n\n```\n\n```\n\nI hope this helps!\n\n========================================\n\nCode:\n```text\n<script>\n import Icon from \"svelte-awesome\";\n import { faTimes } from \"@fortawesome/free-solid-svg-icons/faTimes\";\n</script>\n\n<Icon data={faTimes} />\n```\n\n```html\n<head>\n ...\n <link href=\"./../node_modules/@fortawesome/fontawesome-free/css/all.min.css\" rel=\"stylesheet\">\n ...\n</head>\n```\n\n```text\n<head>\n```\n\n```text\nnpm install --save @fortawesome/fontawesome-free\n```\n\n```text\n<head>\n```\n\n```text\napp.html\n```\n\n```text\n<i class=\"fa-regular fa-lightbulb\">\n```\n\n```text\nimport Icon from 'svelte-awesome/components/Icon';\n```\n\n```text\nnpm install @fortawesome/fontawesome-free\n```\n\n```js\nimport '@fortawesome/fontawesome-free/css/all.min.css'\n```\n\n```html\n<i class=\"fa-regular fa-lightbulb\">\n```\n\n```text\n+layout.ts\n```\n\n========================================\n\nComments:\n- Are you sure that your import is correct? Can you try without the curly braces? Please check this REPL: svelte.dev/repl/9905305c60bc46d99b6c52f1736eaba8?version=3.2‌​3.0\n- With straight Svelte this works. With the server-side rendering of Sapper, however, it does not work.\n- any fixes? same issue...\n- The OP isn't intending to rely on third party packages\n- Note you also need the js. I choose to import both in `main.js`: `import '@fortawesome/fontawesome-free/css/all.css';` `import '@fortawesome/fontawesome-free/js/all.js';`\n- Should it work also after `npm run build`? Because in my case it does not\n- Thankfully found this before my project was overwhelmed with weird packages or strange methods. +1 friend.","metadata":{"transformedAt":"2026-08-18T18:33:40.664Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":116,"estimatedTokens":701}}92{"id":"stack-58690066","source":"stackoverflow","questionId":58690066,"title":"Svelte 'evaluate script' time is appearing higher compare to inferno, preact","tags":["javascript","performance","svelte","svelte-3","infernojs"],"text":"Title: Svelte 'evaluate script' time is appearing higher compare to inferno, preact\nTags: javascript, performance, svelte, svelte-3, infernojs\nSource: Stack Overflow\n\nQuestion:\nI am trying to choose a library for my project which provide ***data binding and DOM management features***. Comparing multiple libraries I ended up with ***Inferno and Svelte***. \n\nI noticed evaluate script time of **Svelte** is higher than the other libraries *(Please refer attached image)* https://i.sstatic.net/OKOnL.jpg. \n\nIn the sample I have rendered a 100 x 15 table (total 1500 cell). though the rendering time reduces by few milliseconds but script execution time of inferno is half of it. https://i.sstatic.net/xmkNQ.png \n\nThe time increases drastically with number of elements, Eg. for 15000 cell svelte script evaluation time is 2000ms where as inferno took 680ms.\n\n**Svelte Code:**\n\n```\n\ntable,td,tr {\n border: 1px solid black;\n}\n\nimport { officedatabase } from '../../../data_generator/sampleGridData/initialloaddata.js';\n\n {#each officedatabase as row}\n \n {#each row as cell}\n {cell}\n {/each}\n \n {/each}\n\n```\n\n**Inferno sample Code:**\n\n```\nimport { Component } from 'inferno';\nimport { officedatabase } from './initialloaddata.js';\nexport default class Grid extends Component {\n state = {\n data: officedatabase\n };\n render () {\n let data = this.state.data,\n rows = data.map((row)=> {\n return (\n \n {row.map((ele)=>{\n return {ele};\n })}\n \n );\n });\n return (\n \n \n {rows}\n \n \n );\n }\n}\n```\n\nWhy this script evaluation time is high for Svelte?\n\n========================================\n\nCode:\n```text\n<style>\ntable,td,tr {\n border: 1px solid black;\n}\n</style>\n<script>\nimport { officedatabase } from '../../../data_generator/sampleGridData/initialloaddata.js';\n</script>\n<table>\n {#each officedatabase as row}\n <tr>\n {#each row as cell}\n <td>{cell}</td>\n {/each}\n </tr>\n {/each}\n</table>\n```\n\n```text\nimport { Component } from 'inferno';\nimport { officedatabase } from './initialloaddata.js';\nexport default class Grid extends Component {\n state = {\n data: officedatabase\n };\n render () {\n let data = this.state.data,\n rows = data.map((row)=> {\n return (\n <tr class='row'>\n {row.map((ele)=>{\n return <td style='border: 1px solid black;'>{ele}</td>;\n })}\n </tr>\n );\n });\n return (\n <div>\n <table style='border: 1px solid black;'>\n {rows}\n </table>\n </div>\n );\n }\n}\n```\n\n========================================\n\nComments:\n- I've also noticed this while populating little big data in tables.\n- I'd be curious if there are any hypotheses as to why this might be. One issue worth digging into further might be github.com/sveltejs/svelte/issues/3898 ?","metadata":{"transformedAt":"2026-08-18T18:33:40.664Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":123,"estimatedTokens":694}}93{"id":"stack-70999468","source":"stackoverflow","questionId":70999468,"title":"Asp.net 4.8 MVC + Vite + Svelte + HMR?","tags":["asp.net-mvc","svelte","vite"],"text":"Title: Asp.net 4.8 MVC + Vite + Svelte + HMR?\nTags: asp.net-mvc, svelte, vite\nSource: Stack Overflow\n\nQuestion:\nI have a legacy application built in ASP.NET 4.8 MVC.\nI would like to start building some client side features in Svelte - having svelte components rendering inside razor views. This I have working. I can render a svelte component anywhere in the razor page.\nHowever vite has some problem (im guessing with HMR?), and it keeps refreshing the razor page (https://localhost:44300/somefeature) every few seconds.\n\n**Environment**\n\nasp.net 4.8 mvc loads to https://localhost:44300/\n\nvite is loading on http://localhost:3000/\n\nHere is what i have so far. I ran npm init vite@latest -> selected svelte + svelte TS\n\n**vite.config.js**\n\n\r\n\r\n\n```\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n svelte({\n compilerOptions: {\n customElement: true,\n }\n })\n ],\n build:{\n // generate manifest.json in outDir\n manifest: true,\n rollupOptions: {\n // overwrite default .html entry\n input: '/src/main.ts'\n }\n }\n})\n```\n\n\r\n\r\n\r\n\nThen i followed the instructions here https://vitejs.dev/guide/backend-integration.html and added this to the razor page:\n\n```\n@Html.Raw(\"\")\n\n```\n\n(Note - had to use Html.Raw because it wouldnt let me escape the @ correctly - even with @@)\n\nAt this point it is rendering my Svelte component perfectly.\n\nThe issue however is that vite is now reloading my page every 2 seconds or so - im guessing because HMR is no longer working correctly as the console just says: [vite] connecting...\n\nCan anyone point me in a direction either to get HMR working whilst using another Backend server? For some reason it works in asp.net core, but not so in ASP.NET 4.8. Any observations to help?\n\nThanks in advance!\n\n========================================\n\nTop Answer:\nTHANK YOU!!!! This is exactly what I was looking for to include my react code in my old Asp.Net 4.8 site with hot module reload!\n\nFor other's the thing I had to include in my cshtml to make the react stuff load properly was:\n\n```\n\n import RefreshRuntime from \"http://localhost:9999/@@react-refresh\"\n RefreshRuntime.injectIntoGlobalHook(window)\n window.$RefreshReg$ = () => {}\n window.$RefreshSig$ = () => (type) => type\n window.__vite_plugin_react_preamble_installed__ = true\n \n```\n\nIf you don't include this you get an error saying '@vitejs/plugin-react can't detect preamble'.\n\nI am hosting the development site in IIS locally so to serve up the local files, I just created a /src folder off of the root or my application pointing to the src in my react directory and it worked beautifullly!!\n\n========================================\n\nCode:\n```html\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n svelte({\n compilerOptions: {\n customElement: true,\n }\n })\n ],\n build:{\n // generate manifest.json in outDir\n manifest: true,\n rollupOptions: {\n // overwrite default .html entry\n input: '/src/main.ts'\n }\n }\n})\n```\n\n```text\n@Html.Raw(\"<script type='module' src='http://localhost:3000/@vite/client'></script>\")\n<script type=\"module\" src=\"http://localhost:3000/src/main.ts\"></script>\n```\n\n```text\nexport default defineConfig({\n plugins: [\n svelte()\n ],\n build:{\n // generate manifest.json in outDir\n manifest: true,\n rollupOptions: {\n // overwrite default .html entry\n input: 'Scripts/svelte/app.js',\n },\n outDir: 'Scripts/svelte/dist'\n },\n server: {\n proxy:{\n '*' : {\n target: 'http://localhost:26688',\n changeOrigin: true\n }\n },\n hmr: {\n protocol: 'ws'\n }\n }\n})\n```\n\n```text\n<script type=\"module\">\n import RefreshRuntime from \"http://localhost:9999/@@react-refresh\"\n RefreshRuntime.injectIntoGlobalHook(window)\n window.$RefreshReg$ = () => {}\n window.$RefreshSig$ = () => (type) => type\n window.__vite_plugin_react_preamble_installed__ = true\n </script>\n```\n\n========================================\n\nComments:\n- It's working perfectly in the development, however, I could not resolve 'assets' folder for the production (if published as asp.net application)\n- What did you resolve svg issues in development environment?","metadata":{"transformedAt":"2026-08-18T18:33:40.664Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":163,"estimatedTokens":1096}}94{"id":"stack-64604624","source":"stackoverflow","questionId":64604624,"title":"Programatically get Svelte component instance","tags":["javascript","svelte"],"text":"Title: Programatically get Svelte component instance\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nIs it possible to get a component's instance outside components files?\n\nFor example, if I programmatically create a component using `const myComponent = new Component(options)`, I can access its instance and call methods such as `myComponent.$set(props)`.\n\nIs it possible to get an instance of some deeply nested component, outside any component scope?\n\nEither to get it by id (the dom class svelte-someid), or to get it internally inside a component (and use it to create a global registry of component instance references).\n\n========================================\n\nCode:\n```text\nconst myComponent = new Component(options)\n```\n\n```text\nmyComponent.$set(props)\n```\n\n```html\n<script>\n import { setContext, onMount } from 'svelte';\n \n import Parent from './Parent.svelte';\n \n const components = { };\n \n setContext('components', components);\n \n onMount(() => {\n components.child1.message = 'Child 1';\n components.child2.message = 'Child 2';\n })\n</script>\n\n<Parent></Parent>\n```\n\n```html\n<script>\n import { onMount, getContext } from 'svelte';\n import Child from './Child.svelte';\n \n let child1, child2;\n \n const components = getContext('components');\n \n onMount(() => {\n components.child1 = child1;\n components.child2 = child2;\n })\n</script>\n\n<Child bind:this={child1}></Child>\n<Child bind:this={child2}></Child>\n```\n\n```text\n<svelte:options accessors/>\n\n<script>\n export let message = '';\n</script>\n\n<p>Child: {message}</p>\n```\n\n========================================\n\nComments:\n- It seems like bind:this on another Svelte component, e.g. `` will bind its instance, but bind:this on the component container itself, e.g. `` will bind the dom node instead - which makes sense - but how to get component's own instanced within the component.\n- Looking at the compiled code, it doesn't seem like there is a way to get this from the outside. Also the css ids are just for css, so they are not unique and instances of the same component will have the same classes. Anyway, I think I will not need this, and there is probably a good reason it was not implemented.","metadata":{"transformedAt":"2026-08-18T18:33:40.664Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":77,"estimatedTokens":565}}95{"id":"stack-60857589","source":"stackoverflow","questionId":60857589,"title":"Parse markdown inside a svelte component","tags":["node.js","markdown","svelte"],"text":"Title: Parse markdown inside a svelte component\nTags: node.js, markdown, svelte\nSource: Stack Overflow\n\nQuestion:\nPlease excuse me if this is a naive question.\nI would like to parse markdown inside a Svelte component, something like\n\n```\n\n --- import some markdownLibrary ---\n export let text; // text is a markdown param\n\nmarkdownLibrary.render({text})\n```\n\nI can't use markdown-it or marked as `require` isn't available.\n\nI feel like I'm missing the bigger picture here. What is the 'svelte' way of doing this? Any pointer would help.\n\n========================================\n\nTop Answer:\nThe problem with the accepted answer is that it relies on `@html` which is not secure.\n\nThere is a svelte component that renders markdown without using `@html`\n\nhttps://www.npmjs.com/package/svelte-markdown\n\n```\nyarn add svelte-markdown\n```\n\n```\n\n import SvelteMarkdown from 'svelte-markdown'\n const source = `\n # This is a header\n\nThis is a paragraph.\n\n* This is a list\n* With two items\n 1. And a sublist\n 2. That is ordered\n * With another\n * Sublist inside\n\n| And this is | A table |\n|-------------|---------|\n| With two | columns |`\n\n```\n\n========================================\n\nCode:\n```text\n<script>\n --- import some markdownLibrary ---\n export let text; // text is a markdown param\n</script>\n\nmarkdownLibrary.render({text})\n```\n\n```text\nrequire\n```\n\n```text\n<script>\n import snarkdown from 'snarkdown'\n\n let md = `\n # Hello\n\n ## How are you?\n\n This text is _bold_\n `\n</script>\n\n<div>\n{@html snarkdown(md)}\n</div>\n```\n\n```text\n<script>\n let _marked = marked\n\n let md = `\n # Hello\n\n ## How are you?\n\n This text is _bold_\n `\n</script>\n\n<div>\n{@html _marked(md)}\n</div>\n```\n\n```text\nyarn add svelte-markdown\n```\n\n```text\n<script>\n import SvelteMarkdown from 'svelte-markdown'\n const source = `\n # This is a header\n\nThis is a paragraph.\n\n* This is a list\n* With two items\n 1. And a sublist\n 2. That is ordered\n * With another\n * Sublist inside\n\n| And this is | A table |\n|-------------|---------|\n| With two | columns |`\n</script>\n\n<SvelteMarkdown {source} />\n```\n\n```text\n@html\n```\n\n```text\n@html\n```\n\n```js\n<script lang=\"ts\">\n import { marked } from 'marked';\n\n export let markdownContent: string;\n</script>\n\n{@html marked(markdownContent)}\n```\n\n```text\n// eslintrc.js\n{\n ...,\n rules: {\n 'svelte/no-at-html-tags': 'warn'\n }\n}\n```\n\n```text\nmarked\n```\n\n```text\n@html\n```\n\n```text\nXSS\n```\n\n```text\n@html\n```\n\n========================================\n\nComments:\n- To anyone new here: if you want to use markdown documents *as* Svelte components or put Svelte components into markdown, I recommend taking a look at mdsvex!\n- using `@html` is risky as per the documentation - *Svelte does not sanitize expressions before injecting HTML. If the data comes from an untrusted source, you must sanitize it, or you are exposing your users to an XSS vulnerability*\n- You can use the DOMPurify package to further sanitize the html text content.\n- Agreed that it is not secure, but we use markdown for our own copy so it doesn't need to be. I would suggest in all cases that you sanitize the input before rendering it. I'm assuming that this library does that.\n- This solution is beyond sanitisation. From the markdown the library builds the tree, so the labels are constrained. It would be analogous to having a query with trusted input because it's internal vs a prepared statement. Variables go on a different channel so injection is not possible\n- If you want to use another library like marked or snarkdown, you can always run the results through a sanitizer like dompurify before rendering.\n- svelte-markdown *does* use `@html` when the Markdown content contains HTML github.com/pablo-abc/svelte-markdown/issues/42","metadata":{"transformedAt":"2026-08-18T18:33:40.664Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":187,"estimatedTokens":941}}96{"id":"stack-61888502","source":"stackoverflow","questionId":61888502,"title":"How can i navigate to different path on click in svelte?","tags":["onclick","navigation","svelte"],"text":"Title: How can i navigate to different path on click in svelte?\nTags: onclick, navigation, svelte\nSource: Stack Overflow\n\nQuestion:\nCurrently in having `on:click | preventDefault=\"{() => showDetail({id})}\"`\nand in `showDetail` function i want to naviagte to particular `id` which in i am passing on click of button.\n\nI tried regular javascript method`location.assign` but this is reloading the page and destroying the purpose of SPA.\nIs there any way to navigate in svelte without reloading\n\n========================================\n\nTop Answer:\nIf you use SvelteKit, it comes with that. You can use\n\n`goto('/my-other-route');`\n\nIt is documented here: https://svelte.dev/docs/kit/$app-navigation\n\nNot sure if you are using that...or Svelte without SvelteKit.\n\n========================================\n\nCode:\n```text\non:click | preventDefault=\"{() => showDetail({id})}\"\n```\n\n```text\nshowDetail\n```\n\n```text\nid\n```\n\n```text\nlocation.assign\n```\n\n```text\ngoto('/my-other-route');\n```\n\n```js\n<script>\n import { goto } from '$app/navigation';\n \n function navigateToAbout() {\n goto('/about');\n }\n</script>\n```\n\n```js\n<script>\n function navigate(path) {\n history.pushState({}, '', path);\n window.dispatchEvent(new PopStateEvent('popstate'));\n }\n</script>\n\n<button on:click={() => navigate('/contact')}>Contacts</button>\n```\n\n========================================\n\nComments:\n- Look here for a solution with SvelteKit: stackoverflow.com/questions/68187584/…\n- No, you don't. Path-based routing is built-in.\n- Routing does not come with svelte.dev/docs . Do you mean it is with SvelteKit ? kit.svelte.dev/docs","metadata":{"transformedAt":"2026-08-18T18:33:40.664Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":72,"estimatedTokens":406}}97{"id":"stack-62698421","source":"stackoverflow","questionId":62698421,"title":"Svelte: Adding a class to a div doesn't add the classes CSS to div","tags":["css","class","onclick","svelte","sapper"],"text":"Title: Svelte: Adding a class to a div doesn't add the classes CSS to div\nTags: css, class, onclick, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nWe are having a problem where on click is adding a class to a div but the classes CSS doesn't get add to the div. It just adds the class.\n\n```\n\n function handleClick() {\n document.getElementById('text').classList.add('blueText')\n }\n\n .blueText{\n color:blue;\n }\n\n Click me\n\n Text\n\n```\n\nCreated a REPL to see it as well. Any explanations or solutions appreciated\n\nhttps://svelte.dev/repl/85554a5f15134a5694c36fc4f4782029?version=3.23.2\n\n========================================\n\nCode:\n```text\n<script>\n function handleClick() {\n document.getElementById('text').classList.add('blueText')\n }\n</script>\n<style>\n .blueText{\n color:blue;\n }\n</style>\n<button on:click={handleClick}>\n Click me\n</button>\n<div id=\"text\">\n Text\n</div>\n```\n\n```text\n<script>\n let isBlue = false\n \n function handleClick() {\n isBlue = !isBlue\n }\n</script>\n\n<style>\n .blueText {\n color: blue;\n }\n</style>\n\n<button on:click={handleClick}>\n Click me\n</button>\n\n<div class:blueText={isBlue}>\n Text\n</div>\n```\n\n```text\n<script>\n let blueText = false\n \n function handleClick() {\n blueText = !blueText\n }\n</script>\n\n<style>\n .blueText {\n color: blue;\n }\n</style>\n\n<button on:click={handleClick}>\n Click me\n</button>\n\n<div class:blueText>\n Text\n</div>\n```\n\n```text\n<script>\n function handleClick() {\n document.getElementById('text').classList.add('blueText')\n }\n</script>\n<style>\n :global(.blueText) {\n color: blue;\n }\n</style>\n<button on:click={handleClick}>\n Click me\n</button>\n<div id=\"text\">\n Text\n</div>\n```\n\n```text\nblueText\n```\n\n```text\n:global\n```\n\n========================================\n\nComments:\n- You are referring to a class, but have given the only and \"id\". Try adding a class to the","metadata":{"transformedAt":"2026-08-18T18:33:40.664Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":128,"estimatedTokens":489}}98{"id":"stack-74166756","source":"stackoverflow","questionId":74166756,"title":"How can I render a component in its own component (recursively) in svelte?","tags":["recursion","svelte"],"text":"Title: How can I render a component in its own component (recursively) in svelte?\nTags: recursion, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make a recursive component that acts as a sort of tree view, where the component takes in an array.\n\n`App.svelte`\n\n```\n\n import Tree from \"./Tree.svelte\"\n let name = 'world';\n\n```\n\n`Tree.svelte`\n\n```\n\n export let arrayTree = []\n export let level = 0\n\n{#each arrayTree as branch}\n {#if Array.isArray(branch)}\n \n {:else}\n {'-'.repeat(level)}{branch}\n\n {/if}\n{/each}\n```\n\nMy goal is to re-render the component inside, but I can't re-call `` inside the component, or else it says: `Tree is not defined`. Is there any way that I can accomplish this?\n\nSvelte REPL\n\n========================================\n\nTop Answer:\n**For Svelte 5, please see the other answer**.\n\nFor Svelte 4, you can use ``:\n\n`App.svelte`\n\n```\n\n import Tree from \"./Tree.svelte\"\n let name = 'world';\n\n```\n\n`Tree.svelte`\n\n```\n\n export let arrayTree = []\n export let level = 0\n\n{#each arrayTree as branch}\n {#if Array.isArray(branch)}\n \n {:else}\n {'-'.repeat(level)}{branch}\n\n {/if}\n{/each}\n```\n\nSvelte REPL\n\n========================================\n\nCode:\n```html\n<script>\n import Tree from \"./Tree.svelte\"\n let name = 'world';\n</script>\n\n<Tree arrayTree={[1, 2, [3, 4], 5, 6, 7, [8, [9, 10]], 11, 12]}/>\n```\n\n```html\n<script>\n export let arrayTree = []\n export let level = 0\n</script>\n\n{#each arrayTree as branch}\n {#if Array.isArray(branch)}\n <!-- How do I do this? -->\n {:else}\n <p>{'-'.repeat(level)}{branch}</p>\n {/if}\n{/each}\n```\n\n```text\nApp.svelte\n```\n\n```text\nTree.svelte\n```\n\n```text\n<Tree>\n```\n\n```text\nTree is not defined\n```\n\n```html\n<script>\n import Tree from \"./Tree.svelte\"\n export let arrayTree = []\n export let level = 0\n</script>\n\n{#each arrayTree as branch}\n {#if Array.isArray(branch)}\n <Tree arrayTree={branch} level={level + 1}/>\n {:else}\n <p>{'-'.repeat(level)}{branch}</p>\n {/if}\n{/each}\n```\n\n```html\n<script>\n import Tree from \"./Tree.svelte\"\n let name = 'world';\n</script>\n\n<Tree arrayTree={[1, 2, [3, 4], 5, 6, 7, [8, [9, 10]], 11, 12]}/>\n```\n\n```html\n<script>\n export let arrayTree = []\n export let level = 0\n</script>\n\n{#each arrayTree as branch}\n {#if Array.isArray(branch)}\n <svelte:self arrayTree={branch} level={level + 1}/>\n {:else}\n <p>{'-'.repeat(level)}{branch}</p>\n {/if}\n{/each}\n```\n\n```text\n<svelte:self>\n```\n\n```text\nApp.svelte\n```\n\n```text\nTree.svelte\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.664Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":166,"estimatedTokens":630}}99{"id":"stack-56552343","source":"stackoverflow","questionId":56552343,"title":"How can I fix \"sessionStorage is not defined\" in Svelte?","tags":["svelte","sapper"],"text":"Title: How can I fix \"sessionStorage is not defined\" in Svelte?\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI'm new in Svelte and I'm trying to set some info into sessionStorage but it is throwing \"sessionStorage is not defined\".\nI realised that I received this error because it's running on the server side.\n\nI created a component at */src/components/nav.svelte* that uses */src/domain/auth/service.js* and the error occurs in the last one.\n\nSearching on the web I found that in this case I must use **sessionStorage** inside **onMount** function. Is that the right way?\n\nHow can I avoid that my code get a little mess?\n\n========================================\n\nTop Answer:\nhey you need to use onMount \n\n```\nimport { onMount } from 'svelte';\n\nonMount(() => {\n sessionStorage.setItem('myWork', 'Developer');\n});\n```\n\n========================================\n\nCode:\n```text\nif (window && window.sessionStorage) {\n // do your stuff with sessionStorage\n}\n```\n\n```text\nif (typeof window !== 'undefined') {\n // do your stuff with sessionStorage\n}\n```\n\n```text\nimport { onMount } from 'svelte';\n\nonMount(() => {\n sessionStorage.setItem('myWork', 'Developer');\n});\n```\n\n```js\nimport { browser } from '$app/environment';\n```\n\n```js\nif (browser) {\n // do your stuff with sessionStorage...\n}\n```\n\n========================================\n\nComments:\n- what data you are trying to store? are you going to use the data in both server side and client side?\n- You indeed found the correct answer. You would use sessionStorage inside the onMount function as this will only run when your attaching the component on the client. The cost inside onMount will specifically NOT run on the server so that you are able to lazily load data on the client side.\n- I put code which contains sessionStorage into functions and it stopped complains. But now it shows me the following warning: \"Using browser-only version of superagent in non-browser environment\" Do I need to worry about it? Thank you!\n- For me, the latter works but the former doesn't (SvelteKit): `ReferenceError: window is not defined`\n- Note to self: Don't call `sessionStorage.setItem()` in a reactive statement (`$:`) since it will reset the stored value to the initial state on every refresh.\n- Or, you may need `afterUpdate` instead of `onMount`, to trigger some action on dom update. For me, after `await goto(`/`);`, need to use `afterUpdate` to read `sessionStorage` to make sure it works, when use `onMount` I need a refresh by hand sometimes.\n- Nice, thanks for the addition, didn't know about that one! Did that exist at the time I wrote the answer?\n- I don't think it was. 😁\n- @exside I think it was introduced recently, in the last 2 years maybe. it is the one I use more often since it makes sense semantically speaking.","metadata":{"transformedAt":"2026-08-18T18:33:40.664Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":72,"estimatedTokens":700}}100{"id":"stack-63299785","source":"stackoverflow","questionId":63299785,"title":"How to setup global bootstrap via scss in Svelte?","tags":["bootstrap-4","svelte","svelte-3"],"text":"Title: How to setup global bootstrap via scss in Svelte?\nTags: bootstrap-4, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI want to use Bootstrap (v4.5) in a Svelte (v3) project with custom theme.\n\nThe bootstrap documentation states that you can do this with scss. So I've setup Svelte with `svelte-preprocess` as follows:\n\nAdded to my `package.json`:\n\n```\n\"bootstrap\": \"^4.5.2\",\n \"node-sass\": \"^4.14.1\",\n \"svelte-preprocess\": \"^4.0.10\",\n```\n\nIn my `rollup.config.js`:\n\n```\n...\nimport preprocess from \"svelte-preprocess\";\n\nexport default {\n ...,\n plugins: [\n ...,\n svelte({\n // enable run-time checks when not in production\n dev: !production,\n // we'll extract any component CSS out into\n // a separate file - better for performance\n css: (css) => {\n css.write(\"public/build/bundle.css\");\n },\n preprocess: preprocess(),\n }),\n```\n\nIn my `App` component:\n\n```\n\n // Variable overrides for bootstrap\n $primary: #19197c;\n $secondary: #fd6400;\n $light: #d8d8d8;\n\n @import \"../node_modules/bootstrap/scss/bootstrap\";\n\n```\n\nUnfortunately, it looks like Svelte purges all the styles since I don't get bootstrap styling in my application. I would like to use bootstrap normalization as well as bootstrap classes. Any tips? Thanks!\n\n========================================\n\nTop Answer:\nI actually found a much easier way, using Svelte Preprocess! All you need to do, in App.svelte\n\n```\n\n...\n\n @import \"path/to/your/scss/files\";\n\n```\n\nJust note that if you use `\"./...\"` in the `@import`, that means it's referencing local files. If there is no `\"./...\"` (so just plain `\"name\"`, then it will import from `node_modules`.\n\nAnd that's it! If you wanted to use the settings, all you would need to do is\n\n========================================\n\nCode:\n```text\n\"bootstrap\": \"^4.5.2\",\n \"node-sass\": \"^4.14.1\",\n \"svelte-preprocess\": \"^4.0.10\",\n```\n\n```text\n...\nimport preprocess from \"svelte-preprocess\";\n\nexport default {\n ...,\n plugins: [\n ...,\n svelte({\n // enable run-time checks when not in production\n dev: !production,\n // we'll extract any component CSS out into\n // a separate file - better for performance\n css: (css) => {\n css.write(\"public/build/bundle.css\");\n },\n preprocess: preprocess(),\n }),\n```\n\n```text\n<style type=\"text/scss\" global>\n // Variable overrides for bootstrap\n $primary: #19197c;\n $secondary: #fd6400;\n $light: #d8d8d8;\n\n @import \"../node_modules/bootstrap/scss/bootstrap\";\n\n</style>\n```\n\n```text\nsvelte-preprocess\n```\n\n```text\npackage.json\n```\n\n```text\nrollup.config.js\n```\n\n```text\nApp\n```\n\n```js\n...\nimport scss from \"rollup-plugin-scss\";\n\nexport default {\n ...,\n plugins: [\n ...,\n svelte({\n // enable run-time checks when not in production\n dev: !production,\n emitCss: true\n }),\n scss(),\n ...,\n```\n\n```css\n// Variable overrides for bootstrap\n$primary: #19197c;\n$secondary: #fd6400;\n$light: #d8d8d8;\n\n@import \"../node_modules/bootstrap/scss/bootstrap\";\n```\n\n```js\nimport \"./main.scss\";\nimport App from \"./App.svelte\";\n\nconst app = new App({\n target: document.body,\n props: {},\n});\n\nexport default app;\n```\n\n```text\nrollup-plugin-scss\n```\n\n```text\nrollup.config.js\n```\n\n```text\nmain.scss\n```\n\n```text\nmain.js\n```\n\n```text\n<!-- app.svelte content -->\n...\n<!-- ... -->\n\n<style lang=\"scss\" global>\n @import \"path/to/your/scss/files\";\n</style>\n```\n\n```text\n\"./...\"\n```\n\n```text\n@import\n```\n\n```text\n\"./...\"\n```\n\n```text\n\"name\"\n```\n\n```text\nnode_modules\n```\n\n```html\n<svelte:head>\n <!-- Google Font -->\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n <link href=\"https://fonts.googleapis.com/css2?family=Roboto&display=swap\" rel=\"stylesheet\">\n\n <style>\n /* Global CSS via SASS */\n @import '../../_assets/sass/global';\n\n ._another_global_stuff {\n z_index: 1001;\n }\n </style>\n</svelte:head>\n```\n\n```js\nlet plugins = [\n //...\n svelte({\n compilerOptions: {\n dev: !production\n },\n preprocess: sveltePreprocess({\n sourceMap: !production,\n defaults: {\n style: 'scss'\n },\n postcss: {\n plugins: [\n require('autoprefixer')()\n ]\n }\n }),\n emitCss: true\n }),\n css({output: 'bundle.css'}),\n //...\n]\n```\n\n```text\n<svelte:head>\n```\n\n========================================\n\nComments:\n- thank you . but if i import my own custom scss file , style will not update when i change it . i need to comment @import , save file , uncomment it , save , then it updates .\n- @BabakKarimiAsl Update the scss plugin like this `scss({watch: 'src'})` to watch the scss file in src folder for changes.\n- @BabakKarimiAsl also to keep you build bundle clean do not import the scss file in `main.js` but add output path like this `scss({watch: 'src',output: 'public/global.css'})` and directly link the output file `global.css` in index.html","metadata":{"transformedAt":"2026-08-18T18:33:40.664Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":264,"estimatedTokens":1213}}101{"id":"stack-61826138","source":"stackoverflow","questionId":61826138,"title":"How to animate an element on an inner change with Svelte?","tags":["svelte"],"text":"Title: How to animate an element on an inner change with Svelte?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nTransitions in Svelte only apply to elements entering or exiting the DOM.\n\nFor example this would apply the fade when the `div` is initially added to the DOM:\n\n```\n{message}\n```\n\nHow can we add a transition instead when `message` changes?\n\nSince Svelte cannot have keys on single elements, the only solution I've found is to use a single element array to trigger a new element in the DOM whenever the array changes which doesn't seem ideal:\n\n```\n\nlet messages = ['hello world'];\n\nfunction updateMessages (message) {\n messages = [message];\n}\n\n{#each messages as message (message)}\n {message}\n{/each}\n```\n\n========================================\n\nTop Answer:\nYour `#each` hack is indeed the recommended approach, currently (we may add something like a `key` directive in future, but no promises) — I'd just make one alteration, which is to do `#each [x] as x` rather than maintaining an array separately:\n\n```\n\nlet message = 'hello world';\n\nfunction updateMessages (new_message) {\n message = new_message;\n}\n\n{#each [message] as message (message)}\n {message}\n{/each}\n```\n\n========================================\n\nCode:\n```text\n<div in:fade>{message}</div>\n```\n\n```text\n<script>\nlet messages = ['hello world'];\n\nfunction updateMessages (message) {\n messages = [message];\n}\n</script>\n\n{#each messages as message (message)}\n <div in:fade>{message}</div>\n{/each}\n```\n\n```text\ndiv\n```\n\n```text\nmessage\n```\n\n```text\n{#key value}\n <div transition:fade>{value}</div>\n{/key}\n```\n\n```html\n<script>\nlet message = 'hello world';\n\nfunction updateMessages (new_message) {\n message = new_message;\n}\n</script>\n\n{#each [message] as message (message)}\n <div in:fade>{message}</div>\n{/each}\n```\n\n```text\n#each\n```\n\n```text\nkey\n```\n\n```text\n#each [x] as x\n```\n\n========================================\n\nComments:\n- Thanks for the array idea Rich, I didn't expect that work! Hopefully a `key` lands on Svelte someday.\n- Please add an example and I will mark your answer as valid!\n- When I try this, it keeps two divs around while the transition is happening, one fades in and one fades out. After the transition is complete, it goes back to one div. Solved this by changing transition:fade to in:fade\n- Here is an example: svelte.dev/repl/bc15ae91a2ba40c4a8d4f4ce026c8387?version=3.4‌​8.0\n- @killdash9 Apologies for the necro, but the duplication seems to be happening because svelte just superimposes the two values while transitioning from one to the other. As can be seen in the example, positioning the element `absolute`-ly solves the issue. 🤷♂️","metadata":{"transformedAt":"2026-08-18T18:33:40.664Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":117,"estimatedTokens":667}}102{"id":"stack-62279184","source":"stackoverflow","questionId":62279184,"title":"How do I get the dom node of a component in Svelte?","tags":["svelte","svelte-3"],"text":"Title: How do I get the dom node of a component in Svelte?\nTags: svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nSay I render the following Dialog:\n\n```\nlet dialog;\n\n```\n\nI want to position this dialog (using `afterUpdate` lifecycle function I guess). However, `dialog` is not a dom element. When I log it, it will look something like:\n\n```\nMyDialog {$$: {…}, left: 785, $set: ƒ, $capture_state: ƒ, $inject_state: ƒ}\n$$: {fragment: {…}, ctx: Array(1), props: {…}, update: ƒ, not_equal: ƒ, …}\n$capture_state: () => {…}\n$inject_state: $$props => {…}\n$set: $$props => {…}\nsomeExportedProp: (...)\n__proto__: SvelteComponentDev\n```\n\nHow can I access its dom in order to position it?\n\n========================================\n\nCode:\n```text\nlet dialog;\n\n<MyDialog bind:this={dialog}/>\n```\n\n```text\nMyDialog {$$: {…}, left: 785, $set: ƒ, $capture_state: ƒ, $inject_state: ƒ}\n$$: {fragment: {…}, ctx: Array(1), props: {…}, update: ƒ, not_equal: ƒ, …}\n$capture_state: () => {…}\n$inject_state: $$props => {…}\n$set: $$props => {…}\nsomeExportedProp: (...)\n__proto__: SvelteComponentDev\n```\n\n```text\nafterUpdate\n```\n\n```text\ndialog\n```\n\n```html\n<div bind:this={el} />\n```\n\n```html\n<script>\n export let el\n</script>\n\n<div class=\"dialog\" bind:this={el}>\n <slot />\n</div>\n```\n\n```html\n<script>\n import MyDialog from './MyDialog.svelte'\n\n let dialog\n\n $: console.log(dialog) // here, DOM element!\n</script>\n\n<MyDialog bind:el={dialog}>\n Hello!\n</MyDialog>\n```\n\n```html\n<script>\n export let top\n export let left\n\n $: style = `top: ${top}px; left: ${left}px`\n</script>\n\n<div class=\"dialog\" {style}>\n <slot />\n</div>\n```\n\n```html\n<script>\n export let top\n export let left\n\n let el\n\n // reactive block will rerun each time el, top, or left changes\n $: if (el) {\n el.style.top = top + 'px'\n el.style.left = left + 'px'\n }\n</script>\n\n<div class=\"dialog\" bind:this={el}>\n <slot />\n</div>\n```\n\n```text\nMyDialog\n```\n\n```text\nbind:this\n```\n\n```text\nMyDialog\n```\n\n```text\nMyDialog\n```\n\n```text\nMyDialog.svelte\n```\n\n```text\nApp.svelte\n```\n\n========================================\n\nComments:\n- Thank you. Could you give me an example of a better solution? Maybe export a function then instead of the dom node?\n- Depends on what you really want to do when you say \"position\", but I think what I would do would probably be to have something like a `position` prop on the `MyDialog` component, and apply the effect to the DOM element from there, from the inside. This way, if the DOM / CSS of your dialog component evolves, you only have a single centralized place that you need to adapt.\n- How do I move the dialog (e.g. with dom top/left style attributes) by changing a props that would be exported? I see with an exported function, where I can give it some coordinates and I execute Dom operations to position the dialog; but I don't see how with your idea of exporting just one prop. How do you execute the Dom operations when that prop changes?\n- One prop can be an object, an array... It was just an example, the point was that it's often desirable to abstract the inside of a component behind a limited API, instead of exposing whole bits of it, and then you're stuck when you want to change those bits... I've added some examples of how I would move an element with props.\n- Man I just wanted to take a few seconds of your time if you had any, but you write me a whole edit. You're an awesome human:) thank you!\n- This is the best solution","metadata":{"transformedAt":"2026-08-18T18:33:40.665Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":146,"estimatedTokens":861}}103{"id":"stack-73178856","source":"stackoverflow","questionId":73178856,"title":"SvelteKit: Packages not being able to access node functions","tags":["javascript","node.js","svelte","sveltekit","cloudflare-pages"],"text":"Title: SvelteKit: Packages not being able to access node functions\nTags: javascript, node.js, svelte, sveltekit, cloudflare-pages\nSource: Stack Overflow\n\nQuestion:\nI am building an app with SvelteKit and publishing it to Cloudflare Pages, but it is some packages I am using are not able to access node native functions. Here's the build log:\n\n```\n2022-07-30T19:05:14.200499Z > Using @sveltejs/adapter-cloudflare\n2022-07-30T19:05:14.227308Z ✘ [ERROR] Could not resolve \"url\"\n2022-07-30T19:05:14.227701Z \n2022-07-30T19:05:14.227859Z node_modules/sequelize/lib/sequelize.js:21:20:\n2022-07-30T19:05:14.228009Z 21 │ const url = require(\"url\");\n2022-07-30T19:05:14.22817Z ╵ ~~~~~\n2022-07-30T19:05:14.228388Z \n2022-07-30T19:05:14.228525Z The package \"url\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.228694Z \n2022-07-30T19:05:14.22885Z ✘ [ERROR] Could not resolve \"path\"\n2022-07-30T19:05:14.229004Z \n2022-07-30T19:05:14.229168Z node_modules/sequelize/lib/sequelize.js:22:21:\n2022-07-30T19:05:14.22932Z 22 │ const path = require(\"path\");\n2022-07-30T19:05:14.229452Z ╵ ~~~~~~\n2022-07-30T19:05:14.229593Z \n2022-07-30T19:05:14.229733Z The package \"path\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.229891Z \n2022-07-30T19:05:14.241501Z ✘ [ERROR] Could not resolve \"@firebase/database-compat/standalone\"\n2022-07-30T19:05:14.2417Z \n2022-07-30T19:05:14.241833Z node_modules/firebase-admin/lib/app/firebase-namespace.js:106:41:\n2022-07-30T19:05:14.242066Z 106 │ ...ject.assign(fn, require('@firebase/database-compat/standalone'));\n2022-07-30T19:05:14.242206Z ╵ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n2022-07-30T19:05:14.242323Z \n2022-07-30T19:05:14.242435Z The path \"./standalone\" is not currently exported by package \"@firebase/database-compat\":\n2022-07-30T19:05:14.242596Z \n2022-07-30T19:05:14.243619Z node_modules/@firebase/database-compat/package.json:16:13:\n2022-07-30T19:05:14.244219Z 16 │ \"exports\": {\n2022-07-30T19:05:14.244437Z ╵ ^\n2022-07-30T19:05:14.244574Z \n2022-07-30T19:05:14.244698Z None of the conditions provided (\"types\", \"node\") match any of the currently active conditions (\"browser\", \"default\", \"require\"):\n2022-07-30T19:05:14.24483Z \n2022-07-30T19:05:14.244956Z node_modules/@firebase/database-compat/package.json:27:20:\n2022-07-30T19:05:14.24507Z 27 │ \"./standalone\": {\n2022-07-30T19:05:14.245196Z ╵ ^\n2022-07-30T19:05:14.245368Z \n2022-07-30T19:05:14.2455Z Consider enabling the \"types\" condition if this package expects it to be enabled. You can use \"conditions: ['types']\" to do that:\n2022-07-30T19:05:14.245626Z \n2022-07-30T19:05:14.245736Z node_modules/@firebase/database-compat/package.json:28:6:\n2022-07-30T19:05:14.245847Z 28 │ \"types\": \"./dist/database-compat/src/index.standalone.d.ts\",\n2022-07-30T19:05:14.245969Z ╵ ~~~~~~~\n2022-07-30T19:05:14.24608Z \n2022-07-30T19:05:14.246397Z You can mark the path \"@firebase/database-compat/standalone\" as external to exclude it from the bundle, which will remove this error. You can also surround this \"require\" call with a try/catch block to handle this failure at run-time instead of bundle-time.\n2022-07-30T19:05:14.246547Z \n2022-07-30T19:05:14.282052Z ✘ [ERROR] Could not resolve \"util\"\n2022-07-30T19:05:14.282324Z \n2022-07-30T19:05:14.282497Z node_modules/retry-as-promised/index.js:3:19:\n2022-07-30T19:05:14.282669Z 3 │ var util = require('util');\n2022-07-30T19:05:14.282834Z ╵ ~~~~~~\n2022-07-30T19:05:14.282992Z \n2022-07-30T19:05:14.28312Z The package \"util\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.283505Z \n2022-07-30T19:05:14.317451Z ✘ [ERROR] Could not resolve \"url\"\n2022-07-30T19:05:14.317714Z \n2022-07-30T19:05:14.317856Z node_modules/pg-connection-string/index.js:3:18:\n2022-07-30T19:05:14.317986Z 3 │ var url = require('url')\n2022-07-30T19:05:14.318109Z ╵ ~~~~~\n2022-07-30T19:05:14.318238Z \n2022-07-30T19:05:14.318505Z The package \"url\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.318665Z \n2022-07-30T19:05:14.319392Z ✘ [ERROR] Could not resolve \"util\"\n2022-07-30T19:05:14.319808Z \n2022-07-30T19:05:14.319968Z node_modules/sequelize/lib/utils/deprecations.js:32:37:\n2022-07-30T19:05:14.320241Z 32 │ var import_util = __toModule(require(\"util\"));\n2022-07-30T19:05:14.320559Z ╵ ~~~~~~\n2022-07-30T19:05:14.320699Z \n2022-07-30T19:05:14.320823Z The package \"util\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.321042Z \n2022-07-30T19:05:14.326057Z ✘ [ERROR] Could not resolve \"fs\"\n2022-07-30T19:05:14.327248Z \n2022-07-30T19:05:14.328892Z node_modules/sequelize/lib/dialects/sqlite/connection-manager.js:2:19:\n2022-07-30T19:05:14.329459Z 2 │ const fs = require(\"fs\");\n2022-07-30T19:05:14.329823Z ╵ ~~~~\n2022-07-30T19:05:14.33005Z \n2022-07-30T19:05:14.330876Z The package \"fs\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.331054Z \n2022-07-30T19:05:14.331281Z ✘ [ERROR] Could not resolve \"assert\"\n2022-07-30T19:05:14.331476Z \n2022-07-30T19:05:14.331604Z node_modules/sequelize/lib/model.js:21:23:\n2022-07-30T19:05:14.33172Z 21 │ const assert = require(\"assert\");\n2022-07-30T19:05:14.331829Z ╵ ~~~~~~~~\n2022-07-30T19:05:14.331936Z \n2022-07-30T19:05:14.33237Z The package \"assert\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.332543Z \n2022-07-30T19:05:14.332673Z ✘ [ERROR] Could not resolve \"util\"\n2022-07-30T19:05:14.332789Z \n2022-07-30T19:05:14.333338Z node_modules/sequelize/lib/data-types.js:2:21:\n2022-07-30T19:05:14.334026Z 2 │ const util = require(\"util\");\n2022-07-30T19:05:14.334206Z ╵ ~~~~~~\n2022-07-30T19:05:14.33441Z \n2022-07-30T19:05:14.334627Z The package \"util\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.334959Z \n2022-07-30T19:05:14.335106Z ✘ [ERROR] Could not resolve \"fs\"\n2022-07-30T19:05:14.335239Z \n2022-07-30T19:05:14.33556Z node_modules/pg-connection-string/index.js:4:17:\n2022-07-30T19:05:14.335971Z 4 │ var fs = require('fs')\n2022-07-30T19:05:14.336165Z ╵ ~~~~\n2022-07-30T19:05:14.336703Z \n2022-07-30T19:05:14.337207Z The package \"fs\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.337373Z \n2022-07-30T19:05:14.337521Z ✘ [ERROR] Could not resolve \"fs\"\n2022-07-30T19:05:14.337657Z \n2022-07-30T19:05:14.337784Z node_modules/firebase-admin/lib/app/lifecycle.js:21:19:\n2022-07-30T19:05:14.337911Z 21 │ const fs = require(\"fs\");\n2022-07-30T19:05:14.338056Z ╵ ~~~~\n2022-07-30T19:05:14.338211Z \n2022-07-30T19:05:14.338342Z The package \"fs\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.338478Z \n2022-07-30T19:05:14.33862Z ✘ [ERROR] Could not resolve \"util\"\n2022-07-30T19:05:14.338756Z \n2022-07-30T19:05:14.339295Z node_modules/sequelize/lib/utils/logger.js:59:37:\n2022-07-30T19:05:14.339765Z 59 │ var import_util = __toModule(require(\"util\"));\n2022-07-30T19:05:14.339936Z ╵ ~~~~~~\n2022-07-30T19:05:14.340093Z \n2022-07-30T19:05:14.340237Z The package \"util\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n\n...............\n\n2022-07-30T19:05:14.89587Z \n2022-07-30T19:05:14.896004Z error during build:\n2022-07-30T19:05:14.896124Z Error: Build failed with 234 errors:\n2022-07-30T19:05:14.896252Z node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js:1:31: ERROR: Could not resolve \"stream\"\n2022-07-30T19:05:14.896371Z node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js:2:25: ERROR: Could not resolve \"util\"\n2022-07-30T19:05:14.896477Z node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js:1:29: ERROR: Could not resolve \"events\"\n2022-07-30T19:05:14.896588Z node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js:2:25: ERROR: Could not resolve \"util\"\n2022-07-30T19:05:14.896701Z node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js:1:25: ERROR: Could not resolve \"util\"\n2022-07-30T19:05:14.896818Z ...\n2022-07-30T19:05:14.896942Z at failureErrorWithLog (/opt/buildhome/repo/node_modules/esbuild/lib/main.js:1621:15)\n2022-07-30T19:05:14.897064Z at /opt/buildhome/repo/node_modules/esbuild/lib/main.js:1263:28\n2022-07-30T19:05:14.897441Z at runOnEndCallbacks (/opt/buildhome/repo/node_modules/esbuild/lib/main.js:1176:65)\n2022-07-30T19:05:14.897756Z at buildResponseToResult (/opt/buildhome/repo/node_modules/esbuild/lib/main.js:1261:7)\n2022-07-30T19:05:14.898025Z at /opt/buildhome/repo/node_modules/esbuild/lib/main.js:1374:14\n2022-07-30T19:05:14.898328Z at /opt/buildhome/repo/node_modules/esbuild/lib/main.js:675:9\n2022-07-30T19:05:14.898627Z at handleIncomingPacket (/opt/buildhome/repo/node_modules/esbuild/lib/main.js:772:9)\n2022-07-30T19:05:14.898889Z at Socket.readFromStdout (/opt/buildhome/repo/node_modules/esbuild/lib/main.js:641:7)\n2022-07-30T19:05:14.90122Z at Socket.emit (node:events:527:28)\n2022-07-30T19:05:14.901427Z at addChunk (node:internal/streams/readable:315:12)\n2022-07-30T19:05:14.917314Z Failed: build command exited with code: 1\n2022-07-30T19:05:16.243508Z Failed: an internal error occurred\n```\n\nThis is happening just after I added some server side code so that might be the reason, but Sveltekit supports that through cloudflare workers so I don't understand why.\n\n========================================\n\nTop Answer:\nIn my case since it was a supported package, all I had to do was updating `wrangler.toml` from\n\ncompatibility_date=\"2023-05-18\"\n\nto\n\ncompatibility_date=\"2024-09-23\"\n\n========================================\n\nCode:\n```text\n2022-07-30T19:05:14.200499Z > Using @sveltejs/adapter-cloudflare\n2022-07-30T19:05:14.227308Z ✘ [ERROR] Could not resolve \"url\"\n2022-07-30T19:05:14.227701Z \n2022-07-30T19:05:14.227859Z node_modules/sequelize/lib/sequelize.js:21:20:\n2022-07-30T19:05:14.228009Z 21 │ const url = require(\"url\");\n2022-07-30T19:05:14.22817Z ╵ ~~~~~\n2022-07-30T19:05:14.228388Z \n2022-07-30T19:05:14.228525Z The package \"url\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.228694Z \n2022-07-30T19:05:14.22885Z ✘ [ERROR] Could not resolve \"path\"\n2022-07-30T19:05:14.229004Z \n2022-07-30T19:05:14.229168Z node_modules/sequelize/lib/sequelize.js:22:21:\n2022-07-30T19:05:14.22932Z 22 │ const path = require(\"path\");\n2022-07-30T19:05:14.229452Z ╵ ~~~~~~\n2022-07-30T19:05:14.229593Z \n2022-07-30T19:05:14.229733Z The package \"path\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.229891Z \n2022-07-30T19:05:14.241501Z ✘ [ERROR] Could not resolve \"@firebase/database-compat/standalone\"\n2022-07-30T19:05:14.2417Z \n2022-07-30T19:05:14.241833Z node_modules/firebase-admin/lib/app/firebase-namespace.js:106:41:\n2022-07-30T19:05:14.242066Z 106 │ ...ject.assign(fn, require('@firebase/database-compat/standalone'));\n2022-07-30T19:05:14.242206Z ╵ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n2022-07-30T19:05:14.242323Z \n2022-07-30T19:05:14.242435Z The path \"./standalone\" is not currently exported by package \"@firebase/database-compat\":\n2022-07-30T19:05:14.242596Z \n2022-07-30T19:05:14.243619Z node_modules/@firebase/database-compat/package.json:16:13:\n2022-07-30T19:05:14.244219Z 16 │ \"exports\": {\n2022-07-30T19:05:14.244437Z ╵ ^\n2022-07-30T19:05:14.244574Z \n2022-07-30T19:05:14.244698Z None of the conditions provided (\"types\", \"node\") match any of the currently active conditions (\"browser\", \"default\", \"require\"):\n2022-07-30T19:05:14.24483Z \n2022-07-30T19:05:14.244956Z node_modules/@firebase/database-compat/package.json:27:20:\n2022-07-30T19:05:14.24507Z 27 │ \"./standalone\": {\n2022-07-30T19:05:14.245196Z ╵ ^\n2022-07-30T19:05:14.245368Z \n2022-07-30T19:05:14.2455Z Consider enabling the \"types\" condition if this package expects it to be enabled. You can use \"conditions: ['types']\" to do that:\n2022-07-30T19:05:14.245626Z \n2022-07-30T19:05:14.245736Z node_modules/@firebase/database-compat/package.json:28:6:\n2022-07-30T19:05:14.245847Z 28 │ \"types\": \"./dist/database-compat/src/index.standalone.d.ts\",\n2022-07-30T19:05:14.245969Z ╵ ~~~~~~~\n2022-07-30T19:05:14.24608Z \n2022-07-30T19:05:14.246397Z You can mark the path \"@firebase/database-compat/standalone\" as external to exclude it from the bundle, which will remove this error. You can also surround this \"require\" call with a try/catch block to handle this failure at run-time instead of bundle-time.\n2022-07-30T19:05:14.246547Z \n2022-07-30T19:05:14.282052Z ✘ [ERROR] Could not resolve \"util\"\n2022-07-30T19:05:14.282324Z \n2022-07-30T19:05:14.282497Z node_modules/retry-as-promised/index.js:3:19:\n2022-07-30T19:05:14.282669Z 3 │ var util = require('util');\n2022-07-30T19:05:14.282834Z ╵ ~~~~~~\n2022-07-30T19:05:14.282992Z \n2022-07-30T19:05:14.28312Z The package \"util\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.283505Z \n2022-07-30T19:05:14.317451Z ✘ [ERROR] Could not resolve \"url\"\n2022-07-30T19:05:14.317714Z \n2022-07-30T19:05:14.317856Z node_modules/pg-connection-string/index.js:3:18:\n2022-07-30T19:05:14.317986Z 3 │ var url = require('url')\n2022-07-30T19:05:14.318109Z ╵ ~~~~~\n2022-07-30T19:05:14.318238Z \n2022-07-30T19:05:14.318505Z The package \"url\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.318665Z \n2022-07-30T19:05:14.319392Z ✘ [ERROR] Could not resolve \"util\"\n2022-07-30T19:05:14.319808Z \n2022-07-30T19:05:14.319968Z node_modules/sequelize/lib/utils/deprecations.js:32:37:\n2022-07-30T19:05:14.320241Z 32 │ var import_util = __toModule(require(\"util\"));\n2022-07-30T19:05:14.320559Z ╵ ~~~~~~\n2022-07-30T19:05:14.320699Z \n2022-07-30T19:05:14.320823Z The package \"util\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.321042Z \n2022-07-30T19:05:14.326057Z ✘ [ERROR] Could not resolve \"fs\"\n2022-07-30T19:05:14.327248Z \n2022-07-30T19:05:14.328892Z node_modules/sequelize/lib/dialects/sqlite/connection-manager.js:2:19:\n2022-07-30T19:05:14.329459Z 2 │ const fs = require(\"fs\");\n2022-07-30T19:05:14.329823Z ╵ ~~~~\n2022-07-30T19:05:14.33005Z \n2022-07-30T19:05:14.330876Z The package \"fs\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.331054Z \n2022-07-30T19:05:14.331281Z ✘ [ERROR] Could not resolve \"assert\"\n2022-07-30T19:05:14.331476Z \n2022-07-30T19:05:14.331604Z node_modules/sequelize/lib/model.js:21:23:\n2022-07-30T19:05:14.33172Z 21 │ const assert = require(\"assert\");\n2022-07-30T19:05:14.331829Z ╵ ~~~~~~~~\n2022-07-30T19:05:14.331936Z \n2022-07-30T19:05:14.33237Z The package \"assert\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.332543Z \n2022-07-30T19:05:14.332673Z ✘ [ERROR] Could not resolve \"util\"\n2022-07-30T19:05:14.332789Z \n2022-07-30T19:05:14.333338Z node_modules/sequelize/lib/data-types.js:2:21:\n2022-07-30T19:05:14.334026Z 2 │ const util = require(\"util\");\n2022-07-30T19:05:14.334206Z ╵ ~~~~~~\n2022-07-30T19:05:14.33441Z \n2022-07-30T19:05:14.334627Z The package \"util\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.334959Z \n2022-07-30T19:05:14.335106Z ✘ [ERROR] Could not resolve \"fs\"\n2022-07-30T19:05:14.335239Z \n2022-07-30T19:05:14.33556Z node_modules/pg-connection-string/index.js:4:17:\n2022-07-30T19:05:14.335971Z 4 │ var fs = require('fs')\n2022-07-30T19:05:14.336165Z ╵ ~~~~\n2022-07-30T19:05:14.336703Z \n2022-07-30T19:05:14.337207Z The package \"fs\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.337373Z \n2022-07-30T19:05:14.337521Z ✘ [ERROR] Could not resolve \"fs\"\n2022-07-30T19:05:14.337657Z \n2022-07-30T19:05:14.337784Z node_modules/firebase-admin/lib/app/lifecycle.js:21:19:\n2022-07-30T19:05:14.337911Z 21 │ const fs = require(\"fs\");\n2022-07-30T19:05:14.338056Z ╵ ~~~~\n2022-07-30T19:05:14.338211Z \n2022-07-30T19:05:14.338342Z The package \"fs\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n2022-07-30T19:05:14.338478Z \n2022-07-30T19:05:14.33862Z ✘ [ERROR] Could not resolve \"util\"\n2022-07-30T19:05:14.338756Z \n2022-07-30T19:05:14.339295Z node_modules/sequelize/lib/utils/logger.js:59:37:\n2022-07-30T19:05:14.339765Z 59 │ var import_util = __toModule(require(\"util\"));\n2022-07-30T19:05:14.339936Z ╵ ~~~~~~\n2022-07-30T19:05:14.340093Z \n2022-07-30T19:05:14.340237Z The package \"util\" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use \"platform: 'node'\" to do that, which will remove this error.\n\n\n...............\n\n\n2022-07-30T19:05:14.89587Z \n2022-07-30T19:05:14.896004Z error during build:\n2022-07-30T19:05:14.896124Z Error: Build failed with 234 errors:\n2022-07-30T19:05:14.896252Z node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js:1:31: ERROR: Could not resolve \"stream\"\n2022-07-30T19:05:14.896371Z node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js:2:25: ERROR: Could not resolve \"util\"\n2022-07-30T19:05:14.896477Z node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js:1:29: ERROR: Could not resolve \"events\"\n2022-07-30T19:05:14.896588Z node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js:2:25: ERROR: Could not resolve \"util\"\n2022-07-30T19:05:14.896701Z node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js:1:25: ERROR: Could not resolve \"util\"\n2022-07-30T19:05:14.896818Z ...\n2022-07-30T19:05:14.896942Z at failureErrorWithLog (/opt/buildhome/repo/node_modules/esbuild/lib/main.js:1621:15)\n2022-07-30T19:05:14.897064Z at /opt/buildhome/repo/node_modules/esbuild/lib/main.js:1263:28\n2022-07-30T19:05:14.897441Z at runOnEndCallbacks (/opt/buildhome/repo/node_modules/esbuild/lib/main.js:1176:65)\n2022-07-30T19:05:14.897756Z at buildResponseToResult (/opt/buildhome/repo/node_modules/esbuild/lib/main.js:1261:7)\n2022-07-30T19:05:14.898025Z at /opt/buildhome/repo/node_modules/esbuild/lib/main.js:1374:14\n2022-07-30T19:05:14.898328Z at /opt/buildhome/repo/node_modules/esbuild/lib/main.js:675:9\n2022-07-30T19:05:14.898627Z at handleIncomingPacket (/opt/buildhome/repo/node_modules/esbuild/lib/main.js:772:9)\n2022-07-30T19:05:14.898889Z at Socket.readFromStdout (/opt/buildhome/repo/node_modules/esbuild/lib/main.js:641:7)\n2022-07-30T19:05:14.90122Z at Socket.emit (node:events:527:28)\n2022-07-30T19:05:14.901427Z at addChunk (node:internal/streams/readable:315:12)\n2022-07-30T19:05:14.917314Z Failed: build command exited with code: 1\n2022-07-30T19:05:16.243508Z Failed: an internal error occurred\n```\n\n```text\nwrangler.toml\n```\n\n========================================\n\nComments:\n- Note for others reading this in 2024: You can now enable a `nodejs_compat` flag in your `wrangler.toml` so that a limited number of Node.js built-ins can be safely used. See docs here: developers.cloudflare.com/workers/configuration/…","metadata":{"transformedAt":"2026-08-18T18:33:40.665Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":315,"estimatedTokens":5343}}104{"id":"stack-72339759","source":"stackoverflow","questionId":72339759,"title":"Right Typescript type for on:change handler in Svelte","tags":["typescript","svelte"],"text":"Title: Right Typescript type for on:change handler in Svelte\nTags: typescript, svelte\nSource: Stack Overflow\n\nQuestion:\nI have this code:\n\n```\n\n```\n\nThe signature for `pathChanged` is:\n\n```\nfunction pathChanged(event: { target: HTMLSelectElement }) {\n```\n\nWhen I run that through `tsc` using `npm run check`, I get this error:\n\n```\nError: Type '(event: { target: HTMLSelectElement; }) => void' is not assignable to type 'FormEventHandler'.\n Types of parameters 'event' and 'event' are incompatible.\n Type 'Event & { currentTarget: EventTarget & HTMLSelectElement; }' is not assignable to type '{ target: HTMLSelectElement; }'.\n Types of property 'target' are incompatible.\n Type 'EventTarget | null' is not assignable to type 'HTMLSelectElement'.\n Type 'null' is not assignable to type 'HTMLSelectElement'. (ts)\n\n```\n\nWhat signature should `pathChanged` have?\n\n========================================\n\nTop Answer:\nI did this in an input type `file`:\n\n```\n// added this interface\ninterface FormEventHandler {\n target: EventTarget | null;\n}\n\n// then in the function\nconst onChangeFile = async (event: FormEventHandler) => {\n const target = event.target as HTMLInputElement;\n // your code\n}\n```\n\n========================================\n\nCode:\n```text\n<select class=\"form-control\" on:change={pathChanged}>\n```\n\n```text\nfunction pathChanged(event: { target: HTMLSelectElement }) {\n```\n\n```text\nError: Type '(event: { target: HTMLSelectElement; }) => void' is not assignable to type 'FormEventHandler<HTMLSelectElement>'.\n Types of parameters 'event' and 'event' are incompatible.\n Type 'Event & { currentTarget: EventTarget & HTMLSelectElement; }' is not assignable to type '{ target: HTMLSelectElement; }'.\n Types of property 'target' are incompatible.\n Type 'EventTarget | null' is not assignable to type 'HTMLSelectElement'.\n Type 'null' is not assignable to type 'HTMLSelectElement'. (ts)\n\n<select class=\"form-control\" on:change={pathChanged}>\n```\n\n```text\npathChanged\n```\n\n```text\ntsc\n```\n\n```text\nnpm run check\n```\n\n```text\npathChanged\n```\n\n```js\nfunction pathChanged(event: Event) {\n const target = event.target as HTMLSelectElement;\n // ...\n}\n```\n\n```js\nfunction pathChanged(event: { currentTarget: HTMLSelectElement })\n```\n\n```js\nfunction onMouseUp(event: MouseEvent & { currentTarget: HTMLSelectElement })\n```\n\n```text\ntarget\n```\n\n```text\ncurrentTarget\n```\n\n```text\nEvent\n```\n\n```text\nMouseEvent\n```\n\n```text\n&\n```\n\n```text\ntarget\n```\n\n```text\ncurrentTarget\n```\n\n```js\n// added this interface\ninterface FormEventHandler<T> {\n target: EventTarget | null;\n}\n\n// then in the function\nconst onChangeFile = async (event: FormEventHandler<HTMLInputElement>) => {\n const target = event.target as HTMLInputElement;\n // your code\n}\n```\n\n```text\nfile\n```\n\n```ts\nconst pathChanged: ChangeEventHandler<HTMLSelectElement> = (event) => {\n console.log(event.currentTarget)\n}\n```\n\n```text\nChangeEventHandler\n```\n\n```text\nevent\n```\n\n```text\nevent.target\n```\n\n```text\nevent.currentTarget\n```\n\n```text\ntarget\n```\n\n```text\ncurrentTarget\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.665Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":176,"estimatedTokens":767}}105{"id":"stack-62884259","source":"stackoverflow","questionId":62884259,"title":"Making class instance reactive in Svelte using stores","tags":["javascript","oop","svelte","svelte-3","svelte-store"],"text":"Title: Making class instance reactive in Svelte using stores\nTags: javascript, oop, svelte, svelte-3, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI am learning Svelte by creating simple app.\n\nThe logic is written using classes. The idea is, that all the data needed comes from class instance properties. Instances should not be instantiated more than once. I am using stores to provide components this instances.\n\nThe problem is I can't get reactivity using this approach. I tried readable and writable stores and nothing helps. It is still possible to get reactivity using OOP and what can I do? Reassignment and creating new instances will be expensive.\n\n**Edit**\n\nI can't make up the example in REPL cause the class is too big.\n\n*Parser.js*\n\n```\nexport default class Parser {\n constructor() {\n this._history = [];\n }\n\n parse(string) {\n this._history.push(string)\n }\n\n get history() {\n return this._history;\n }\n}\n```\n\nHere I pass instance to the store.\n\n*parserStore.js*\n\n```\nimport writable from \"svelte/store\";\nimport Parser from \"Parser.js\"\n\nexport const parserStore = writable(new Parser());\n```\n\nIn this component I get the instance and use reactively a method.\n\n*Component_1.svelte**\n\n```\nimport { parserStore } from \"parserStore.js\";\n\n$: result = parserStore.parse(binded_input_value);\n```\n\nWhat I want to get is the up to time history property that was updated from using class method:\n\n*Component_2.svelte*\n\n```\nimport { parserStore } from \"parserStore.js\";\n\n$: history = parserStore.history;\n\n{#each history as ... }\n```\n\nI know, it is not the best example, but what I want is reactive class instance available through the store. Actually the values are up to date, but it is not causing the re-render of the components. When the component is mounted - data of the latest, but after nothing re-renders at all even so the properties of the instance is changed.\n\n========================================\n\nTop Answer:\nHad the same problem and found a solution how it is possible to use \"reactive\" classes in svelte.\n\nIn svelte anything with a subscribe function is a store. So if you want to make a class to a store you have to implement a subscribe function.\n\n```\nimport { writable } from 'svelte/store';\n\nclass ClassStore {\n constructor() {\n this._history = writable([])\n }\n\n parse(string) {\n this._history.update(v => [...v, string])\n }\n \n subscribe(run) {\n return this._history.subscribe(run);\n }\n}\n\nexport const classStore = new ClassStore();\n```\n\nHere is a working example: https://svelte.dev/repl/8e3f4f664cc14710afce0c9683e04652?version=3.42.6\n\n========================================\n\nCode:\n```text\nexport default class Parser {\n constructor() {\n this._history = [];\n }\n\n parse(string) {\n this._history.push(string)\n }\n\n get history() {\n return this._history;\n }\n}\n```\n\n```text\nimport writable from \"svelte/store\";\nimport Parser from \"Parser.js\"\n\nexport const parserStore = writable(new Parser());\n```\n\n```text\nimport { parserStore } from \"parserStore.js\";\n\n$: result = parserStore.parse(binded_input_value);\n```\n\n```text\nimport { parserStore } from \"parserStore.js\";\n\n$: history = parserStore.history;\n\n{#each history as ... }\n```\n\n```js\nimport { writable } from 'svelte/store'\n\nclass Parser {\n constructor() {\n this._history = writable([])\n }\n\n parse(string) {\n console.log(string)\n this._history.update(v => [...v, string])\n }\n\n get history() {\n return this._history;\n }\n}\n```\n\n```js\nimport { Parser } from './Parser.js'¨\n\nexport const parser = new Parser()\n```\n\n```html\n<script>\n import { parser } from './parserStore.js';\n\n let value\n let { history } = parser\n \n $: parser.parse(value);\n</script>\n\n<input bind:value />\n\n{#each $history as h}<p>{h}</p>{/each}\n```\n\n```js\nimport { writable } from 'svelte/store'\n\nexport const parser = (() => {\n const P = writable([]) \n const { set, subscribe, update } = P \n \n function parse(string) {\n P.update(arr => [...arr, string])\n }\n \n return {\n parse,\n subscribe\n }\n})()\n```\n\n```html\n<script>\n import { parser } from './parserStore.js';\n\n let value\n $: parser.parse(value)\n</script>\n\n<input bind:value />\n\n{#each $parser as h}<p>{h}</p>{/each}\n```\n\n```js\n...\n return {\n parse,\n history: { subscribe }\n }\n```\n\n```html\n<script>\n ...\n const { history } = parser\n ...\n</script>\n\n{#each $history as h}<p>{h}</p>{/each}\n```\n\n```text\nhistory\n```\n\n```text\nhistory\n```\n\n```text\nparser\n```\n\n```js\nexport default class Parser {\n constructor() {\n this._history = [];\n }\n\n parse(string) {\n this._history.push(string)\n }\n\n get history() {\n return this._history;\n }\n \n save() {\n return this;\n }\n}\n```\n\n```js\nimport { Parser } from \"Parser.js\";\nimport writable from \"svelte/store\";\n\n// create new class instance\nconst p = new Parser();\n\n// add some values\np.parse(binded_input_value);\n\n// save that class instance\nconst parserStore = writable(p.save());\n\n// can be called after page is loaded\nfunction showHistory() {\n console.log(get(parserStore).history);\n}\n```\n\n```text\nsave()\n```\n\n```text\np.save()\n```\n\n```text\nsetContext()\n```\n\n```text\ngetContext()\n```\n\n```js\nimport { writable } from 'svelte/store';\n\nclass ClassStore {\n constructor() {\n this._history = writable([])\n }\n\n parse(string) {\n this._history.update(v => [...v, string])\n }\n \n subscribe(run) {\n return this._history.subscribe(run);\n }\n}\n\nexport const classStore = new ClassStore();\n```\n\n```text\n/*\nI recently jumped into svelte programming and wanted to create a class/singleton that could double as a reactive writable store. \nI did things very wrong until people on the discord confirmed how wrong my implementation was so I wanted to provide a simple example.\nSo below is a simple account store you can use. I'm not sure if it's optimal or even correct, but it's better than my first attempt. \nFeel free to provide feedback.\n*/\n...\n```\n\n```none\nimport { type Subscriber, type Writable } from 'svelte/store';\n\nconst dummy: () => void = () => {};\nconst updateStore = <T>(store: Writable<T>, callback: (state: T) => void) => {\n store.update((state) => {\n callback(state);\n return state;\n });\n};\n\nexport abstract class SvelteStore<T> {\n protected abstract store: Writable<T>;\n constructor() {}\n subscribe(callback: Subscriber<T>) {\n return this.store.subscribe(callback);\n }\n update(callback?: (state: T) => void) {\n updateStore(this.store, callback || dummy);\n }\n protected set<T extends SvelteStore<T>>() {\n this.update();\n }\n}\n```\n\n```js\nimport {writable} from 'svelte/store';\n\nexport class Parser extends SvelteStore<Parser>{\n protected store = writable(this as Parser); // registering `this`\n\n constructor(private readonly _history = []) {}\n\n parse(string) {\n this._history.push(string)\n this.update(); // triggers re-rendering\n }\n\n get history() {\n return this._history;\n }\n}\n```\n\n```js\n<script>\nimport { parserStore } from \"parserStore.js\";\nimport {Parser} from './parser.store.js'\n\nconst parser = new Parser();\n\nconst addHistory = () => {\n const randomText = Math.random().toString();\n parser.parse(randomText);\n}\n</script>\n\n<button on:click={addHistory}>parse anything</button>\n<ul>\n{#each $parser.history as history }\n <li>{history}</li>\n{/each}\n</ul>\n```\n\n```text\nparser.store.ts\n```\n\n```text\nparser\n```\n\n========================================\n\nComments:\n- We need to see what you did. Show your code, here, or on a svelte REPL.\n- @AndreasDolk I tried to provide some sort of example, I hope it will help!\n- Oh, I see. Thank you! I guess, I will use the \"store as a part of class\" approach. I did not think about it, wow!\n- Now how do you get `this._history` or `P` within your class, as it is a writable type and not your actual value at a certain point in time...?\n- As put below, other examples of implementations for classes and Svelte stores: gist.github.com/3lpsy/55da83779a50f603a78ae8331e360a37 and \"6.7 Using stores with classes\" livebook.manning.com/book/svelte-and-sapper-in-action/chapte‌​r-6/…\n- How would you get items or count of items in the history when it is 'writable' store? `history.length` does not work anymore. It seem it is not suitable for more performant code. I want to use certain state 'as is' when i call another method. So I only want to ensure that when i call `parser.history` it has the most recent list of items, without 'notifying me' on changes explicitly (via subscribe)","metadata":{"transformedAt":"2026-08-18T18:33:40.665Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":406,"estimatedTokens":2125}}106{"id":"stack-69791435","source":"stackoverflow","questionId":69791435,"title":"svelte list won't update when I add to an array","tags":["javascript","svelte"],"text":"Title: svelte list won't update when I add to an array\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm just starting out with svelte... so, this is probably a noob question.\n\nI have a list, and I can remove items from the array and the list (#each) updates no problems.\n\n...but if I add an item to the array the list doesn't redraw until I remove another item...\n\nhttps://svelte.dev/repl/ef316351462a434691388351aef1676a?version=3.44.0\n\n========================================\n\nCode:\n```js\n//Short Syntax \ntickets = [...tickets, newTicket]\n\n// Or\ntickets.push(newTicket);\n\ntickets = tickets;\n```\n\n========================================\n\nComments:\n- Don’t use push for update the array, use spread operator, like this tickets = [...tickets, newItem];\n- ah, as in create a new array with the extra entry, rather than push an entry onto the old array? does svelte watch for the array being replaced or something?\n- thankyou, I used the spread operator, and it now works as expected. svelte.dev/repl/16a22798ab1a49468d08dedf1bffee1d?version=3.4‌​4.0\n- For checking reactivity svelte check assign operator.\n- You saved an hour. Thank you","metadata":{"transformedAt":"2026-08-18T18:33:40.665Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":34,"estimatedTokens":291}}107{"id":"stack-69332819","source":"stackoverflow","questionId":69332819,"title":"Svelte +Vite: writable store in Typescript, cannot import Writable interface","tags":["typescript","svelte","vite"],"text":"Title: Svelte +Vite: writable store in Typescript, cannot import Writable interface\nTags: typescript, svelte, vite\nSource: Stack Overflow\n\nQuestion:\nIn a Svelte project scaffolded using Vite I try to write a Svelte store in Typescript; having troubles with importing `Writable` interface like below:\n\n```\nimport { Writable, writable, derived } from 'svelte/store';\n```\n\nThis results in the following error in a browser console:\n\n```\nUncaught SyntaxError: The requested module '/node_modules/.vite/svelte_store.js?v=16f52463' does not provide an export named 'Writable'.\n```\n\nIs there any way to import `Writable` interface in such a setup?\n\n========================================\n\nCode:\n```text\nimport { Writable, writable, derived } from 'svelte/store';\n```\n\n```text\nUncaught SyntaxError: The requested module '/node_modules/.vite/svelte_store.js?v=16f52463' does not provide an export named 'Writable'.\n```\n\n```text\nWritable<T>\n```\n\n```text\nWritable<T>\n```\n\n```text\nimport type { Writable } from 'svelte/store';\nimport { writable, derived } from 'svelte/store';\n```\n\n```text\nimport { type Writable, writable, derived } from 'svelte/store';\n```\n\n```text\nimport type { Writable } from 'svelte/store';\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.665Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":50,"estimatedTokens":302}}108{"id":"stack-59119677","source":"stackoverflow","questionId":59119677,"title":"How to bind input value from child component in Svelte?","tags":["javascript","single-page-application","svelte"],"text":"Title: How to bind input value from child component in Svelte?\nTags: javascript, single-page-application, svelte\nSource: Stack Overflow\n\nQuestion:\n### ideal\n\nI'd like to get input data from child component.\n\n### What I have tried\n\n```\n\n import Input from \"./Input.svelte\";\n let userGoal = \"\";\n\n### Your Goal is {userGoal}\n\n```\n\n```\n\n export let userGoal = \"\";\n\n $: console.log(userGoal);\n\n```\n\n`$: console.log(userGoal);` shows userGoal at each event which is as I expected. However, It doesn't affect to parent Component.\n\n### Summary\n\nI'm new to Svelte.\nAny help is appreciated.\n\n========================================\n\nCode:\n```text\n<script>\n import Input from \"./Input.svelte\";\n let userGoal = \"\";\n</script>\n\n<h1>Your Goal is {userGoal}</h1>\n\n<Input {userGoal} />\n```\n\n```text\n<script>\n export let userGoal = \"\";\n\n $: console.log(userGoal);\n</script>\n\n<input type=\"text\" bind:value={userGoal} />\n```\n\n```text\n$: console.log(userGoal);\n```\n\n```html\n<Input bind:userGoal/>\n```\n\n```text\n<Input {userGoal}/>\n```\n\n```text\nbind:userGoal={somethingElse}\n```\n\n========================================\n\nComments:\n- Wow, great. Thank you very much. I have an another question, but why it's different way from \"parent to child\"? When trying pass input value to child, I didn't need to write `bind`.\n- Because normally data should flow from parents to children. Flowing from children to parents should be the exception, used sparingly.","metadata":{"transformedAt":"2026-08-18T18:33:40.665Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":80,"estimatedTokens":359}}109{"id":"stack-58884662","source":"stackoverflow","questionId":58884662,"title":"How does `:` in `on:click` work, in Svelte?","tags":["javascript","html","frontend","dom-events","svelte"],"text":"Title: How does `:` in `on:click` work, in Svelte?\nTags: javascript, html, frontend, dom-events, svelte\nSource: Stack Overflow\n\nQuestion:\nI am experimenting with Svelte and following the official tutorial. At https://svelte.dev/tutorial/reactive-assignments, I am instructed to use this line of code:\n\n```\n\n```\n\nWhat is the purpose of the colon? Why isn't it simply `I found the Svelte API documentation on element directives, which provides usage examples within Svelte, but I still don't understand how this is valid JS syntax, or how it is transformed to such. I don't understand how the colon *works* (as separate from understanding its *usage*).\n\nI can understand that this was a way to implement a single directive for all DOM event attributes, but its actual functioning is not that transparent to me.\n\n========================================\n\nTop Answer:\nThe first thing to understand is that the code in Svelte components is actually not the resulting JavaScript that is sent to the browser, so about:\n\n I still don't understand how this is valid JS syntax\n\nIt is not. It is \"compiled\" into valid JavaScript by SvelteJS's compiler.\n\nI have not roamed through the source code, but I presume the colon in this case, is used to denote the event handler binding directive (`on`) from the event itself (`click`).\n\nFor an actual demonstration of the compilation: you can visit the REPL and select the \"Js output\" tab to see the compiled JavaScript code.\n\n========================================\n\nCode:\n```js\n<button on:click={handleClick}>\n```\n\n```text\n<button onclick=...\n```\n\n```text\n<button onclick=...\n```\n\n```text\nonclick\n```\n\n```text\non:click\n```\n\n```text\n:\n```\n\n```text\non:...\n```\n\n```text\nbind:...\n```\n\n```text\nin:...\n```\n\n```text\nout:...\n```\n\n```text\ntransition:...\n```\n\n```text\non\n```\n\n```text\nclick\n```\n\n```text\n<button on:click ... />\n```\n\n```text\n<button on:click on:doWhatever...\n```\n\n```text\nonclick\n```\n\n========================================\n\nComments:\n- Vue uses `@click`, Angular uses `(click)` etc. As mentioned below it's not valid, it's run through some compilation.\n- pardon me if this is a stupid question, svelte is a compiler right? so does that mean it reads this file with the on:click and generates some JS code from it which is what the browsers eventually run? how does it generate platform specific JS code?\n- Visit the REPL, click 'JS Output'. All will be revealed\n- NOTE: as of Svelte 5, you should use `onclick` instead of `on:click` svelte.dev/docs/svelte/…","metadata":{"transformedAt":"2026-08-18T18:33:40.665Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":102,"estimatedTokens":627}}110{"id":"stack-71896236","source":"stackoverflow","questionId":71896236,"title":"How to put my text in a single line in tailwind css?","tags":["html","tailwind-css","svelte"],"text":"Title: How to put my text in a single line in tailwind css?\nTags: html, tailwind-css, svelte\nSource: Stack Overflow\n\nQuestion:\nI want the result to be like this\n\nhttps://i.sstatic.net/Eu7b9.png\n\nbut this is what i get\n\nhttps://i.sstatic.net/TLsyo.png\n\nwith my svelte code:\n\n```\n\n \n\n \n \n \n By {unsplash?.author.username}\n \n\n \n Find similar pictures on Unsplash\n \n\n \n\n```\n\ni used inline-block, but doesn't work\n\n========================================\n\nTop Answer:\nYou probably want Whitespace exactly `whitespace-nowrap` which is `white-space: nowrap;`\nAlthough you may look at Word break and Text overflow\n\n========================================\n\nCode:\n```js\n<div\n style=\"background-image: url('{unsplash?.url}');\"\n class=\"bg-black flex items-center justify-center min-h-screen bg-cover\"\n>\n <Authenticate />\n\n<!-- here is my div -->\n\n <div class=\"block flex absolute bottom-9 left-5 h-16 w-16\">\n <img src={unsplash?.author.avatar} alt={unsplash?.author.username} class=\"rounded-full\" />\n <p class=\"inline-block text-blank ml-2\">\n By <a class=\"inline-block\" target=\"__blank\" href={unsplash?.author.url}\n >{unsplash?.author.username}</a\n >\n </p>\n <p class=\"inline-block text-black\">\n Find similar pictures on <a class=\"inline-block\" target=\"__blank\" href=\"http://unsplash.com\"\n >Unsplash</a\n >\n </p>\n </div>\n</div>\n```\n\n```text\nwhitespace-nowrap\n```\n\n```text\nwhite-space: nowrap;\n```\n\n========================================\n\nComments:\n- `inline-block` has nothing to do with internal wrapping, though it enforces a box around the content. For an explanation what `inline-block` is about see this question. To prevent wrapping you need to set `white-space: nowrap` or similar; don't know what the respective Tailwind class for that is...\n- yeah, it worked, thanks. but i have a problem imgur.com/loJuRxo I want \"Find similar pictures on Unsplash\" this one below\n- Then don't use `inline-block` on the `p` elements, that puts the elements in text flow mode, `p` should stack on top of each other by default (they are block elements).\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:40.665Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":84,"estimatedTokens":583}}111{"id":"stack-67808939","source":"stackoverflow","questionId":67808939,"title":"How can I tell whether SvelteKit's \"load\" function is running on the server vs. client?","tags":["svelte","sveltekit"],"text":"Title: How can I tell whether SvelteKit's \"load\" function is running on the server vs. client?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm trying to do API calls in a SvelteKit page from the load function, but I don't want to proxy these calls with local endpoints because I want to keep the web server as light as possible.\n\nWhat I want to do specifically is, when the call is made from the server, the API's URL should be different than when it's called from the client (e.g. \"http://localhost:1234\" vs. \"https://example.com:1234\", respectively).\n\nBut, more generally than this, **is there a way to differentiate whether the current code is running on the server vs. the client?**\n\n========================================\n\nTop Answer:\nDisclaimer: what I'm writing is not the real answer to the title, but it is the specific answer to the described problem.\n\nThere's a targeted hook function (`handleFetch`) that's build to address resources differently if client or server:\n\nhttps://kit.svelte.dev/docs/hooks#server-hooks-handlefetch\n\n```\n/** @type {import('@sveltejs/kit').HandleFetch} */\nexport async function handleFetch({ request, fetch }) {\n if (request.url.startsWith('https://api.yourapp.com/')) {\n // clone the original request, but change the URL\n request = new Request(\n request.url.replace('https://api.yourapp.com/', 'http://localhost:9999/'),\n request\n );\n }\n\n return fetch(request);\n}\n```\n\n========================================\n\nCode:\n```js\n<script context=\"module\">\n import { browser } from '$app/environment'; \n ...\n export async function load({ fetch }) {\n if (!browser) {\n // code here runs only on the server\n }\n return {\n ...\n }\n }\n ...\n<script>\n```\n\n```text\nload\n```\n\n```text\nbrowser\n```\n\n```text\n$app/environment\n```\n\n```js\n/** @type {import('@sveltejs/kit').HandleFetch} */\nexport async function handleFetch({ request, fetch }) {\n if (request.url.startsWith('https://api.yourapp.com/')) {\n // clone the original request, but change the URL\n request = new Request(\n request.url.replace('https://api.yourapp.com/', 'http://localhost:9999/'),\n request\n );\n }\n\n return fetch(request);\n}\n```\n\n```text\nhandleFetch\n```\n\n========================================\n\nComments:\n- is there anything wrong with just process.browser?\n- @koo5 Wouldn't that mean adding the process dependency? Not sure if that one is an ES module. A CJS module may not work for SvelteKit without some unnecessary workarounds (FAQ).\n- can i use `browser` outside of load function?\n- @chovy The `browser` var gets initialized and that way gets it's value outside of the `load` function. So this var's scope is surrounding that `load` function's scope. You can of course pass the var as an arg to a scope even more outside to a custom function to use it's value in the scope of that custom function.","metadata":{"transformedAt":"2026-08-18T18:33:40.665Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":92,"estimatedTokens":732}}112{"id":"stack-62626343","source":"stackoverflow","questionId":62626343,"title":"Svelte: transition on reactive data change","tags":["svelte","svelte-transition"],"text":"Title: Svelte: transition on reactive data change\nTags: svelte, svelte-transition\nSource: Stack Overflow\n\nQuestion:\nWhat would be the best way to trigger an animation when a reactive variable changes?\nI would like to do something like this : \n\n```\n\n import { fade } from 'svelte/transition'\n let count = 0;\n const handleClick = () => count +=1\n\n Click me\n\n You cliked **{count}** times\n\n```\n\nWhich doesn't work because the ``node isn't removed from the DOM (I guess). So what would be the best way to have numbers fading in and out when they change?\n\n========================================\n\nCode:\n```html\n<script>\n import { fade } from 'svelte/transition'\n let count = 0;\n const handleClick = () => count +=1\n</script>\n\n<button on:click={handleClick} transition:slide>\n Click me\n</button>\n<p> You cliked <strong transition:fade>{count}</strong> times</p>\n```\n\n```text\n<strong>\n```\n\n```html\n<script>\n import { fade } from 'svelte/transition'\n let count = 0;\n const handleClick = () => count +=1\n</script>\n\n<button on:click={handleClick}>\n Click me\n</button>\n<p> You cliked \n {#key count}\n <strong in:fade>{count}</strong> \n {/key}\n times</p>\n```\n\n```html\n<script>\n import { fade } from 'svelte/transition'\n let count = 0;\n const handleClick = () => count +=1\n</script>\n\n<button on:click={handleClick}>\n Click me\n</button>\n<p> You cliked \n {#each [count] as c (c)}\n <strong in:fade>{c}</strong> \n {/each}\n times</p>\n```\n\n```text\n{#key <key}\n```\n\n========================================\n\nComments:\n- It is working indeed, thanks! I leave the question as seems to be a bit hacky, maybe there is a more idiomatic way to do it. I'll accept in a couple day, if not 😅\n- Accepted, can't seem to find any better way for now. Thanks ! ;)\n- there is now a {#key} directive. I have updated my answer\n- Oh that's really nice! Thanks,","metadata":{"transformedAt":"2026-08-18T18:33:40.665Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":87,"estimatedTokens":472}}113{"id":"stack-73747781","source":"stackoverflow","questionId":73747781,"title":"node.component is not a function","tags":["typescript","forms","svelte","sveltekit"],"text":"Title: node.component is not a function\nTags: typescript, forms, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm trying out sveltekit form actions, and it keeps on giving 500 Internal Error with the title in the console: `node.component is not a function`\n\n`src/routes/login/+page.server.js`\n\n```\nimport type { Actions } from '@sveltejs/kit';\n\nexport const actions: Actions = {\n default: async ({ request, cookies, url }) => {\n return { success: true }\n }\n};\n```\n\n`src/routes/+page.svelte`\n\n```\n\n \n Login\n \n\n```\n\n========================================\n\nTop Answer:\nI'm adding this answer because I ran into this same problem, but couldn't find a missing `+page.svelte` for a form.\n\nI had a nested `+layout.server.ts` that I was just using to serve data, but I didn't have a corresponding `+layout.svelte`.\n\nI just put `` in this new, nested `+layout.svelte`.\n\n========================================\n\nCode:\n```text\nimport type { Actions } from '@sveltejs/kit';\n\nexport const actions: Actions = {\n default: async ({ request, cookies, url }) => {\n return { success: true }\n }\n};\n```\n\n```html\n<form method=\"POST\" action=\"/login\">\n <div class=\"card-body\"> \n <button class=\"btn btn-primary w-100\" type=\"submit\">Login</button>\n </div>\n</form>\n```\n\n```text\nnode.component is not a function\n```\n\n```text\nsrc/routes/login/+page.server.js\n```\n\n```text\nsrc/routes/+page.svelte\n```\n\n```text\nsrc/routes/login/+page.svelte\n```\n\n```text\n+page.svelte\n```\n\n```text\n+layout.svelte\n```\n\n```text\n+layout.server.ts\n```\n\n```text\n+layout.svelte\n```\n\n```text\n<slot/>\n```\n\n```text\n+page.svelte\n```\n\n```text\n+layout.server.ts\n```\n\n```text\n+layout.svelte\n```\n\n```text\n<slot />\n```\n\n```text\n+layout.svelte\n```\n\n```text\nsrc/blog/[slug]/page.svelte\n```\n\n```text\nsrc/blog/[slug]/+page.svelte\n```\n\n```text\nTypeError: node.component is not a function\n```\n\n========================================\n\nComments:\n- Oof. Would be good to see the framework handle that better. Without this answer, it would have taken me forever to figure that out.","metadata":{"transformedAt":"2026-08-18T18:33:40.665Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":131,"estimatedTokens":512}}114{"id":"stack-50352748","source":"stackoverflow","questionId":50352748,"title":"How to disable field conditionally in Svelte?","tags":["html","svelte"],"text":"Title: How to disable field conditionally in Svelte?\nTags: html, svelte\nSource: Stack Overflow\n\nQuestion:\nIn Angular 2+ (for example), I can use this syntax to disable a field conditionally:\n\n```\n\n```\n\nIn Svelte I'm trying to do as follows, but it doesn't work:\n\n```\n\n```\n\nHow can I do it?\n\n========================================\n\nTop Answer:\n```\n\n let disabled = true;\n\n```\n\nThis is the shorthand for:\n\n```\n\n let disabled = true;\n\n```\n\nIt works because when the attribute name and value match (name={name}), they can be replaced with {name}.\n\nYou can find this at Svelte Docs\n\nWorks the same in a button:\n\n```\nCan't Click\n```\n\n========================================\n\nCode:\n```text\n<input [disabled]=\"booleanCondition\" type=\"text\">\n```\n\n```text\n<input {booleanCondition ? 'disabled=\"\"' : ''} type=\"text\">\n```\n\n```html\n<input disabled={booleanCondition}>\n```\n\n```html\n<!-- Nested.svelte -->\n<input disabled={ $$props.disabled }>\n```\n\n```html\n<!-- App.svelte -->\n<Nested disabled={ booleanCondition }/>\n```\n\n```html\n<!-- Nested.svelte -->\n<script>\nconst { type, name, required, disabled } = $$props\n</script>\n<input { type } { name } { required } { disabled }>\n```\n\n```html\n<!-- App.svelte -->\n<Nested type=\"text\" name=\"myName\" required disabled={ booleanCondition }/>\n```\n\n```text\n<script>\n let disabled = true;\n</script>\n\n<input {disabled} type=\"text\"/>\n```\n\n```text\n<script>\n let disabled = true;\n</script>\n\n<input disabled={disabled} type=\"text\"/>\n```\n\n```text\n<button {disabled}>Can't Click</button>\n```\n\n```text\n<input disabled={booleanCondition || null} type=\"text\">\n```\n\n========================================\n\nComments:\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:40.665Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":112,"estimatedTokens":479}}115{"id":"stack-73214622","source":"stackoverflow","questionId":73214622,"title":"How to Enable CORS on a Sveltekit Standalone Endpoint?","tags":["svelte","server-side-rendering","sveltekit"],"text":"Title: How to Enable CORS on a Sveltekit Standalone Endpoint?\nTags: svelte, server-side-rendering, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm building an embed that needs access to a sveltkit endpoint from any origin.\n\nIf I was using express I would simply use the `cors` middleware.\n\nI'm curious if there is a way to enable CORS on sveltkit endpoints so I don't need to spin up another service.\n\nSome things I've tried so far:\n\nReturning 'Access-Control-Allow-Origin': '*' from the get handle in the endpoint\n\nOverriding the OPTIONS http method (never seems to get called)\n\nI saw this reddit post but it seems outdated.\n\n========================================\n\nTop Answer:\nI encountered a similar issue but couldn't use the `express` workaround.\n\nThis however has worked for me:\n\n```\nconst response = new Response();\n \n response.headers.append('Access-Control-Allow-Origin', );\n\n return response;\n```\n\nSveltekit: https://kit.svelte.dev/docs/web-standards#fetch-apis-headers\n\nMDN: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n\n========================================\n\nCode:\n```text\ncors\n```\n\n```js\n// this is file exported by the node adapter plugin\nimport { handler } from './build/handler.js'; \nimport express from 'express';\nimport cors from 'cors';\n\nconst app = express();\napp.use(cors());\n\n// add a route that lives separately from the SvelteKit app \napp.get('/healthcheck', (req, res) => { res.end('ok'); });\n\n// let SvelteKit handle everything else, including serving prerendered pages and static assets app.use(handler);\n\napp.listen(3000, () => { console.log('listening on port 3000'); });\n```\n\n```js\nconst response = new Response(<YOUR_RESPONSE>);\n \n response.headers.append('Access-Control-Allow-Origin', <YOUR_URL>);\n\n return response;\n```\n\n```text\nexpress\n```\n\n```js\nexport async function OPTIONS() {\n return new Response(null, {\n headers: {\n 'Access-Control-Allow-Origin': '*', // Specify the url you wish to permit\n 'Access-Control-Allow-Methods': 'POST, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type',\n },\n })\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.665Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":85,"estimatedTokens":522}}116{"id":"stack-72251017","source":"stackoverflow","questionId":72251017,"title":"SvelteKit: disable SSR","tags":["server-side-rendering","svelte","sveltekit"],"text":"Title: SvelteKit: disable SSR\nTags: server-side-rendering, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI made an app in Svelte and now I wanted to port it to SvelteKit. My app uses `window` and `document` objects, but those aren't available in SSR. Firstly, it threw `ReferenceError: window is not defined`, but I fixed that by checking if the app is running in the browser. But because of that, my app is not working.\n\n========================================\n\nTop Answer:\nThe previous answer no longer works because of changes to SvelteKit. See this PR for more information: https://github.com/sveltejs/kit/pull/6197 and also the documentation: https://kit.svelte.dev/docs/page-options\n\nBasically now you disable SSR at the page/layout level, so instead of in `src/hooks.server.js`: (`hooks.js` was also separated into client and server with the addition of client side hooks.)\n\n```\nexport function handle({ event, resolve }) {\n return resolve(event, { \n ssr: false\n });\n```\n\nYou now do:\n\n```\n// src/routes/+layout.js\nexport const ssr = false;\n```\n\nMake sure to put the line above in `+layout.js` and not `+layout.svelte`.\n\n========================================\n\nCode:\n```text\nwindow\n```\n\n```text\ndocument\n```\n\n```text\nReferenceError: window is not defined\n```\n\n```js\nexport async function handle({ event, resolve }) {\n return resolve(event, { ssr: false });\n}\n```\n\n```text\nhandle\n```\n\n```text\nsrc/hooks.js\n```\n\n```text\nevent\n```\n\n```text\nbrowser\n```\n\n```js\nexport function handle({ event, resolve }) {\n return resolve(event, { \n ssr: false\n });\n```\n\n```js\n// src/routes/+layout.js\nexport const ssr = false;\n```\n\n```text\nsrc/hooks.server.js\n```\n\n```text\nhooks.js\n```\n\n```text\n+layout.js\n```\n\n```text\n+layout.svelte\n```\n\n```text\n<script lang=\"ts\">\n import { browser } from '$app/environment'; \n if(browswer){\n // Access browser apis\n }\n</script>\n```\n\n========================================\n\nComments:\n- May be I'm missing some setting, but `browser` is always `false`. I'm reading it under `load` of `__layout.svelte`.\n- And I'm running `dev`.\n- See the other answer for more recent versions\n- They are different concepts. You can have prerendering disabled and still do SSR.\n- Also in 2024: `Unexpected option config.kit.prerender.enabled`\n- I note that `vite` still tries to make a \"ssr bundle\" when building that seems to build empty .js files... And I have not found a way to stop vite from doing that in order to speed up `vite build`\n- @cassepipe still no good?\n- @cassepipe I have a similar issue. I have set disabled to false in my layout. But once pushed to netlify (my hosting) it builds a SSR bundle anyway and I still have a svelteKit-render function running on page loads. I am confused. Did you manage to resolve your own issue?","metadata":{"transformedAt":"2026-08-18T18:33:40.665Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":115,"estimatedTokens":696}}117{"id":"stack-58546496","source":"stackoverflow","questionId":58546496,"title":"v-show alternative for Svelte","tags":["conditional-statements","svelte","svelte-3"],"text":"Title: v-show alternative for Svelte\nTags: conditional-statements, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nThe case is that I'm showing `Loading` component on fetch request. I use store to set `$loading` to `true` and inside conditions is the `Loading` component. The problem is that the Loading component seems to be taking some time to show. It feels/looks like the reason is re-rendering of Loading component. So, I was looking for `v-show` like thing in Svelte, which I cannot find in Docs. (Don't get angry if its there, just tell me.)\n\nCan anyone help with this case?\n\n========================================\n\nTop Answer:\nIf you want a block of HTML that does not re-render when the condition is changed, here is a simple solution:\n\n```\n\n // Show.svelte\n export let show = true;\n\n \n\n .hide {\n display: none !important;\n }\n\n```\n\nAnd then use the `Show` component to create that block:\n\n```\n\n import Show from \"Show.svelte\";\n let show = true;\n\n { show = !show}}>\n Click to Show/Hide Content\n\n Content\n\n```\n\nI have posted the `Show` component as an npm package `https://www.npmjs.com/package/svelte-show`\n\n========================================\n\nCode:\n```text\nLoading\n```\n\n```text\n$loading\n```\n\n```text\ntrue\n```\n\n```text\nLoading\n```\n\n```text\nv-show\n```\n\n```text\n{#if someCondition}\n```\n\n```text\nhidden={!someCondition}\n```\n\n```text\n<script>\n // Show.svelte\n export let show = true;\n</script>\n\n<div class:hide={!show}>\n <slot />\n</div>\n\n<style>\n .hide {\n display: none !important;\n }\n</style>\n```\n\n```text\n<script>\n import Show from \"Show.svelte\";\n let show = true;\n</script>\n<button on:click={() => { show = !show}}>\n Click to Show/Hide Content\n</button>\n<Show {show}>\n <div>Content</div>\n</Show>\n```\n\n```text\nShow\n```\n\n```text\nShow\n```\n\n```text\nhttps://www.npmjs.com/package/svelte-show\n```\n\n========================================\n\nComments:\n- may be `class:show`?\n- Try creating a Loading component using only css with no external assets (no images, videos, lottie, etc) that way the component will show instantly. See loading.io/css for inspiration.\n- Wouldn't wrapping it in an `{ #if }` cause the element to re-render?\n- If the value of the condition changes, yes. That's the whole point!","metadata":{"transformedAt":"2026-08-18T18:33:40.666Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":123,"estimatedTokens":556}}118{"id":"stack-53495018","source":"stackoverflow","questionId":53495018,"title":"Exclude a page from _layout","tags":["svelte"],"text":"Title: Exclude a page from _layout\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nHello I am new to Svelte, Sapper & Express.\n\nThe problem:\n\nI am using Sappers _layout.html to display 2 components (header & menu) that should be displayed on all pages, save for the login page.\n\nWhat is the right way to achieve this ? \n\nPossible solutions:\n\nA) Serve the login page from the static folder, and use the express middleware to route to it? \n\nB) Have the login as the root of my project and move all other routes down a level so they can a common layout that dosnt involve the login page?\n\nC) Put and if statement in the layout and determine when the user is on the login page to hide the header & menu components.\n\nD) Not use the layout to display the components.\n\n========================================\n\nTop Answer:\nJust adding a similar answer as the accepted one, but with updated syntax for SvelteKit as of early 2022 (still in beta).\n\n```\n\nimport { page } from '$app/stores'\n\n{#if $page.url.pathname === '/fancy'}\n \n \n \n{:else}\n \n{/if}\n```\n\n========================================\n\nCode:\n```html\n<!-- src/routes/_layout.html -->\n{#if child.segment === 'login'}\n <svelte:component this={child.component} {...child.props}/>\n{:else}\n <div class=\"fancy-layout\">\n <svelte:component this={child.component} {...child.props}/>\n </div>\n{/if}\n```\n\n```text\nchild.segment\n```\n\n```text\n<!-- src/routes/__layout.svelte -->\n\n<script>\nimport { page } from '$app/stores'\n</script>\n\n{#if $page.url.pathname === '/fancy'}\n <div class=\"fancy-layout\">\n <slot />\n </div>\n{:else}\n <slot />\n{/if}\n```\n\n```text\nsrc/routes/\n│ (default)/ <-- In this folder you put all your ordinary routes.\n│ ├ dashboard/\n│ ├ item/\n│ └ +layout.svelte \n│ (no-layout)/ <-- In this folder you put the routes that shouldn't use a layout.\n│ ├ sign-in/\n```\n\n========================================\n\nComments:\n- Where does the child.segment come from? I see it is exported in github.com/sveltejs/realworld/blob/master/src/routes/… but I don't know where to set it's value. Thanks\n- @lsabi The `segment` prop is set magically by Sapper when you navigate thru the routes. See Sapper docs.\n- Since this answer is from 2018, this should probably be updated: `child.segment` is only `segment` now, as @mustofa.id pointed out. And the whole `` line is now ``\n- Can you post new answer for svelte-kit, this OP solution doesn't work.\n- I get `segment` is not defined in svelte-kit\n- @chovy SvelteKit is different from Sapper, see migration guides. In Kit you can use `page` store to get `segment` trickily via `url.pathname`. But if you need conditionally render element/component based on user login, I suggest to use `session` store instead.","metadata":{"transformedAt":"2026-08-18T18:33:40.666Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":94,"estimatedTokens":679}}119{"id":"stack-59889859","source":"stackoverflow","questionId":59889859,"title":"How can I return the rendered HTML of a Svelte component?","tags":["svelte","svelte-3"],"text":"Title: How can I return the rendered HTML of a Svelte component?\nTags: svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI'm having a tough time making a tooltip that runs off `use:action`. My requirements are:\n\n- Create a tooltip with HTML or a Component as the content\n\n- Without having to wrap a component in a ``\n\n- Hook in to premade libraries for flexibility\n\nPlease see my example code below. It doesn't work in the REPL due to Tippy.js dependencies, but I do have it working with simple HTML in my app. This is why my thinking is that I should seek to render a component, which acknowledges props like any other, then somehow take its HTML and put it in use:action call. (see \"content: '**Hey I work!**'\") It should be as simple to use as in the days of jQuery's tooltips.\n\nREPL link:\nhttps://svelte.dev/repl/e8fdf98eb42445e3b791d7c908581a71?version=3.17.3\n\n========================================\n\nCode:\n```text\nuse:action\n```\n\n```text\n<Tooltip><element></Tooltip>\n```\n\n```html\n<script>\nconst logHtml = el => {\n console.log(el.innerHTML)\n}\n</script>\n\n<div use:logHtml> ... </div>\n```\n\n```html\n<script>\n let el\n $: if (el) console.log(el.innerHTML)\n</script>\n\n<div bind:this={el}> ... </div>\n```\n\n```js\nexport function tipz(elem, { content, props, ...opts }) {\n let cmp\n\n const tp = tippy(elem, {\n onCreate() {\n cmp = new content({\n target: instance.popper.querySelector(\".tippy-content\"),\n props,\n });\n },\n ...opts\n })\n\n return {\n update(params) {\n // ensure reactivity\n if (cmp) {\n cmp.$set(params.props)\n }\n },\n destroy() {\n tp.destroy();\n if (cmp) {\n // cleanup component\n cmp.$destroy();\n }\n }\n };\n}\n```\n\n```text\ngenerate: 'ssr'\n```\n\n```text\nCmp.render()\n```\n\n```text\nbind:this\n```\n\n```text\nnew MyComponent\n```\n\n```text\ntippy.js\n```\n\n========================================\n\nComments:\n- Thank you so much! I learned a lot just from your answer. It's working now but there were two problems: 1. I was getting a weird `__update` error. Turns out Svelte 3.16.7 had a use:action bug in it, fixed in 3.17.0! 2. I had to modify the onCreate to additionally pass `, props` because it seemed to not be created with them. Updated REPL: svelte.dev/repl/ffd2b212ae9e48e4b0279e72c1c7cb21?version=3.1‌​7.3\n- Oh, you're right, you need to pass the props at component creation too. I fixed the code example. Thanks.\n- I've noticed this instantiates the component on init, meaning if I have 50 elements on the page, it makes 50 components. Any idea if it's possible to use `new MyComponent` without this happening?\n- Yes, it's be possible. It mainly depends on your lib providing the right hooks. For example, with tippyjs, you can create the `new Cmp` on `onShow` hook, and `$destroy` it on `onHidden`. `new Cmp` will render to the DOM synchronously, so you don't have to worry about the content flickering because the component is rendered too late. The one thing to worry about maybe, if you create the component only when the tooltip is shown, is that you'll probably have to store new props arriving through `update` in a local var or something, to be sure that the component is created with latest values.","metadata":{"transformedAt":"2026-08-18T18:33:40.666Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":107,"estimatedTokens":807}}120{"id":"stack-64092593","source":"stackoverflow","questionId":64092593,"title":"Svelte: is there a way to cache the API result in a way that it won't trigger the API call every time the component renders?","tags":["javascript","caching","svelte","store"],"text":"Title: Svelte: is there a way to cache the API result in a way that it won't trigger the API call every time the component renders?\nTags: javascript, caching, svelte, store\nSource: Stack Overflow\n\nQuestion:\nIt could be that I'm typing the wrong things in Google and can't get a good answer.\n\nIs there a \"svelte recommended\" way to store the value of a GET result, so that, on every refresh or link switch, the result in the store is used in the component until a timeout (where the API is called again)?\n\nMy purpose is to fetch blogposts from an external API and show them in a list but not on every refresh, or link switch.\n\nMy code:\n\n```\n\n let posts = [];\n\n onMount(async () => {\n const res = await fetch(apiBaseUrl + \"/blogposts\");\n posts = await res.json();\n });\n\n{#each posts as post}\n \n\n### {post.title}\n\n{/each}\n```\n\nIn pseudo-code what I want:\n\n```\nif (store.blogposts.timeout === true){\n onMount(...);\n // renew component\n}\n```\n\n========================================\n\nTop Answer:\nsvelte-query can help:\n\nSvelte Query is often described as the missing data-fetching library for Svelte, but in more technical terms, it makes fetching, caching, synchronizing and updating server state in your Svelte applications a breeze.\n\nnote: svelte-query is abandoned and will be replaced with @tanstack/svelte-query\n\n========================================\n\nCode:\n```text\n<script>\n let posts = [];\n\n onMount(async () => {\n const res = await fetch(apiBaseUrl + \"/blogposts\");\n posts = await res.json();\n });\n</script>\n\n{#each posts as post}\n <h5>{post.title}</h5>\n{/each}\n```\n\n```text\nif (store.blogposts.timeout === true){\n onMount(...);\n // renew component\n}\n```\n\n```text\nimport {writable} from 'svelte/store';\nexport const posts = writable([]);\nexport const timeout = writable(false);\n```\n\n```text\n<script>\nimport {posts, timeout} from \"./stores.js\"\n\n onMount(async () => {\n if($posts.length<1 || $timeout == true){\n const res = await fetch(apiBaseUrl + \"/blogposts\");\n $posts = await res.json();\n }\n});\n</script>\n\n {#each $posts as post}\n <h5>{post.title}</h5>\n {/each}\n```\n\n```text\n<script>\nlet posts = [];\n \nonMount(async () => { \n posts = await getdata();\n } \n \nconst getdata = async ()=>{\n // set cache lifetime in seconds\n var cachelife = 5000; \n //get cached data from local storage\n var cacheddata = localStorage.getItem('posts'); \n if(cacheddata){\n cacheddata = JSON.parse(cacheddata);\n var expired = parseInt(Date.now() / 1000) - cacheddata.cachetime > cachelife;\n }\n //If cached data available and not expired return them. \n if (cacheddata && !expired){\n return cacheddata.posts;\n }else{\n //otherwise fetch data from api then save the data in localstorage \n const res = await fetch(apiBaseUrl + \"/blogposts\");\n var posts = await res.json();\n var json = {data: posts, cachetime: parseInt(Date.now() / 1000)}\n localStorage.setItem('posts', JSON.stringify(json));\n return posts;\n }\n }\n \n{#each posts as post}\n<h5>{post.title}</h5>\n{/each}\n```\n\n```js\nlet data;\n let interval;\n\n onMount(async () => {\n // If data is cached, get it otherwise fetch it\n const cachedData = localStorage.getItem('cachedData');\n if (cachedData) {\n data = JSON.parse(cachedData);\n } else {\n data = await fetch('http://localhost:8080/blogposts')\n .then((response) => response.json())\n .then((dataJson) => dataJson)\n .catch((err) => console.warn(err));\n localStorage.setItem('cachedData', JSON.stringify(data));\n }\n\n // Clear the local storage after 3 seconds\n interval = setInterval(() => localStorage.clear(), 3000);\n });\n```\n\n```js\nonDestroy(() => {\n clearInterval(interval);\n });\n```\n\n```js\nexport function GET({ url }) {\n const data = [\n { title: 'Blog post 1', body: 'Body 1' },\n { title: 'Blog post 2', body: 'Body 2' },\n { title: 'Blog post 3', body: 'Body 3' }\n ];\n\n return new Response(JSON.stringify(data));\n}\n```\n\n```text\nlocalStorage.clear()\n```\n\n```text\nclearInterval\n```\n\n```text\nroutes/blogposts/+server.js\n```\n\n========================================\n\nComments:\n- Can you use svelte store to store a flag-variable, which tells when to reload posts?\n- how would you set the flag? api-call, on a timer? for a timer you can use setTimeout `setTimeout(() => { $timeout=true; }, 10 * 1000);` in post.svelte\n- @dagalti ’s answer is exactly what I had in mind.\n- this solved the refetch on route switch for me, which is good enough for me, but it did refetch on refresh. my guess is on refresh the store is empty again making the first condition in if statement true. I'm gonna accept the answer, however I think there is a more complete answer. Thanks.\n- @QuintenSpillemaeckers updated the code for localstorage cache.\n- Although this answers the question, \"Sveltekit's local storage\" may be confusing; SvelteKit by itself doesn't have local storage, at least not server-side. You are talking about the browser standard Web Storage API (localStorage), including a docs link would be helpful too: developer.mozilla.org/en-US/docs/Web/API/Window/localStorage\n- @ThorGalle Thanks for the remark. You are correct, I will rephrase the answer to remove the confusion about the local storage.","metadata":{"transformedAt":"2026-08-18T18:33:40.666Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":193,"estimatedTokens":1312}}121{"id":"stack-68160941","source":"stackoverflow","questionId":68160941,"title":"SvelteKit- How to correctly show a loading indicator in a server rendered page on subsequent calls","tags":["javascript","promise","svelte","sveltekit"],"text":"Title: SvelteKit- How to correctly show a loading indicator in a server rendered page on subsequent calls\nTags: javascript, promise, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a page (a dynamic route) where I am fetching data from an API in the load function. What is the correct way to show a loading indicator till the data is fetched. Things I have tried:\n\n- Using await block. I return a promise to fetch function and then in the normal script tag, I export a promise variable. I then resolve this promise manually after manipulating the data.\n\n```\n\n export async function load({ fetch, page }) { \n let collectionId = page.params.id; \n let endpoint = url; \n const promise = fetch(endpoint); \n return {props:{promise}}; \n }\n\n```\n\nthen in normal script tag\n\n```\n\nexport let promise = new Promise(() => '');\n\npromise = new Promise((resolve, reject) => {\n promise.then(function (response) {\n if(response.ok){\n console.log('response');\n response.json().then(function (json) {\n console.log('data in promise');\n console.log(json);\n let posts = json.map((post) => new Post(post));\n posts = posts.sort(function (a, b) {\n return a.id - b.id;\n });\n resolve(posts);\n });\n }else{\n response.text().then((text)=>reject(text));\n }\n });\n});\n\n```\n\nthen in HTML\n\n```\n{#await promise}\n \n{:then posts}\n \n{:catch error}\n \n{/await}\n```\n\nThis works fine the first time, I am guessing, this works when the page is rendered server side. But on subsequent calls, my promise resolution logic doesn't get called and I receive promise directly in my await block, where there is no logic to manipulate it.\n\n- I export a variable to receive final processed data from the load function and in HTML, I try to display the loading indicator till this variable is undefined using {if} block. This works for the first time when the variable is actually undefined, but on subsequent calls, only the value of this variable changes but it is never undefined.\n\n```\nlet posts;\n\n{#if posts===undefined}\nLoading...\n{:else}\n{posts}\n{/if}\n```\n\n========================================\n\nTop Answer:\nOne of the perks of using the `load()` function in a module in this way is that you don't need to use any kind of spinner or await the data, since the function runs before the component is created. The page effectively doesn't load until the data is ready to go. From the docs:\n\n[The load function] allows you to get data for a page without (for\nexample) showing a loading spinner and fetching data in onMount.\n\nSo in your case, just using\n\n```\n\n export let promise;\n\n```\n\nis enough. It shouldn't matter if it's the first time you're hitting that page or not, the data in your promise variable is available without having to use any await or promise logic on it. It's as simple as using `if (promise)` to see if you got the data.\n\n========================================\n\nCode:\n```svelte\n<script context=\"module\">\n export async function load({ fetch, page }) { \n let collectionId = page.params.id; \n let endpoint = url; \n const promise = fetch(endpoint); \n return {props:{promise}}; \n }\n</script>\n```\n\n```svelte\n<script>\nexport let promise = new Promise(() => '');\n\npromise = new Promise((resolve, reject) => {\n promise.then(function (response) {\n if(response.ok){\n console.log('response');\n response.json().then(function (json) {\n console.log('data in promise');\n console.log(json);\n let posts = json.map((post) => new Post(post));\n posts = posts.sort(function (a, b) {\n return a.id - b.id;\n });\n resolve(posts);\n });\n }else{\n response.text().then((text)=>reject(text));\n }\n });\n});\n</script>\n```\n\n```text\n{#await promise}\n <Shimmer items=\"3\" />\n{:then posts}\n <Cards data={posts} />\n{:catch error}\n <Error message={error}/>\n{/await}\n```\n\n```text\nlet posts;\n\n{#if posts===undefined}\nLoading...\n{:else}\n{posts}\n{/if}\n```\n\n```text\nnavigating\n```\n\n```text\nnavigating\n```\n\n```text\n{#if $navigating} Loading... {:else} Content {/if}\n```\n\n```svelte\n<script>\n export let promise;\n</script>\n```\n\n```text\nload()\n```\n\n```text\nif (promise)\n```\n\n```text\n<script lang=\"ts\">\n import { navigating } from '$app/state';\n</script>\n\n{#if navigating.to}\n Loading...\n{/if}\n```\n\n```text\n$app/state\n```\n\n```text\nnavigating\n```\n\n```text\n$navigating\n```\n\n========================================\n\nComments:\n- But say after load function has finished and now you have data in promise variable. Next time you refresh the page, you already have data in the promise variable and if(promise) check won't work.","metadata":{"transformedAt":"2026-08-18T18:33:40.666Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":202,"estimatedTokens":1152}}122{"id":"stack-63226808","source":"stackoverflow","questionId":63226808,"title":"why context is undefined in svelte","tags":["javascript","svelte","svelte-3"],"text":"Title: why context is undefined in svelte\nTags: javascript, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI'm working on a component and i need to use context for it. But i don't know why when i using getContext, It's undefined.\n\nThis is a part of my codes on first component (Index Component):\n\n```\nimport { setContext } from 'svelte';\nimport {onMount} from \"svelte\";\n\nlet tempSuggest;\n\nconst suggestModel = {\n category_id: 1,\n title: \"\",\n images: [{}],\n catalogues: [{}],\n dependent_attributes: [{}],\n independent_attributes: [{}],\n};\n\n$: tempSuggest = Object.assign({}, suggestModel);\n\nonMount(() => {\n setContext(clientProductSuggest, tempSuggest);\n});\n```\n\nIn html codes of first component (loading sub components in the end of index file):\n\n```\n\n```\n\nIn second component:\n\n```\nimport { getContext } from 'svelte';\nconst c = getContext('clientProductSuggest');\n\nconsole.log(c);\n```\n\nAnd now context is undefined.\n\n========================================\n\nTop Answer:\nThis is because *contexts* in Svelte are not reactive by default, when you assign `tempSuggests` to the context it is in fact *undefined*\n\nIn order to get reactivity in your context you should create `tempSuggests` as a store:\n\n```\nimport { setContext } from 'svelte';\nimport { writable } from \"svelte/store\";\n\nlet tempSuggest = writable({});\n\nconst suggestModel = {\n category_id: 1,\n title: \"\",\n images: [{}],\n catalogues: [{}],\n dependent_attributes: [{}],\n independent_attributes: [{}],\n};\n\n$: tempSuggest.update(value => Object.assign(value, suggestModel));\nsetContext('clientProductSuggest', tempSuggest);\n```\n\nAlso consider the following:\n\n- `setContext` does not have to be called inside *onMount*\n\n- the first argument of `setContext` should be a string (I added '')\n\n- `suggestModel` is now a store and should be treated as such in the children\n\n========================================\n\nCode:\n```text\nimport { setContext } from 'svelte';\nimport {onMount} from \"svelte\";\n\nlet tempSuggest;\n\nconst suggestModel = {\n category_id: 1,\n title: \"\",\n images: [{}],\n catalogues: [{}],\n dependent_attributes: [{}],\n independent_attributes: [{}],\n};\n\n$: tempSuggest = Object.assign({}, suggestModel);\n\nonMount(() => {\n setContext(clientProductSuggest, tempSuggest);\n});\n```\n\n```text\n<svelte:component this={component} {...props}/>\n```\n\n```text\nimport { getContext } from 'svelte';\nconst c = getContext('clientProductSuggest');\n\nconsole.log(c);\n```\n\n```text\ngetContext\n```\n\n```text\nsetContext\n```\n\n```js\nimport { setContext } from 'svelte';\nimport { writable } from \"svelte/store\";\n\nlet tempSuggest = writable({});\n\nconst suggestModel = {\n category_id: 1,\n title: \"\",\n images: [{}],\n catalogues: [{}],\n dependent_attributes: [{}],\n independent_attributes: [{}],\n};\n\n$: tempSuggest.update(value => Object.assign(value, suggestModel));\nsetContext('clientProductSuggest', tempSuggest);\n```\n\n```text\ntempSuggests\n```\n\n```text\ntempSuggests\n```\n\n```text\nsetContext\n```\n\n```text\nsetContext\n```\n\n```text\nsuggestModel\n```\n\n```js\nimport { setContext } from 'svelte';\nimport {onMount} from \"svelte\";\n\nlet tempSuggest;\n\nconst suggestModel = {\n category_id: 1,\n title: \"\",\n images: [{}],\n catalogues: [{}],\n dependent_attributes: [{}],\n independent_attributes: [{}],\n};\n\nsetContext(\"clientProductSuggest\", tempSuggest);\n\n$: tempSuggest = Object.assign({}, suggestModel);\n```\n\n```text\nReactive statements run after other script code and before the component markup is rendered\n```\n\n========================================\n\nComments:\n- I have used your code, But why when i log the context in console after setContext, In get method doesn't show to me the suggestModel?\n- I wanna to make my temporary variable empty and looklike as suggestModel, when pages load or when user presses the cancel button, then context needs to be updated.\n- When you say \"log the context after setContext\" is that in the child, immediately after doing getContext ? Because at that point you have not updated the tempSuggest yet","metadata":{"transformedAt":"2026-08-18T18:33:40.666Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":195,"estimatedTokens":1002}}123{"id":"stack-61805696","source":"stackoverflow","questionId":61805696,"title":"How to define a conditional transition in Svelte?","tags":["svelte"],"text":"Title: How to define a conditional transition in Svelte?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nIn Svelte we can add transitions with:\n\n```\n...\n```\n\nIt's also possible to have conditional HTML attributes with:\n\n```\n\n```\n\nThis doesn't work with transitions:\n\n```\n...\n```\n\nWhich throws this error as it expects a config object:\n\n Cannot read property 'delay' of null\n\nSo what would would be the appropriate way of adding a conditional transition in Svelte?\n\nOther than:\n\n```\n{#if animate}\n \n{:else}\n \n{/if}\n```\n\n========================================\n\nTop Answer:\nYou could also solve this with a wrapper around the transition function. Demo here.\n\n```\n\n import { fly, slide } from 'svelte/transition';\n \n export let animate = true;\n \n function maybe(node, options) {\n if (animate) {\n return options.fn(node, options);\n }\n }\n\n### Hello!\n\n```\n\n========================================\n\nCode:\n```text\n<div in:fade={{duration: 150}}>...</div>\n```\n\n```text\n<input disabled={null}>\n```\n\n```text\n<div in:fade={null}>...</div>\n```\n\n```text\n{#if animate}\n <div in:fade></div>\n{:else}\n <div></div>\n{/if}\n```\n\n```html\n<script>\n import { fade } from 'svelte/transition'\n \n export let animate\n</script>\n\n<div in:fade={{ duration: animate ? 500 : 0 }}>\n ...\n</div>\n```\n\n```html\n<!-- Modal.svelte -->\n<div class=\"modal\" transition:fade={{ duration: 500 }}>\n <div class=\"alert\" transition:slide={{ duration: 0 }}>\n Alert!\n </div>\n</div>\n```\n\n```html\n<!-- Transition.svelte -->\n<script lang=\"ts\">\n import { slide } from 'svelte/transition';\n\n export let transition: boolean = true;\n export let duration: number = 500;\n</script>\n\n{#if transition}\n <div transition:slide={{ duration }}>\n <slot />\n </div>\n{:else}\n <slot />\n{/if}\n```\n\n```html\n<!-- Modal.svelte -->\n<div class=\"modal\" transition:fade={{ duration: 500 }}>\n <Transition transition={false}>\n <div class=\"alert\">\n Alert!\n </div>\n </Transition>\n</div>\n```\n\n```text\n<script>\n import { fly, slide } from 'svelte/transition';\n \n export let animate = true;\n \n function maybe(node, options) {\n if (animate) {\n return options.fn(node, options);\n }\n }\n</script>\n\n<h1 in:maybe={{ fn: fly, x: 50 }} out:maybe={{ fn: slide }}>Hello!</h1>\n```\n\n========================================\n\nComments:\n- I ended up doing this but it feels wasteful. I wish there was a way to not add any transition at all. Anyway this is better than using conditionals on the template so I will accept this answer until someone finds a better solution.\n- You're right that it's wasteful. IIRC we have an issue for it somewhere, but I remember it being not quite as straightforward a fix as I imagined. We'll get there one day\n- @RichHarris has that day come already? I stumbled over this question myself and was lead to here.\n- This solution worked wonders. So simple, yet so elegant.","metadata":{"transformedAt":"2026-08-18T18:33:40.666Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":156,"estimatedTokens":717}}124{"id":"stack-67141392","source":"stackoverflow","questionId":67141392,"title":"Access parameter without load function in svelte kit","tags":["svelte","sveltekit"],"text":"Title: Access parameter without load function in svelte kit\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nIn SvelteKit, I want to access page.params without using the SSR load function because I want to have client side rendering only. Is there any way to access page.params without the SSR load function?\n\n========================================\n\nCode:\n```text\nimport { page } from \"$app/stores\";\nconst { slug } = $page.params;\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.666Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":14,"estimatedTokens":112}}125{"id":"stack-71760177","source":"stackoverflow","questionId":71760177,"title":"Styling the body element in svelte","tags":["css","svelte","vite","darkmode"],"text":"Title: Styling the body element in svelte\nTags: css, svelte, vite, darkmode\nSource: Stack Overflow\n\nQuestion:\nMy goal is to make a darkmode for my web app.\nTo get my setup enter `npm init vite` and pick svelte as a framwork. Then the command line instructions. Go to src > App.svelte:\n\nTry the following:\n\n\r\n\r\n\n```\nbody {\n background: black;\n}\n```\n\n\r\n\r\n\r\n\nYou will get the following warning by the svelte extension in vs-code:\n\n```\nUnused CSS selector \"body\"\n```\n\nTo check if this error is related to the browser I manually set the property in chrome dev tools and the expected result was achieved.\n\nBecause of this I have the following questions:\n\n- Why doesn't svelte allow styling of the body in this way?\n\n- How can you style the body tag in svelte?\n\n- How would darkmode be implemented?\n\n========================================\n\nTop Answer:\nYou can achieve what I tried to do by adding a `global.css` file to your project and importing it to your file like this:\n\n\r\n\r\n\n```\n\n import \"./global.css\";\n\n```\n\n\r\n\r\n\r\n\nIf you really want it to be global you can also link it in your index.html in the root of your project like this:\n\n\r\n\r\n\n```\n\n```\n\n========================================\n\nCode:\n```css\nbody {\n background: black;\n}\n```\n\n```text\nUnused CSS selector \"body\"\n```\n\n```text\nnpm init vite\n```\n\n```text\n:global(body)\n```\n\n```text\nbody\n```\n\n```text\n:global(body)\n```\n\n```text\n:global(body.dark-mode)\n```\n\n```html\n<script>\n import \"./global.css\";\n</script>\n```\n\n```html\n<link rel=\"stylesheet\" href=\"styles.css\">\n```\n\n```text\nglobal.css\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.666Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":112,"estimatedTokens":388}}126{"id":"stack-69606222","source":"stackoverflow","questionId":69606222,"title":"How to update the page and query parameters in SvelteKit?","tags":["svelte","sveltekit"],"text":"Title: How to update the page and query parameters in SvelteKit?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a page with a search field. If accessed with a query parameter (e.g. `?word=cat`) the page should load with results present and the search field filled. If a search is done the results and the query parameters (browser history) should update.\n\nThe only way I found to update query parameters is `goto`, so my attempt is:\n\n```\n\n export async function load({ page, fetch }) {\n const response = await fetch(`/data.json?${page.query.toString()}`)\n if (response.ok) {\n return {\n props: {\n word: page.query.get('word'),\n body: await response.json()\n }\n }\n }\n }\n\n import { goto } from '$app/navigation'\n import { page } from '$app/stores'\n\n export let word\n export let body\n\n function search() {\n $page.query.set('word', word)\n goto(`?${$page.query.toString()}`)\n }\n\n \n \n \n \n\n```\n\nThis works but sometimes gets stuck just updating the query parameters and nothing else. For some reason `load` isn't being called in those cases. I can get it to work reliably by adding `await invalidate` for the URL before the `goto`, but now `load` is always called twice and the search field flips back to the old value shortly.\n\nI just started with Svelte/SvelteKit, so my approach is probably just wrong. Thanks for any help.\n\n========================================\n\nTop Answer:\n`$page.query` is no longer available since it was replaced by `$page.url` (in @sveltejs/kit@1.0.0-next.208).\n\nNow, it is done like this:\n\n```\n$page.url.searchParams.set('word',word); \ngoto(`?${$page.url.searchParams.toString()}`);\n```\n\n`$page` and `goto()` you can get from:\n\n```\nimport { goto } from \"$app/navigation\";\nimport { page } from \"$app/stores\";\n```\n\n========================================\n\nCode:\n```html\n<script context=\"module\">\n export async function load({ page, fetch }) {\n const response = await fetch(`/data.json?${page.query.toString()}`)\n if (response.ok) {\n return {\n props: {\n word: page.query.get('word'),\n body: await response.json()\n }\n }\n }\n }\n</script>\n\n<script>\n import { goto } from '$app/navigation'\n import { page } from '$app/stores'\n\n export let word\n export let body\n\n function search() {\n $page.query.set('word', word)\n goto(`?${$page.query.toString()}`)\n }\n</script>\n\n<main>\n <form on:submit|preventDefault={search}>\n <input bind:value={word}>\n </form>\n <!-- ... -->\n</main>\n```\n\n```text\n?word=cat\n```\n\n```text\ngoto\n```\n\n```text\nload\n```\n\n```text\nawait invalidate\n```\n\n```text\ngoto\n```\n\n```text\nload\n```\n\n```js\nlet query = new URLSearchParams($page.url.searchParams.toString());\n \nquery.set('word', word);\n \ngoto(`?${query.toString()}`);\n```\n\n```text\nload\n```\n\n```text\nURLSearchParams\n```\n\n```js\n$page.query.set('word',word); \ngoto(`?${$page.query.toString()}`);\n```\n\n```js\n$page.url.searchParams.set('word',word); \ngoto(`?${$page.url.searchParams.toString()}`);\n```\n\n```js\nimport { goto } from \"$app/navigation\";\nimport { page } from \"$app/stores\";\n```\n\n```text\n$page.query\n```\n\n```text\n$page.url\n```\n\n```text\n$page\n```\n\n```text\ngoto()\n```\n\n```js\nconst newUrl = new URL($page.url);\nnewUrl?.searchParams?.set('hello', 'world');\ngoto(newUrl);\n```\n\n```js\nimport { page } from \"$app/stores\";\n\n$page.query.set('word', word); \nhistory.replaceState(history.state, '', $page.url);\n```\n\n```js\nimport { page } from \"$app/stores\";\nimport { replaceState } from \"$app/navigation\";\n\n$page.url.searchParams.set('word', word); \nreplaceState($page.url, $page.state);\n```\n\n```text\n$page.query\n```\n\n```text\n$page.url.searchParams\n```\n\n```text\nreplaceState\n```\n\n```html\n<script lang=\"ts\">\n import { page } from \"$app/stores\";\n // Reactive statement to log a specific query parameter\n $: console.log($page.url.searchParams.get('tag'));\n</script>\n```\n\n```text\ngoto()\n```\n\n```text\nhttp://localhost:5173?tag=travel\n```\n\n```js\nfunction rerun() {\n $page.url.searchParams.set('player2', 'Jabami')\n fetch($page.url)\n}\n```\n\n```html\n<form action=\"/game\">\n <label>\n Search\n <input name=\"q\">\n </label>\n</form>\n```\n\n```text\nGET\n```\n\n```text\nsearchParams\n```\n\n```text\nmethod='POST'\n```\n\n```text\nGET\n```\n\n```js\nimport { pushState, replaceState } from '$app/navigation';\n\n$effect(() => {\n tick().then(() => {\n pushState(`?id=123`, $page.state);\n });\n})\n```\n\n```js\n// Only run on the client\n $effect(() => {\n // To set the input from the URL if exists\n if (page.url.searchParams.get(\"character\")) {\n store.input = page.url.searchParams.get(\"character\") || \"\";\n }\n \n // To update the URL when the input changes\n $effect(() => {\n store.input;\n tick().then(() => {\n page.url.searchParams.set(\"character\", store.input);\n replaceState(page.url, page.state);\n });\n });\n });\n```\n\n========================================\n\nComments:\n- try removing the `$page.query.set` line and simple have `goto` that should be enough\n- Thanks, I replaced it with a separate `URLSearchParams` and it works.\n- You don't actually have a create a new URLSearchParams object passing the page.query. the `$page.url.searchParams;` already returns a urlSearchParams object so you can just assign that to a variable: `const urlSearchParams = $page.url.searchParams;`\n- @Nicholas Mordecai I respectfully disagree. See Anatole Lucet's comment.\n- github.com/sveltejs/kit/issues/2785\n- Actually, this will mutate `page`'s internal `URLSearchParams` which might cause some issues when working with reactive statements. A better way would be to create and mutate a new `URLSearchParams` from `$page.url.searchParams`, and then use it in the `goto` (`goto(newSearchParams)`).","metadata":{"transformedAt":"2026-08-18T18:33:40.666Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":293,"estimatedTokens":1426}}127{"id":"stack-67852559","source":"stackoverflow","questionId":67852559,"title":"Pass Svelte Component as Props","tags":["reactjs","properties","svelte"],"text":"Title: Pass Svelte Component as Props\nTags: reactjs, properties, svelte\nSource: Stack Overflow\n\nQuestion:\nI am pretty new to the `svelte` environment,\nI have some react code and try to convert them as svelte for the learning purpose.\n\nIn the react, we can pass a string or React Node as props.\n\n```\n}\nkey=\"1\"\n>\n {/** some code **/} \n\n```\n\nI am trying to use the same code in svelte, but it throws an error.\nhttps://i.sstatic.net/sF0yp.png\n\n========================================\n\nTop Answer:\nIn many cases you'll want to use slots as Tan Li Hau suggested. However, it is possible to pass components as props. For this, we are going to make use of ``. It's quite restrictive, but it's a possibility.\n\nhttps://svelte.dev/docs#svelte_component\n\n### ``\n\nNormally, you'd use `` like this:\n\n```\n\n import Component from './component.svelte'\n\n```\n\nThe above is equivalent to this:\n\n```\n\n import Component from './component.svelte'\n\n```\n\n### Passing down components through props\n\nThis means we can actually pass down components through props.\n\n```\n\n import ComponentA from './component-a.svelte'\n import ComponentB from './component-b.svelte'\n\n```\n\nAnd render the component…\n\n```\n\n export let foo\n\n```\n\n### Caveats\n\nNote there are a few things you can't do:\n\n- Set props on the component passed down through props\n\n- Pass down components which children through props\n\n- Or do pretty much anything else with the component passed down as a prop\n\nSvelte may not even be designed to do this (even though it works). So yeah, unless you really need this, use slots. But now you know this is possible.\n\n========================================\n\nCode:\n```text\n<TabPane\nname=\"profile\"\ntitle={<img src=\"images/profile.svg\" alt=\"Profile\" />}\nkey=\"1\"\n>\n {/** some code **/} \n</TabPane>\n```\n\n```text\nsvelte\n```\n\n```html\n<TabPane\n name=\"profile\"\n key=\"1\"\n>\n <img slot=\"title\" src=\"images/profile.svg\" alt=\"Profile\" />\n <!-- some code, eg: -->\n <div>Some code here</div>\n</TabPane>\n```\n\n```html\n<!-- filename: TabPane.svelte -->\n\n<h1>\n <slot name=\"title\" />\n</h1>\n\n<slot />\n```\n\n```text\nfunction TabPane({ title, children }) {\n return (\n <>\n <h1>{title}</h1>\n {children}\n </>\n );\n}\n```\n\n```html\n<TabPane\n name=\"profile\"\n key=\"1\"\n>\n <svelte:fragment slot=\"title\">\n string title here\n <svelte:fragment>\n <!-- some code, eg: -->\n <div>Some code here</div>\n</TabPane>\n```\n\n```text\n<slot>\n```\n\n```text\nslot=\"title\"\n```\n\n```text\n<slot name=\"title\">\n```\n\n```text\n<slot />\n```\n\n```text\n<svelte:fragment>\n```\n\n```text\nslot=\"title\"\n```\n\n```text\n<script>\n import Component from './component.svelte'\n</script>\n\n<svelte:component this={Component} foo={bar} />\n```\n\n```text\n<script>\n import Component from './component.svelte'\n</script>\n\n<Component foo={bar} />\n```\n\n```text\n<!-- app.svelte -->\n\n<script>\n import ComponentA from './component-a.svelte'\n import ComponentB from './component-b.svelte'\n</script>\n\n<ComponentA foo={ComponentB} />\n```\n\n```text\n<!-- component-a.svelte -->\n\n<script>\n export let foo\n</script>\n\n<svelte:component this={foo} />\n```\n\n```text\n<svelte:component>\n```\n\n```text\n<svelte:component>\n```\n\n```text\n<svelte:component>\n```\n\n```html\n<Modal>\n {#snippet title(isOpen)}\n <Component text=\"Hello, world!\" />\n <span>isOpen: {isOpen}</span>\n {/snippet}\n <span>Everything outside of a snippet becomes children of the component (like a default snippet).</span>\n</Modal>\n```\n\n```html\n<script>\n let { children, title } = $props();\n</script>\n\n<div class=\"modal\">\n <div class=\"header\">\n {@render title?.(true)}\n </div>\n <div class=\"body\">\n {@render children?.()}\n </div>\n</div>\n```\n\n```text\nchildren?.()\n```\n\n========================================\n\nComments:\n- Is `` is allow only the string?\n- If you're familiar with React's fragments (i.e., `<> `), you can use `` the same way. Anything can go inside of it.\n- For anyone coming across this: you don’t need to use svelte:fragment for the string. Just use export let variables or the forthcoming props$ rune. You only need slots when you are passing HTML or components into a component. You use svelte:fragment if you want the contents of your slot to show up without other surrounding elements like s, just like react, which is useful sometimes. Happy coding!","metadata":{"transformedAt":"2026-08-18T18:33:40.666Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":247,"estimatedTokens":1072}}128{"id":"stack-57257499","source":"stackoverflow","questionId":57257499,"title":"How to focus on newly added inputs in Svelte?","tags":["javascript","svelte"],"text":"Title: How to focus on newly added inputs in Svelte?\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI use #each to display an input for every member of the `tasks` array. When I click the Add task button, a new element is inserted into the array, so a new input appears in the #each loop.\n\nHow do I focus the input that's been added upon clicking the Add task button?\n\n```\n\n let tasks = [];\n\n function addTask() {\n tasks = [...tasks, { title: \"\" }];\n }\n\n{#each tasks as task}\n \n{/each}\n\nAdd task\n```\n\n========================================\n\nTop Answer:\nYou can use the `autofocus` attribute:\n\n```\n\n let tasks = [];\n\n function addTask() {\n tasks = [...tasks, { title: \"\" }];\n }\n\n{#each tasks as task}\n \n{/each}\n\nAdd task\n```\n\nNote that you'll get an accessibility warning. That's because accessibility guidelines actually recommend that you don't do this:\n\n People who are blind or who have low vision may be disoriented when focus is moved without their permission. Additionally, autofocus can be problematic for people with motor control disabilities, as it may create extra work for them to navigate out from the autofocused area and to other locationso on the page/view.\n\nIt's up to you to determine whether this advice is relevant in your situation!\n\n========================================\n\nCode:\n```text\n<script>\n let tasks = [];\n\n function addTask() {\n tasks = [...tasks, { title: \"\" }];\n }\n</script>\n\n{#each tasks as task}\n <input type=\"text\" bind:value={task.title} />\n{/each}\n\n<button on:click={addTask}>Add task</button>\n```\n\n```text\ntasks\n```\n\n```text\n<script>\n let tasks = [];\n\n function addTask() {\n tasks = [...tasks, { title: \"\" }];\n }\n \n function init(el){\n el.focus()\n }\n</script>\n\n{#each tasks as task}\n <input type=\"text\" bind:value={task.title} use:init />\n{/each}\n\n<button on:click={addTask}>Add task</button>\n```\n\n```text\nuse:action\n```\n\n```html\n<script>\n let tasks = [];\n\n function addTask() {\n tasks = [...tasks, { title: \"\" }];\n }\n</script>\n\n{#each tasks as task}\n <input type=\"text\" bind:value={task.title} autofocus />\n{/each}\n\n<button on:click={addTask}>Add task</button>\n```\n\n```text\nautofocus\n```\n\n```html\n<script>\n import { tick } from 'svelte';\n\n let tasks = [];\n\n async function addTask() {\n let newTask = { title: \"\" };\n tasks = [...tasks, newTask];\n\n await tick();\n newTask.input.focus();\n }\n</script>\n\n{#each tasks as task}\n <input type=\"text\" bind:value={task.title} bind:this={task.input} />\n{/each}\n\n<button on:click={addTask}>Add task</button>\n```\n\n```text\nbind:this\n```\n\n```text\ntick\n```\n\n```text\ntasks\n```\n\n```text\nautofocus\n```\n\n```text\nuse:action\n```\n\n========================================\n\nComments:\n- @AntonZotov Not surprisingly Rich Harris has a nicer solution\n- Yours is nice too. I used it because I had some problems using autofocus. I did not investigate it, but it's maybe related to this chrome bug: autofocus does not work when URL contains fragment in Chrome 79: bugs.chromium.org/p/chromium/issues/detail?id=1046357\n- `autofocus` is not recommended these days; the Svelte language tools discourage it. Using the attribute is definitely a more elegant solution, but this is warning-free!\n- As best I can tell, this solution is no better for a11y than the Rich Harris solution. It simply circumvents the Svelte warning. It's fooling Svelte; but it shouldn't fool us!\n- This is a great solution, because it's very flexible\n- \"autofocus\" is not recommended... but neither is this. you are NOT supposed to set focus, you are supposed to, I don't know, just have a crappy app I guess. ;) I've seen too many apps that leave the focus *nowhere* which I'm not sure is significantly better for screen readers. For modal dialogs I just recommend \"navigating\" to a new \"page\" as the modal, using html5 state, but for this you're just going to have to be, well, bad.\n- Neither of the proposed answers work in my situation; I'll explain: I have a form with 2 inputs, and after submitting the form, I'd like to have the cursor back in the first input. Any suggestions how that should be done? Thanks!\n- Use `` to get a reference to the input you want to focus, then call `myInput.focus()` once the form is submitted\n- thank you, this is a good solution! However, I desire more: not only after submission, but also before. N.B. the solution is to use autofocus!\n- Would you still consider it as an accessibility issue, if autofocus happen on the stage of page loading? For example: the user click on \"Login\" link that direct him to login page, the login page is loaded, and automatically the \"Username\" input field takes the focus. Does it make a difference when you're in single app application mode?\n- Whether you use auto focus or just focus manually probably doesn't matter in terms of accessebility?\n- Tick is what I needed for my app as the element was previous hidden behind an `{#if}` so it didn't exist yet.\n- Where does `input` come from? Not a property on `task`.\n- @Dennis The `task.input` property is set by the `bind:this={task.input}` directive on each input element in the loop","metadata":{"transformedAt":"2026-08-18T18:33:40.666Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":176,"estimatedTokens":1275}}129{"id":"stack-66637632","source":"stackoverflow","questionId":66637632,"title":"Access URL query string in svelte","tags":["svelte","query-string"],"text":"Title: Access URL query string in svelte\nTags: svelte, query-string\nSource: Stack Overflow\n\nQuestion:\nHow should I access the the query string parameters from svelte? I'd like my script to behave differently when \"?beta\" has been appended to the URL.\n\nMy intuitive approach would be to use the standard `URLSearchParams` in a svelte `#if` block.\n\n========================================\n\nTop Answer:\nHere's how you do it with in SvelteKit 5:\n\n```\nimport { page } from '$app/state'\nconst email = page.url.searchParams.get('email')\n```\n\n========================================\n\nCode:\n```text\nURLSearchParams\n```\n\n```text\n#if\n```\n\n```html\n<script>\n const urlParams = new URLSearchParams(window.location.search);\n const isBeta = urlParams.has('beta');\n</script>\n\n{#if isBeta}\n <p>This is beta!</p>\n{:else}\n <p>This is not beta.</p>\n{/if}\n```\n\n```html\n<script>\n import { page } from '$app/stores';\n \n const isBeta = $page.url.searchParams.has('beta');\n</script>\n```\n\n```text\n$page.query\n```\n\n```text\n$page.url\n```\n\n```text\n<script>\n import { page } from '$app/stores';\n let isBeta = page.query.beta;\n</script>\n\n\n{#if isBeta}\n <p>This is beta!</p>\n{:else}\n <p>This is not beta.</p>\n{/if}\n```\n\n```text\npage\n```\n\n```text\npage.query\n```\n\n```js\nimport { page } from '$app/state'\nconst email = page.url.searchParams.get('email')\n```\n\n```text\n<script> \n import { page } from '$app/stores'\n let urlPrams = $page.query.get('beta')\n const isBeta = false\n if (urlPrams && urlPrams.length > 0) {\n const isBeta = true\n }\n \n</script>\n\n{#if isBeta}\n <p>This is beta!</p>\n{:else}\n <p>This is not beta.</p>\n{/if}\n```\n\n```text\nwindow\n```\n\n```html\n<script>\n import { page } from '$app/stores';\n const BETA = $page.url.searchParams.get('beta');\n</script>\n```\n\n```text\n<script>\nimport { page } from '$app/stores';\nconst beta = $page.url.searchParams.get('beta');\n</script>\n\n{#if typeof beta === 'string'}\nBeta is on!\n{:else}\nNo beta :(\n{/if}\n```\n\n```text\n?beta=1\n```\n\n```text\nimport { page } from '$app/state'\n```\n\n```text\n<script>\n import { page } from '$app/state'\n const isBeta = page.url.searchParams.has('beta')\n</script>\n\n{#if isBeta}\n<!-- do something wonderful here -->\n{/if}\n```\n\n```text\n$page\n```\n\n```text\n$\n```\n\n========================================\n\nComments:\n- `$page.url.searchParams.get('xxx')` to get a url query param.\n- `Cannot read properties of undefined (reading 'searchParams')` when i use it\n- `page` is no longer a store. It's now available as `import { page } from '$app/state'` and can be used as: `const isBeta = page.url.searchParams.has('beta')`. Note page has no preceding dollar-sign.\n- This answer is outdated. See below.\n- You need the page.query.get(\"beta\") for it to work\n- this is deprecated\n- `$page.query` has been replaced by `$page.url.searchParams`\n- how do you use this?\n- `import {page} from '$app/stores'; const id = $page.url.searchParams.get('id');`\n- `Cannot read properties of undefined (reading 'searchParams')`\n- @lefrost can you provide a link to this in the docs? I can't seem to find any reference to searchParams or the URL type that is attached to $page.\n- @thomallen I can't find it in the docs either... but Geoff Rich's answer cites the this PR, which `replaces (among other things) [query] with the url object`.\n- The official SvelteKit docs for URL APIs is available here and agrees with this answer: kit.svelte.dev/docs/web-standards#url-apis `const foo = url.searchParams.get('foo');`","metadata":{"transformedAt":"2026-08-18T18:33:40.667Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":171,"estimatedTokens":873}}130{"id":"stack-71379031","source":"stackoverflow","questionId":71379031,"title":"How do get query string parameter in sveltekit?","tags":["svelte","svelte-3","sveltekit"],"text":"Title: How do get query string parameter in sveltekit?\nTags: svelte, svelte-3, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm trying to the `/login?ref=/some/path` parameter to redirect to after login:\n\n```\nconst ref = $page.url.searchParams.get('ref') || '/dashboard';\n```\n\nHowever I get this error:\n\n`TypeError: Cannot read properties of undefined (reading 'searchParams')`\n\n========================================\n\nTop Answer:\nYou can get the query string parameters from the `url` property of the object passed to the `load` function of a page:\n\n```\n\n export function load({ url }) {\n const ref = url.searchParams.get('ref') || '/dashboard';\n return {\n props: {\n ref\n }\n };\n }\n\n export let ref;\n\n // do stuff\n\n```\n\nMore info on the `load` function, its input format and its reactivity here (SvelteKit docs).\n\n========================================\n\nCode:\n```js\nconst ref = $page.url.searchParams.get('ref') || '/dashboard';\n```\n\n```text\n/login?ref=/some/path\n```\n\n```text\nTypeError: Cannot read properties of undefined (reading 'searchParams')\n```\n\n```js\nexport async function load({ params, url }) {\n let lang = url.searchParams.get('lang');\n let q = url.searchParams.get('q');\n return { lang, q };\n}\n```\n\n```js\nimport { page } from '$app/stores';\n$page.data.q\n```\n\n```text\nexport var lang\n```\n\n```js\n<script context=\"module\">\n export function load({ url }) {\n const ref = url.searchParams.get('ref') || '/dashboard';\n return {\n props: {\n ref\n }\n };\n }\n</script>\n<script>\n export let ref;\n\n // do stuff\n</script>\n```\n\n```text\nurl\n```\n\n```text\nload\n```\n\n```text\nload\n```\n\n```js\nimport { page } from '$app/stores'\n\n$page.url.searchParams.get('ref')\n```\n\n```js\n// /login/+page.server.ts\n\nexport const load = async ({ url }) => {\n return {\n ref: url.searchParams.get('ref')\n }\n}\n```\n\n```html\n<!-- /login/+page.svelte -->\n\n<script lang=\"ts\">\n import type { PageData } from \"./$types\";\n\n export let data: PageData;\n // data is type safe and will autocomplete `data.ref`\n</script>\n\n...\n```\n\n```text\nv1\n```\n\n```text\n<script lang=\"ts\">\n import { page } from '$app/state';\n\n const ref = page.url.searchParams.get('ref');\n</script>\n```\n\n```text\n$app/state\n```\n\n```text\n$app/stores\n```\n\n========================================\n\nComments:\n- I tested you code, and works perfect. Which version of SveteKit are you running?\n- 3.x is what I have\n- That is the svelte version, what is your SvelteKit version? Update to the latest verserion (1.0.0-next.294)\n- \"@sveltejs/kit\": \"1.0.0-next.294\",\n- For reference: sveltekit example: learn.svelte.dev/tutorial/page-store\n- Is there a way to get it from `$page`?\n- Yes you can, in similar fashion, see the code in the `Header` component in this Stackblitz example I quickly put together. Which, incidentally, is the way you're attempting to do it in your own code, so you might want to check that your SvelteKit version is up-to-date.\n- Yeah that’s what I thought. I have svelte 3.x\n- It's the SvelteKit version that matters here. Kit is where the routing, etc. is handled.\n- ` \"@sveltejs/kit\": \"next\",`\n- @ThomasHennes This answer is \"unfortunately\" outdated since all the changes to the sveltekit framework on the `v1` migration have been made. See stackoverflow.com/a/78261994/8583669.\n- @johannchopin Thank you. You are correct and I am well-aware this answer is outdated. However I have kept it as is because: - Bitdom8 already provided an updated, SvelteKit 1.0+ answer in September of 2022 - some users might still be using pre-1.0 versions of SvelteKit, in which case this answer might still prove valuable\n- Why do you destructure params? You are not using it. Plus, `$page.data` is used in a page **that need to access data from a child page or layout**: kit.svelte.dev/docs/load#using-url-data kit.svelte.dev/docs/load#$page-data\n- Actually, we are using it. That's why included. Good that it's reachable from server side\n- @Big_Boulard you can also do it like this `$page.url.searchParams.get(\"q\")` now with latest sveltekit without need `load({ params, url })`\n- @Bitdom8 your are *not* using `params` in your function, only `url`.\n- Upvoted as this is the correct way to access query strings as of SvelteKit versions 1.0 and above. This is more accurate and more complete (e.g. filenames) than the accepted answer. Also, the suggestion in the accepted answer to use the `page` import from `$app/stores` should only be used for components, not for actual routes.","metadata":{"transformedAt":"2026-08-18T18:33:40.667Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":170,"estimatedTokens":1117}}131{"id":"stack-56983938","source":"stackoverflow","questionId":56983938,"title":"How to `console.log('yes')` when a variable changed?","tags":["javascript","svelte"],"text":"Title: How to `console.log('yes')` when a variable changed?\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\n```\nlet c = 0;\n$: console.log(c);\n```\n\nIf we want to print the value of `c` when it is changed, we can write like above.\n\nBecause `c` is used in `$` directive literally, so this statement can be reactive to `c`.\n\nBut what if I just want to `console.log('yes')` when `c` is changed?\n\n```\nlet c = 0;\n$: console.log('yes');\n```\n\nObviously, the statement `console.log('yes')` is not reactive to `c`.\n\nFurthermore, if I still `console.log(c)` but put it into a function:\n\n```\nlet c = 0;\nfunction log() {\n console.log(c);\n}\n$: log();\n```\n\n`log()` is also not reactive to `c`.\n\nSo, what can I do if the reactive code doesn't literally contain the variable which I want to reactive to?\n\n========================================\n\nTop Answer:\nI have recently been playing with svelte and needed to call a function when a property changed.\n\nIn Vue you would do it with `watch`, but I could not find an equivilent in Svelte.\n\n In my project have done it like this: \n\n```\nlet c = 0;\n$: if (c) {\n console.log(\"yes\");\n}\n```\n\nI am not 100% sure if this is the correct way or not though.\n\nHopefully Rich Harris will chime in here as I would like to know.\n\n========================================\n\nCode:\n```text\nlet c = 0;\n$: console.log(c);\n```\n\n```text\nlet c = 0;\n$: console.log('yes');\n```\n\n```text\nlet c = 0;\nfunction log() {\n console.log(c);\n}\n$: log();\n```\n\n```text\nc\n```\n\n```text\nc\n```\n\n```text\n$\n```\n\n```text\nc\n```\n\n```text\nconsole.log('yes')\n```\n\n```text\nc\n```\n\n```text\nconsole.log('yes')\n```\n\n```text\nc\n```\n\n```text\nconsole.log(c)\n```\n\n```text\nlog()\n```\n\n```text\nc\n```\n\n```text\n$: c, console.log('yes');\n```\n\n```text\nlet c = 0;\n$: if (c >= 0) {\n console.log(\"yes\");\n}\n```\n\n```text\nlet c = 0;\n$: if (c) {\n console.log(\"yes\");\n}\n```\n\n```text\nwatch\n```\n\n```text\nlet c\n$: if (condition) console.log(c)\n```\n\n```text\nlet c = 0;\n\nsetInterval(() => c++; , 5000);\n$: console.log(c);\n```\n\n```js\n$effect(() => (c, console.log(\"yes\")))\n```\n\n```js\n$inspect(c).with(() => console.log(\"yes\"));\n```\n\n========================================\n\nComments:\n- A very good read on Svelte Reactivity with examples and explanations sveltesociety.dev/recipes/svelte-language-fundamentals/…\n- change `c` from 1 to 0 will not do log...but it's another thread about the false value in javascript.\n- your intention is to write `c` literally in $ statement, although it looks strange. It's a workaround, we can also write `console.log('yes' || c)` or `c; console.log('yes');`, but they are all ugly...\n- I updated my answer to include `0`. This if statement can be adjusted to include negative values as well should you need that.\n- `c; console.log('yes')` doesn't look so ugly to me\n- I've @Rich_Harris in Twitter, if he responses, I'll sync here.\n- You may use shorter syntax like `$: c ? console.log(yes):null;`\n- One gotcha with this approach is if you want that code to run on every change, including a change from non-zero to zero. The `$: if()` approach won't run when the value becomes 0 (or any other falsy value).\n- Thanks for coming back with the answer, staring this for future reference. I really wish this was outlined in the svelte docs.\n- Wow, this is quite the golden nugget of info. I would not have guessed to use a comma-separated statement after `$:`, which is new to me anyway. Is this a valid/better way to operate than having to put `boo.far = boo.far` whenever you think it might make a difference, in terms of updating a state (cos sometimes for some reason I don't, while other times I do - it's still a bit of a mystery)?\n- One big problem with this is that it doesn't expose the previous value, so this will trigger on page instantiation as well as user triggered update.\n- The OP specifically says \"what can I do if the reactive code doesn't literally contain the variable\", meaning doesn't contain `c`.","metadata":{"transformedAt":"2026-08-18T18:33:40.667Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":179,"estimatedTokens":982}}132{"id":"stack-46086483","source":"stackoverflow","questionId":46086483,"title":"How to apply styles to slot element in Svelte?","tags":["svelte"],"text":"Title: How to apply styles to slot element in Svelte?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI'd like styles declared in one module to be applied to the slot elements of that module (which get filled in in another file).\n\nHere's a Svelte REPL of the following example:\n\n*App.html*\n\n```\n\n {{#each items as item}}\n \n- {{item}}\n {{/each}}\n\n import List from './List.html'\n\n export default {\n components: {\n List\n }\n }\n\n```\n\n*List.html*:\n\n```\n\n### A Special List\n\n \n- Let's all be red!\n \n\n ul a {\n color: red;\n }\n\n```\n\n*Data*:\n\n```\n{\n \"items\": [\"Nope\", \"I'm good\"]\n}\n```\n\nThe red coloring doesn't apply to the `a` tag elements that were added through slot.\nhttps://i.sstatic.net/YtRxl.png\n\nI'm very new to Svelte, but I read through as much as I could find online, and couldn't seem to find a solution. Any help would be appreciated, thank you.\n\n========================================\n\nTop Answer:\nFor those who need to style the slot container only if it exists\n\nCreate button component\n\n```\n\n {#if $$slots['start-icon']}\n \n \n \n {/if}\n\n \n\n```\n\nUsage\n\n```\n\n \n\n Button name\n\n```\n\nSee Component composition / Checking for slot content\n\n========================================\n\nCode:\n```text\n<List>\n {{#each items as item}}\n <li><a>{{item}}</a></li>\n {{/each}}\n</List>\n\n<script>\n import List from './List.html'\n\n export default {\n components: {\n List\n }\n }\n</script>\n```\n\n```text\n<h1>A Special List</h1>\n<ul>\n <li><a>Let's all be red!</a></li>\n <slot></slot>\n</ul>\n\n<style>\n ul a {\n color: red;\n }\n</style>\n```\n\n```text\n{\n \"items\": [\"Nope\", \"I'm good\"]\n}\n```\n\n```text\na\n```\n\n```html\n<style>\n ul :global(a) {\n color: red;\n }\n</style>\n```\n\n```text\n:global(...)\n```\n\n```text\na\n```\n\n```text\nul\n```\n\n```text\n<button>\n {#if $$slots['start-icon']}\n <div class=\"m-4\">\n <slot name=\"start-icon\" />\n </div>\n {/if}\n\n <slot></slot>\n</button>\n```\n\n```text\n<button>\n <Icon slot='start-icon' />\n\n Button name\n</button>\n```\n\n========================================\n\nComments:\n- Thanks so much. Is this documented anywhere? I couldn't seem to find anything. Edit: I see it's mentioned in svelte's README under the cascade option.\n- Yeah, we need to do a better job of covering this in the docs themselves. I'll raise an issue for it\n- How to use child selector `>` inside `:global()`?\n- Great answer. This functionality wasn't obvious to me (hence why I'm here), and though it's documented in svelte.dev/docs#style , I missed it because I was relying on svelte/tutorial instead.\n- Is this guaranteed to be scoped to only `a`s of `ul`s within the slotted component? Or it targets `a`s of ALL `ul`s everywhere in the document? (Assuming it's used within a slotted component.) **P.S.: I've got my answer from another forum, I'll add it here for future readers:** \"*This targets all `a`'s underneath that `ul`, since only the `a` is globally scoped it will leak into child components but not parent because the `ul` specifier is scoped.*\" So yeah, it's safe to use.","metadata":{"transformedAt":"2026-08-18T18:33:40.667Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":181,"estimatedTokens":760}}133{"id":"stack-57174373","source":"stackoverflow","questionId":57174373,"title":"Can I set svelte style css attribute values using variables passed in to a component","tags":["syntax","svelte"],"text":"Title: Can I set svelte style css attribute values using variables passed in to a component\nTags: syntax, svelte\nSource: Stack Overflow\n\nQuestion:\nI want to create a svelte component that receives the name and path of an image. I want to have the component set the image as the \"background-image\" using CSS.\n\nI've tried the following which does not seem to work...\n\nComponent called in ***App.svelte***:\n\n```\n\n```\n\n***Image.Svelte***\n\n```\n\nexport let image_url;\n\n.image{\n position:relative;\n opacity: 0.70;\n background-position:bottom;\n background-size: cover;\n background-repeat: no-repeat;\n background-attachment: fixed;\n background-image: url({image_url});\n min-height: 100%;\n}\n\n some text\n\n```\n\nWhen I inspect the component the css for background_image is:\n\n```\nbackground-image: url({image_url});\n```\n\nIs it possible to have the variable converted in the CSS?\n\n========================================\n\nTop Answer:\nYou can now pass css variables directly as props: https://svelte.dev/docs#template-syntax-component-directives---style-props\n\n```\n\n```\n\nIn `Image.svelte`\n\n```\nbackground-image: var(--background-image, url(./images/default.jpg));\n```\n\n========================================\n\nCode:\n```text\n<Image image_url='./images/image1.jpg' />\n```\n\n```text\n<script>\nexport let image_url;\n</script>\n\n<style>\n.image{\n position:relative;\n opacity: 0.70;\n background-position:bottom;\n background-size: cover;\n background-repeat: no-repeat;\n background-attachment: fixed;\n background-image: url({image_url});\n min-height: 100%;\n}\n</style>\n\n<div class=\"image\">\n <p>some text</p>\n</div>\n```\n\n```text\nbackground-image: url({image_url});\n```\n\n```html\n<script>\nexport let image_url;\n</script>\n\n<style>\n.image{\n position:relative;\n opacity: 0.70;\n background-position:bottom;\n background-size: cover;\n background-repeat: no-repeat;\n background-attachment: fixed;\n /* background-image: url({image_url}); */\n min-height: 100%;\n}\n</style>\n\n<!-- <div class=\"image\"> -->\n<div class=\"image\" style=\"background-image: url({image_url});\">\n <p>some text</p>\n</div>\n```\n\n```html\n<script>\nexport let image_url;\n</script>\n\n<style>\n.image{\n position:relative;\n opacity: 0.70;\n background-position:bottom;\n background-size: cover;\n background-repeat: no-repeat;\n background-attachment: fixed;\n /* background-image: url({image_url}); */\n background-image: var(--image);\n min-height: 100%;\n}\n</style>\n\n<!-- <div class=\"image\"> -->\n<div class=\"image\" style=\"--image: url({image_url});\">\n <p>some text</p>\n</div>\n```\n\n```text\n<style>\n```\n\n```text\n<style>\n```\n\n```html\n<script>\nexport let image_url;\n</script>\n\n<style lang=\"scss\">\n@import \"my/path/to/variables\";\n\n.image{\n position:relative;\n opacity: 0.70;\n background-position:bottom;\n background-size: cover;\n background-repeat: no-repeat;\n background-attachment: fixed;\n background-image: url(#{$image_url});\n min-height: 100%;\n}\n</style>\n\n<div class=\"image\">\n <p>some text</p>\n</div>\n```\n\n```html\n<Image --background-image='url(./images/image1.jpg)' />\n```\n\n```css\nbackground-image: var(--background-image, url(./images/default.jpg));\n```\n\n```text\nImage.svelte\n```\n\n```text\n<script>\n export let image_url;\n</script>\n\n<div class=\"image\" style=\"--image_url: url({image_url})\">\n <p>some text</p>\n</div>\n\n<style>\n .image{\n background-image: var(--image-url);\n }\n</style>\n```\n\n========================================\n\nComments:\n- I guess the answers here are out of date. See svelte.dev/tutorial/style-directive .\n- Link is out of date for the style directive. See the docs and an example with pixel length.\n- ...or 3. use \"framework-agnostic css-in-js solution\" as core team suggests. it's kind more flexible since inline styles does not handle media queries, pseudoclasses and pseudoelements.\n- btw I'm the creator of Svelte, I wrote that article ;) CSS-in-JS has its uses but I wouldn't generally recommend using it to solve this particular problem, it's probably overkill\n- @RichHarris, if this is *overkill*, then what is the alternative? I want to delegate these changes to the component where the parent can deliver a 'context' to customize in the child component's css styling, the alternatives break the clean separations\n- I like the css variables approach better\n- @coyotte508, is there a way in the *var* function that takes the prop name and the variable value to add a default? How can some logic be attached to it? Is it possible to make this prop inclusion optional for the parent component in adding it?\n- @Vass, no. You would need to set it as a variable, e.g. \"backgroundImage\" where you would have access to the string in javascript.","metadata":{"transformedAt":"2026-08-18T18:33:40.667Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":214,"estimatedTokens":1173}}134{"id":"stack-62499335","source":"stackoverflow","questionId":62499335,"title":"Further explanation of Svelte's keyed each block","tags":["javascript","each","svelte","svelte-3"],"text":"Title: Further explanation of Svelte's keyed each block\nTags: javascript, each, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI don't understand this section in the tutorial: https://svelte.dev/tutorial/keyed-each-blocks.\n\nI can see the `things` array is updated correctly so the right `thing.color` is passed as expected. But by the first sentence \"By default, when you modify the value of an `each` block, it will add and remove items at the end of the block, and update any values that have changed.\", it seems to be saying that Svelte anyway removes the last block when clicking the button, then the remaining 4 blocks will be faced with the sliced `things`, which is\n\n```\n[{ id: 2, color: '#6a00a8' },\n { id: 3, color: '#b12a90' },\n { id: 4, color: '#e16462' },\n { id: 5, color: '#fca636' }]\n```\n\nAnd since `initial` is declared as `const`, it cannot be updated anymore, so the colors of `thing.id` 1--4 remains.\n\nIs this a correct understanding? Is this default behavior assuming the `each` blocks are exchangeable?\n\nThen it says using `thing.id` as the key for the `each` blocks will solve the issue, namely, `{#each things as thing (thing.id)}`. I don't understand how the keys are used in the `each` blocks and what was the default key if `thing.id` is not provided. And why the default key (if there is one, or the default no-key) doesn't work while providing `thing.id` does.\n\nThanks for the clarification.\n\n========================================\n\nTop Answer:\nThe API docs explain it thus:\n\nIf a *key* expression is provided — which must uniquely identify each list item — Svelte will use it to intelligently update the list when data changes by inserting, moving and deleting items, rather than adding or removing items at the end and updating the state in the middle.\n\nThe key can be any object, but strings and numbers are recommended since they allow identity to persist when the objects themselves change.\n\n```\n{#each items as item (item.id)}\n \n- {item.name} x {item.qty}\n{/each}\n\n{#each items as item, i (item.id)}\n \n- {i + 1}: {item.name} x {item.qty}\n{/each}\n```\n\nI found this was lacking proper explanation in the tutorial as well. However, I think the docs are more clear-- a unique key may be provided to the each function so that every iteration is uniquely identified. Thus, when a particular element is removed from the\ndata provided to the each function, the correct iteration can be identified and removed.\n\n========================================\n\nCode:\n```text\n[{ id: 2, color: '#6a00a8' },\n { id: 3, color: '#b12a90' },\n { id: 4, color: '#e16462' },\n { id: 5, color: '#fca636' }]\n```\n\n```text\nthings\n```\n\n```text\nthing.color\n```\n\n```text\neach\n```\n\n```text\nthings\n```\n\n```text\ninitial\n```\n\n```text\nconst\n```\n\n```text\nthing.id\n```\n\n```text\neach\n```\n\n```text\nthing.id\n```\n\n```text\neach\n```\n\n```text\n{#each things as thing (thing.id)}\n```\n\n```text\neach\n```\n\n```text\nthing.id\n```\n\n```text\nthing.id\n```\n\n```text\n{#each things as thing, index (index)}\n <Thing current={thing.color}/>\n{/each}\n```\n\n```text\n<Thing>\n```\n\n```text\nid: 1\n```\n\n```text\nThing1\n```\n\n```text\nThing1\n```\n\n```text\nThing2\n```\n\n```text\nThing1\n```\n\n```text\nThing5\n```\n\n```text\nThing\n```\n\n```text\nThing1\n```\n\n```text\nThing1\n```\n\n```text\ninitial\n```\n\n```text\nid: 1\n```\n\n```text\nid: 1\n```\n\n```text\nThing\n```\n\n```text\nThing1\n```\n\n```js\n{#each items as item (item.id)}\n <li>{item.name} x {item.qty}</li>\n{/each}\n\n<!-- or with additional index value -->\n{#each items as item, i (item.id)}\n <li>{i + 1}: {item.name} x {item.qty}</li>\n{/each}\n```\n\n```text\nconst emoji = emojis[name]\n```\n\n```text\n$: emoji = emojis[name];\n```\n\n```text\n{#each} {/each}\n```\n\n```text\n<Thing>\n```\n\n```text\n<Thing>\n```\n\n```text\n'things'\n```\n\n```text\n(thing.id)\n```\n\n```text\n(thing.hashCode())\n```\n\n========================================\n\nComments:\n- This is the best explanation I've ever seen. This should go to official Svelte docs.\n- adding `(thing.id)` into each block is something like changing `const initial = current` to `$: initial = current`\n- Amazing explanation, totally cleared it up for me. Huge thanks!\n- What if the id is set to 0 originally for the 1st element in `things`? seems to have the same erroneous behavior","metadata":{"transformedAt":"2026-08-18T18:33:40.667Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":40,"totalLines":230,"estimatedTokens":1052}}135{"id":"stack-55830638","source":"stackoverflow","questionId":55830638,"title":"What is this : sign after a variable JS syntax?","tags":["javascript","syntax","svelte","labeled-statements"],"text":"Title: What is this : sign after a variable JS syntax?\nTags: javascript, syntax, svelte, labeled-statements\nSource: Stack Overflow\n\nQuestion:\nI came across the following valid syntax in JS when looking at `svelte` library:\n\n```\n$: doubled = 6 * 2;\n```\n\nAt first, I thought it was specific for the library, **but it works on the Chrome console**. What is this syntax?\n\nIt can be anything:\n\n```\nname: something = 6 * 2;\n```\n\n========================================\n\nTop Answer:\nThis is label in JavaScript.\n\nThe interesting point here is how Svelte is using this to bind variables to other variables. Here's a portion of a video where Rich Harris explains this.\n\nEssentially, in Svelte, **`$:`** means **re-run whenever these values change**\n\nIf we look a the example in Svelte's Reactive declarations example,\n\n```\n\n let count = 1;\n\n // the `$:` means 're-run whenever these values change'\n $: doubled = count * 2;\n $: quadrupled = doubled * 2;\n\n function handleClick() {\n count += 1;\n }\n\n Count: {count}\n\n{count} * 2 = {doubled}\n\n{doubled} * 2 = {quadrupled}\n\n```\n\nThe variables `doubled` and `quadrupled` have `$` label. So, they'll be computed again when `count` or `doubled` changes respectively.\n\nIf you take a look at the compiled code, you can see\n\n```\nlet doubled, quadrupled;\n$$self.$$.update = ($$dirty = { count: 1, doubled: 1 }) => {\n if ($$dirty.count) { $$invalidate('doubled', doubled = count * 2); }\n if ($$dirty.doubled) { $$invalidate('quadrupled', quadrupled = doubled * 2); }\n};\n```\n\nSo, each time the update happens, there is a dirty check for those variables and update. \n\nIn conclusion. `$:` in Svelte doesn't have anything to do with JavaScript label. It's a directive for Svelte compiler to have the code for updating those variables. `$:` is of course valid syntax but outside the context of Svelte, it doesn't do what it does in Svelte. It's the compilation that does the magic ;)\n\n========================================\n\nCode:\n```text\n$: doubled = 6 * 2;\n```\n\n```text\nname: something = 6 * 2;\n```\n\n```text\nsvelte\n```\n\n```text\nfoo: var x = 0;\n```\n\n```text\n$: doubled = 6 * 2;\n```\n\n```text\nwholeLoop:\nfor (let i = 0; i < matrix.length; i++) {\n for (let j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] == null)\n // Oh no! This is terrible\n break wholeLoop;\n }\n}\n```\n\n```text\ngoto\n```\n\n```text\nbreak\n```\n\n```text\ncontinue\n```\n\n```text\nlet count = 0;\n$: doubled = count * 2;\n```\n\n```text\nbreak\n```\n\n```text\ncontinue\n```\n\n```text\n<script>\n let count = 1;\n\n // the `$:` means 're-run whenever these values change'\n $: doubled = count * 2;\n $: quadrupled = doubled * 2;\n\n function handleClick() {\n count += 1;\n }\n</script>\n\n<button on:click={handleClick}>\n Count: {count}\n</button>\n\n<p>{count} * 2 = {doubled}</p>\n<p>{doubled} * 2 = {quadrupled}</p>\n```\n\n```text\nlet doubled, quadrupled;\n$$self.$$.update = ($$dirty = { count: 1, doubled: 1 }) => {\n if ($$dirty.count) { $$invalidate('doubled', doubled = count * 2); }\n if ($$dirty.doubled) { $$invalidate('quadrupled', quadrupled = doubled * 2); }\n};\n```\n\n```text\n$:\n```\n\n```text\ndoubled\n```\n\n```text\nquadrupled\n```\n\n```text\n$\n```\n\n```text\ncount\n```\n\n```text\ndoubled\n```\n\n```text\n$:\n```\n\n```text\n$:\n```\n\n```text\n$\n```\n\n```text\n$:\n```\n\n========================================\n\nComments:\n- It's just variable/property name. `doubled` is probably a typescript interface or a class\n- `$` is valid character in any JavaScript identifier. Without seeing more context for that code, it looks like a labelled statement to me.\n- @SudhirOjha you are wrong :) jQuery **is** JavaScript.\n- @Pointy You can never have enough jQuery.\n- This is so interesting, i can't find anything about it.\n- stackoverflow.com/questions/1150381/…\n- just to add to @Pointy, it's like `label: x = 1 + 1;`\n- It works in Chrome console because it's a valid labeled statement. From their github it looks like they are using typescript. So, it's unlikely that this is labeled statement\n- It actually works in Vanilla JS! This is ridiculous, I completely expected it to throw a syntax error.\n- @adiga I understand, possibly incorrectly, that TypeScript is a superset of JavaScript syntax\n- @Pointy All javascript is valid typescript** (Conditions apply: `var a = \"\"; a = 1;` will throw an error). But, it does look like labeled statement after all github.com/sveltejs/svelte/blob/…\n- Not enough jQuery.\n- @LogicalBranch funny thing is I'm like the last jQuery user on earth I sometimes think.\n- I still use various versions of jQuery in production environments, mainly for safety and browser support. It's probably the greatest JS library to exist.\n- I think the saddest thing about jQuery is when people attack you for using it then make out out to be some kind of demon for wanting good browser support.\n- Yea I mean, it just gets rid of a bunch of unnecessary headaches, and so long as it's not abused I don't have a problem with it. (jQueryUI I don't like, however, but that's mostly a matter of design opinion.)\n- In the beginning jQuery UI was very promising, then they added those horrific themes/add ons.\n- I must be doing something wrong, I just error this error \"Uncaught ReferenceError: assignment to undeclared variable doubled\"","metadata":{"transformedAt":"2026-08-18T18:33:40.667Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":215,"estimatedTokens":1312}}136{"id":"stack-73790956","source":"stackoverflow","questionId":73790956,"title":"Cross-site POST form submissions are forbidden","tags":["node.js","post","backend","svelte","sveltekit"],"text":"Title: Cross-site POST form submissions are forbidden\nTags: node.js, post, backend, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nMy sveltekit app has a form which sends a POST request to server. The app is working fine on dev server but when I build and run the app it fails to send the form data via POST request. It shows the following error in the browser:\n\nCross-site POST form submissions are forbidden\n\n========================================\n\nTop Answer:\nThis is a built-in protection against cross-site request forgery attacks in Sveltekit. Set `csrf` to `false` in `svelte.config.js` to allow cross-site post requests.\n\nSee csrf in the Sveltekit configuration docs\n\n```\nimport adapter from '@sveltejs/adapter-node'\n\nconst config = {\n kit: {\n adapter: adapter(),\n csrf: {\n checkOrigin: false,\n }\n },\n}\n\nexport default config\n```\n\n========================================\n\nCode:\n```text\nORIGIN=http://localhost:3000 node build/index.js\n```\n\n```js\nimport adapter from '@sveltejs/adapter-node'\n\nconst config = {\n kit: {\n adapter: adapter(),\n csrf: {\n checkOrigin: false,\n }\n },\n}\n\nexport default config\n```\n\n```text\ncsrf\n```\n\n```text\nfalse\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nnode -r dotenv/config build\n```\n\n```text\nORIGIN=https://yourwebsite.com\n```\n\n```text\nnpm install dotenv\n```\n\n```text\nORIGIN=https://yourapp.com pm2 restart /var/www/build/index.js --name 'yourapp' --update-env\n```\n\n```text\nenvironment:\n - ORIGIN=https://mywebsite.com\n```\n\n```text\nORIGIN\n```\n\n```text\nENV ORIGIN https://mywebsite.com\n```\n\n```js\nfunction is_form_content_type(request) {\n return is_content_type(\n request,\n \"application/x-www-form-urlencoded\",\n \"multipart/form-data\",\n \"text/plain\"\n );\n}\n```\n\n```text\ncsrf\n```\n\n```text\nContent-Type\n```\n\n```text\nContent-Type\n```\n\n```text\napplication/json\n```\n\n```text\nenvironment:\n - ORIGIN=https://example.com\n```\n\n```text\nexample.com {\n reverse_proxy mysite:3000 {\n header_up Host\n }\n}\n```\n\n```text\nORIGIN\n```\n\n```text\nORIGIN=https://example.com node build/index.js\n```\n\n```text\ns\n```\n\n```text\nhttps\n```\n\n```text\nhttps://example.com\n```\n\n```text\nhttps://www.example.com\n```\n\n```text\nhttps://\n```\n\n```text\nhttp://\n```\n\n```text\nCaddy\n```\n\n```text\nheader_up Host\n```\n\n```text\nHost\n```\n\n```text\nnginx\n```\n\n```text\nproxy_set_header Host $http_host;\n```\n\n========================================\n\nComments:\n- I would *not* advise to do this! CSRF attacks are a real thing and its important to have a protection against them. See the answer below by evan for the correct way to do it - you have to tell the sveltekit server about the actual origin domain when you start your sveltekit application.\n- Can this be done for a single route?\n- @gwest7 It can be done for individual hostnames now using the new `trustedOrigins` settings. `checkOrigin` has been deprecated. See the docs for more info: `https://svelte.dev/docs/kit/configuration#csrf`\n- Thank you, this worked. Also for anyone who's setting enviroment variables in powershell, `$env:ORIGIN = \"http://127.0.0.1\"` and run `node build/index.js` on the next line, because for some reason, powershell does not notice the change in env var when the env var is changed and the build command is run on the same line.\n- What about `import adapter from '@sveltejs/adapter-auto';` ? how to fix this error with adapter-auto..\n- You can also set an environment variable `ORIGIN` when you deploy your app (for example when using Docker). Note that it is important whether you use `https://example.com` or `https://www.example.com` when setting the origin.\n- you may need to benefit from node-adaptor if you are using sveltekit with latest version kit.svelte.dev/docs/adapter-node\n- I have a .com site and a .org site. Using nginx to point both to the same app. Should I be redirecting to one or the other instead? Because if I specify ORIGIN to be one domain, POST requests won't be available on the other domain\n- hey @DavidPH how did you fix this ? I have a similar situation\n- @TheAnimatrix Unfortunately not, don't think it's possible. I ended up setting csrf to false like that other answer suggested. Later on I made one domain redirect to the other and re-enabled csrf. I'd still be interested if a solution exists though.\n- Can we make this work with multiple origins ?\n- Now it doesn't after updating it. Something may go wrong and it doesn't restart the serever, thus not loading origin as your domain\n- After several days, checked .env variables if they are loaded correctly, seems origin is undefined: process.env.ORIGIN. Check all of them `console.log(process.env)`\n- You mention that changing a specific setting is unwise; could you add an edit to explain why? Readers may appreciate the detail.\n- @halfer on why is unwise to turn off a security measure made specifically to avoid a specific type of attack? Google csrf\n- @Emiliano: the point of my remark was to offer this answer author an opportunity to improve their post. \"You can google it\" is insufficient here; we want answers to be self-contained. Would you like to propose an edit to this answer?","metadata":{"transformedAt":"2026-08-18T18:33:40.667Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":205,"estimatedTokens":1288}}137{"id":"stack-57580013","source":"stackoverflow","questionId":57580013,"title":"How to render html in svelte","tags":["html","render","svelte","svelte-3"],"text":"Title: How to render html in svelte\nTags: html, render, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI have tried rendering the html by storing the html in a variable but it is not working , I also tried the triple curly braces\n\n```\n\n let name = 'world';\n let val = \"\"\n let ans2 = \"\"\n let ans3;\n import showdown from 'showdown';\n import validity from 'validity-checker';\n function dataSubmit(e){\n e.preventDefault();\n //ans = validity.isEmoji(\"ggg\");\n ans2 = new showdown.Converter();\n ans3 = ans2.makeHtml(val)\n }\n\n \n \n {{{ans3}}} \n \n \n\n```\n\nReturn type of the ans3 variable is like \"\n\n### Hello\n\n\"\n\n========================================\n\nTop Answer:\nOrdinarily, strings are inserted as plain text, meaning that characters like `` have no special meaning.\n\nBut sometimes you need to render HTML directly into a component. For example, the words you're reading right now exist in a markdown file that gets included on this page as a blob of HTML.\n\nIn Svelte, you do this with the special `{@html ...}` tag:\n\n```\n{@html string}\n\n```\n\nSvelte doesn't perform any sanitization of the expression inside `{@html ...}` before it gets inserted into the DOM. In other words, if you use this feature it's critical that you manually escape HTML that comes from sources you don't trust, otherwise you risk exposing your users to XSS attacks.\n\nFrom https://svelte.dev/tutorial/html-tags\n\n========================================\n\nCode:\n```html\n<script>\n let name = 'world';\n let val = \"\"\n let ans2 = \"\"\n let ans3;\n import showdown from 'showdown';\n import validity from 'validity-checker';\n function dataSubmit(e){\n e.preventDefault();\n //ans = validity.isEmoji(\"ggg\");\n ans2 = new showdown.Converter();\n ans3 = ans2.makeHtml(val)\n }\n</script>\n\n<div>\n <textarea bind:value={val} on:change={dataSubmit}></textarea>\n <div>\n {{{ans3}}} \n </div>\n \n</div>\n```\n\n```text\n{@html expression}\n```\n\n```html\n<p>{@html string}</p>\n```\n\n```text\n<\n```\n\n```text\n>\n```\n\n```text\n{@html ...}\n```\n\n```text\n{@html ...}\n```\n\n```text\nlet myComponent = document.createElement('div');\n\ndocument.getElementById('parent').appendChild(myComponent);\n```\n\n```text\n{@html expression : string}\n```\n\n========================================\n\nComments:\n- This doesn't work for me. I get entity encoded html\n- @chovy see a working example\n- Is this only static? Updating expression seems fruitless.","metadata":{"transformedAt":"2026-08-18T18:33:40.667Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":122,"estimatedTokens":604}}138{"id":"stack-56988717","source":"stackoverflow","questionId":56988717,"title":"How to target a component in svelte with css?","tags":["javascript","svelte","svelte-component"],"text":"Title: How to target a component in svelte with css?\nTags: javascript, svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nHow would I do something like this:\n\n```\n\nNested {\n color: blue;\n}\n\n```\n\ni.e. How do I apply a style to a component from its parent?\n\n========================================\n\nTop Answer:\nThe only way I can think of is with an additional `div` element.\n\n**App.svelte**\n\n```\n\n import Nested from './Nested.svelte' \n\n div :global(.style-in-parent) {\n color: green;\n }\n\n \n\n```\n\n**Nested.svelte**\n\n```\n\n Colored based on parent style\n\n```\n\n**Multiple Nested elements**\n\nYou could even allow the class name to be dynamic and allow for different colors if you use multiple `Nested` components. Here's a link to a working example.\n\n========================================\n\nCode:\n```text\n<style>\nNested {\n color: blue;\n}\n</style>\n\n<Nested />\n```\n\n```html\n<!-- in parent component -->\n\n<script>\nimport Nested from './Nested.svelte';\n</script>\n\n<Nested class=\"foo\"/>\n<style>\n:global(.foo) {\n //...\n}\n</style>\n```\n\n```html\n<!-- in Nested.svelte -->\n\n<script>\nlet {\n class: propsClass = \"\"\n} = $props()\n</script>\n\n<p class={propsClass}>\n Yes this will work\n</p>\n```\n\n```html\n<!-- in parent component -->\n\n<script>\nimport Nested from './Nested.svelte';\n</script>\n\n<Nested color=\"green\"/>\n```\n\n```html\n<!-- in Nested.svelte -->\n\n<script>\nexport let color;\n</script>\n\n<p style=\"color: {color}\">\n Yes this will work\n</p>\n```\n\n```html\n<!-- in parent component -->\n\n<script>\nimport Nested from './Nested.svelte';\n</script>\n\n<Nested ref=\"green\"/>\n\n<style>\n:global([ref=green]) {\n background: green;\n color: white;\n padding: 5px;\n border-radius: .5rem;\n}\n</style>\n```\n\n```html\n<!-- in Nested.svelte -->\n\n<script>\nexport let ref;\n</script>\n\n<p {ref}>\n Yes this will work also\n</p>\n```\n\n```text\npropsClass\n```\n\n```html\n<style>\n.Nested {\n color: blue;\n}\n</style>\n<div class=\"Nested\">\n <Nested />\n</div>\n```\n\n```text\n<div>\n```\n\n```html\n<script>\n import Nested from './Nested.svelte' \n</script>\n\n<style>\n div :global(.style-in-parent) {\n color: green;\n }\n</style>\n\n<div>\n <Nested /> \n</div>\n```\n\n```html\n<div class=\"style-in-parent\">\n Colored based on parent style\n</div>\n```\n\n```text\ndiv\n```\n\n```text\nNested\n```\n\n```text\n<style>\n div > :global(*) {\n color: blue;\n }\n<style>\n\n<div>\n <Nested />\n<div>\n```\n\n```text\n:global(*)\n```\n\n```text\n<!-- in parent component -->\n\n<script>\nimport Nested from './Nested.svelte';\n</script>\n\n<Nested style=\"background: green; color: white; padding: 10px; text-align: center; font-weight: bold\" />\n```\n\n```text\n<!-- in Nested.svelte -->\n\n<script>\n let stylish=$$props.style\n</script>\n\n<div style={stylish}>\n Hello World\n</div>\n```\n\n```html\n<style lang=\"stylus\">\n section\n // section styles\n\n :global(img)\n // image styles\n</style>\n```\n\n```text\nsection.svelte-15ht3eh img\n```\n\n```svelte\n<svelte:head>\n <style>\n div { color: red };\n </style>\n</svelte:head>\n```\n\n```text\n<!-- Nested.svelte -->\n<div>\n <slot />\n</div>\n\n<style>\n div { color: var(--nested-color, inherit); }\n</style>\n```\n\n```text\n<!-- Parent.svelte -->\n<div>\n <Nested>\n Applesauce\n </Nested>\n</div>\n\n<style>\n div {\n --nested-color: red;\n }\n</style>\n```\n\n```html\n<style>\n.wrapper > :global(*){\n color: blue;\n}\n</style>\n\n<div class=\"wrapper\">\n <Nested class=\"nested\"/>\n</div>\n```\n\n```html\n<style>\n.wrapper > :global(.nested){\n color: blue;\n}\n</style>\n\n<div class=\"wrapper\">\n <Nested class=\"nested\"/>\n <Nested/>\n</div>\n```\n\n```html\n<div class={$$props.class} />\n```\n\n```html\n<style>\n:global(.ss-ReplaceWithRandom){\n color: blue;\n}\n</style>\n\n<Nested class=\"ss-ReplaceWithRandom\"/>\n<Nested/>\n```\n\n```html\n<div class={$$props.class} />\n```\n\n```html\n<style>\n* + :global(*){\n color: blue;\n}\n</style>\n\n<template />\n<Nested/>\n```\n\n========================================\n\nComments:\n- What parent? I see no parent here.\n- Just add a class to your Nested component ``. stackoverflow.com/q/42765262/6809926\n- @AntoineF that doesn't work in svelte. It thinks that the class is a property, I think.\n- @MarkSchultheiss that is the code in the parent.\n- This approach sets `color: blue` on the entire `Nested` component. I provided an answer below that allows you to targed certain elements within `Nested`.\n- @MikeNikles nice one, I just discover svelte 20 minute ago, I didn't know about this.\n- You made a nice discovery :)! I've used it for a while but it also took me quite a bit to figure out how this all works with styling nested components.\n- Is the `.` inside the style tag needed?\n- Yes because you not anymore targeting the `Nested` component but div class above, so in CSS you need to use the dot to trigger it.\n- As I see you use :global so it's not targeting only inside the Nested Component, but all class `style-in-parent` inside the div. I tried it here.\n- Ah right, good catch. I think the next step is to understand your use case better and why you try to style from the parent component.\n- In order to avoid leaking in the same component, you should add a class known to be unique, once again in the same component (svelte will add a hash preventing it from leaking outside. Here's an variation of @MikeNikles example: svelte.dev/repl/09b33283d787480cb30cab35d5b9d0a0?version=3.6‌​.7\n- The `ref` above is just an attribute, so that global CSS will leak out and affect any component with an attribute of `ref=green`.\n- This is the best and most simple solution because you can target Components that are more than 1 level Nested.\n- One-liner for Nested.svelte: ``\n- This seems to be just what OP asked for, are there any downsides to doing it this way? Looks very straight-forward!\n- @MartinGunnarsson what if you are using library components? Then you have to go to the source code to add props into divs\n- @cikatomo what will be a good solution in your opinion for headless library components like npmjs.com/package/@bojalelabs/headless-svelte-ui to enable us to add props to divs?\n- @ayooluwaalfonso sorry, I really don't know\n- I found using $$props in a component caused it to get updated more frequently. It was better to have custom props and svelte would more accurately determine if a component updated or not.\n- Life saver! `` is the only thing that worked correctly.","metadata":{"transformedAt":"2026-08-18T18:33:40.668Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":357,"estimatedTokens":1578}}139{"id":"stack-64131176","source":"stackoverflow","questionId":64131176,"title":"Svelte custom event on svelte typescript","tags":["javascript","typescript","typescript-typings","svelte","svelte-3"],"text":"Title: Svelte custom event on svelte typescript\nTags: javascript, typescript, typescript-typings, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI'm using clickOutside directive on my svelte-typescript project and I'm getting this error when I assign custom event to the related element\n\n```\nType '{ class: string; onclick_outside: () => boolean; }' is not assignable to type 'HTMLProps'.\n Property 'onclick_outside' does not exist on type 'HTMLProps'\n```\n\nhere's a snippet of my code\n\n```\n{#if profileToolbar}\n (profileToolbar = !profileToolbar)}\n class=\"origin-top-right absolute right-0 mt-2 w-48 rounded-md\n shadow-lg z-10 shadow-md\">\n```\n\nthis is the clickOutside directive that I'm using currently https://svelte.dev/repl/0ace7a508bd843b798ae599940a91783?version=3.16.7\n\nI'm new to typescript so I don't really know where to start with my google search, anyone knows how to tackle this issue? thanks for your help\n\n========================================\n\nTop Answer:\nAccording to the doc, you can create a `.d.ts` file in your project somewhere. And put inside that file the following:\n\n```\ndeclare namespace svelte.JSX {\n interface HTMLAttributes {\n onclick_outside: () => void\n }\n}\n```\n\nPlease read the doc for more detail.\n\n========================================\n\nCode:\n```text\nType '{ class: string; onclick_outside: () => boolean; }' is not assignable to type 'HTMLProps<HTMLDivElement>'.\n Property 'onclick_outside' does not exist on type 'HTMLProps<HTMLDivElement>'\n```\n\n```html\n{#if profileToolbar}\n<div\n transition:fly={{ y: -20, duration: 300 }}\n use:clickOutside={profileToolbarContainer}\n on:click_outside={() => (profileToolbar = !profileToolbar)}\n class=\"origin-top-right absolute right-0 mt-2 w-48 rounded-md\n shadow-lg z-10 shadow-md\">\n```\n\n```text\ndeclare namespace svelte.JSX {\n interface HTMLProps<T> {\n onclick_outside?: (e: CustomEvent) => void;\n }\n}\n```\n\n```text\nclickOutside\n```\n\n```text\nclick_outside\n```\n\n```text\ndeclare namespace svelte.JSX {\n interface HTMLAttributes<T> {\n onclick_outside: () => void\n }\n}\n```\n\n```text\n.d.ts\n```\n\n```text\ndeclare namespace svelte.JSX {\n interface DOMAttributes<T> {\n onclick_outside?: CompositionEventHandler<T>;\n }\n}\n```\n\n```text\ntsconfig.json\n```\n\n```text\ndeclare namespace svelteHTML {\n interface HTMLAttributes<T> {\n \"on:click_outside\"?: CompositionEventHandler<T>;\n }\n}\n```\n\n```text\nsrc/app.d.ts\n```\n\n```text\n// See https://kit.svelte.dev/docs/types#app\n// for information about these interfaces\ndeclare global {\n namespace App {\n // interface Error {}\n // interface Locals {}\n // interface PageData {}\n // interface Platform {}\n }\n\n declare namespace svelteHTML {\n interface HTMLAttributes<T> {\n 'on:clickOutside'?: CompositionEventHandler<T>;\n }\n }\n}\n\nexport { };\n```\n\n```text\nsrc/app.d.ts\n```\n\n```js\nconst dispatch = createEventDispatcher<{\n mounted: { id: string; store: FSStore }\n destroyed: { id: string }\n }>()\n\nonMount(() => {\n dispatch('mounted', {\n id,\n store: fsStore,\n })\n return () => {\n dispatch('destroyed', {\n id,\n })\n }\n})\n```\n\n```html\n<Explorer\n on:mounted={onExplorerMount}\n on:destroyed={onExplorerDestroy}\n/>\n```\n\n```text\n// See https://kit.svelte.dev/docs/types#app\n// for information about these interfaces\ndeclare global {\n namespace App {\n // interface Error {}\n // interface Locals {}\n // interface PageData {}\n // interface PageState {}\n // interface Platform {}\n }\n\n declare namespace svelteHTML {\n interface HTMLAttributes {\n 'on:remove'?: (event: CustomEvent<{ itemId: string }>) => void;\n }\n }\n}\n\nexport {};\n```\n\n```text\nevent.details\n```\n\n========================================\n\nComments:\n- Works perfectly!, i just need to change it to `interface HTMLProps`, thanks for the help and the advice man, i'm aware that svelte typescript is still new, but unfortunately i'm not the one making the decision atm, but i'll make sure to remember your words\n- To hackape: I know this is a little off topic, but could you some of the other inconveniences you experienced while using Svelte with TS? I'm one of the maintainers in that area and feedback like this is really valuable (because it's rare).\n- @dummdidumm I know bridging the two is not easy, so kudos to the work! But sorry I don’t have much to cus it was more than half a year ago and I don’t remember much about specific things. I can only remember the general impression about the experience was acceptable, but not totally satisfying. At the end of day I thought to myself better just keep the TS things in `.ts` file as much as possible and import into `.svelte` file to lessen the melange and ignore warnings. Later on I switch back to the comfort world of react 😅\n- I was trying to port the svelte repl into vscode extension, but got interrupted then dropped it halfway. I can find time to dust off and refresh my memory. If I have anything worth sharing I’ll get back to you.\n- Thanks for the quick response! Things should be better now half a year later, but I agree that there are still some rough edges. About your REPL: In case you only want the \"show compiled output\" behavior of the REPL, that is now possible through the Svelte for VS Code extension. Command is \"Svelte: Show Compiled Code\".\n- Ah okay. I want the preview feature too. Are you maintainer of the vscode extension?\n- Where do you put this?\n- @Marcus and future readers: SvelteKit comes with a `app.d.ts` inside the `src` folder. That's a fine location, also if you're using \"plain\" Svelte. In comparison, Angular used to generate a `typings.d.ts` in its `src` folder for the same purpose.\n- That's the only one actually working, should be marked as answer\n- For those looking at this answer: A gotcha in this new format is that the property includes the colon `:` in the property name. So `on:clickOutside` instead of `onclickOutside`\n- My custom event and class is called `clickOutside`, so it works for me.\n- worked perfectly @sveltejs/kit\": \"^2.0.0\",","metadata":{"transformedAt":"2026-08-18T18:33:40.668Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":202,"estimatedTokens":1532}}140{"id":"stack-61333755","source":"stackoverflow","questionId":61333755,"title":"Svelte - access child component's method","tags":["javascript","svelte"],"text":"Title: Svelte - access child component's method\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI have an app that simply hides content `Hidden.svelte`:\n\n```\n\n let shown = false;\n\n function show() {\n shown = true;\n }\n\n{#if shown}\n \n{/if}\n```\n\nParent `App.svelte`:\n\n```\n\n import Hidden from 'Hidden';\n\n let child;\n\n Content\n\n child.shown = true}>Show\n```\n\nSo, child's `shown` can be easily set due to `` in parent\n\nBut, I want to use method `show()` since it can not only set `shown` value, but also perform some magic\n\nThx to Chrome's DevTools, I found that all components have an `Array` with props and methods, that could be accessed via some `.$$.ctx`, so Hidden's `show()` method can be called like this:\n\n```\n child.$$.ctx[2]()}>Show\n```\n\nBut) You know) Is there is a legal way to do it?\n\n========================================\n\nTop Answer:\nAnother solution than binding the whole child component is to bind the child's component method in the parent :\n\n`Hidden.svelte`\n\n```\n\n let shown = false;\n\n export function show() {\n shown = true;\n }\n\n{#if shown}\n \n{/if}\n```\n\n`App.svelte`\n\n```\n\n import Hidden from './Hidden.svelte';\n\n let childShow;\n\n Content\n\n childShow()}>Show\n```\n\n========================================\n\nCode:\n```text\n<script>\n let shown = false;\n\n function show() {\n shown = true;\n }\n</script>\n\n<svelte:options accessors={true}/>\n\n{#if shown}\n <slot/>\n{/if}\n```\n\n```text\n<script>\n import Hidden from 'Hidden';\n\n let child;\n</script>\n\n<Hidden bind:this={child}>\n Content\n</Hidden>\n\n<button on:click={() => child.shown = true}>Show</button>\n```\n\n```text\n<button on:click={() => child.$$.ctx[2]()}>Show</button>\n```\n\n```text\nHidden.svelte\n```\n\n```text\nApp.svelte\n```\n\n```text\nshown\n```\n\n```text\n<svelte:options accessors={true}/>\n```\n\n```text\nshow()\n```\n\n```text\nshown\n```\n\n```text\nArray\n```\n\n```text\n.$$.ctx\n```\n\n```text\nshow()\n```\n\n```html\n<script>\n let shown = false;\n\n export function show() {\n shown = true;\n }\n</script>\n\n{#if shown}\n <slot/>\n{/if}\n```\n\n```html\n<script>\n import Hidden from './Hidden.svelte';\n\n let child;\n</script>\n\n<Hidden bind:this={child}>\n Content\n</Hidden>\n\n<button on:click={() => child.show()}>Show</button>\n```\n\n```html\n<button on:click={child.show}>Show</button>\n```\n\n```text\nHidden.svelte\n```\n\n```text\nApp.svelte\n```\n\n```text\nchild.show()\n```\n\n```html\n<script>\n let shown = false;\n\n export function show() {\n shown = true;\n }\n</script>\n\n{#if shown}\n <slot/>\n{/if}\n```\n\n```html\n<script>\n import Hidden from './Hidden.svelte';\n\n let childShow;\n</script>\n\n<Hidden bind:show={childShow}>\n Content\n</Hidden>\n\n<button on:click={() => childShow()}>Show</button>\n```\n\n```text\nHidden.svelte\n```\n\n```text\nApp.svelte\n```\n\n========================================\n\nComments:\n- You can even use the same method name in the parent and child. Like: ``","metadata":{"transformedAt":"2026-08-18T18:33:40.668Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":235,"estimatedTokens":721}}141{"id":"stack-59605327","source":"stackoverflow","questionId":59605327,"title":"How do you load and use a custom font in Svelte","tags":["fonts","svelte"],"text":"Title: How do you load and use a custom font in Svelte\nTags: fonts, svelte\nSource: Stack Overflow\n\nQuestion:\nI know it probably uses @font-face but I dont know where to put my woff files localy to get Svelte to use a custom font. I dont know where to put the @font-face either. Thanks in advance!\n\n========================================\n\nTop Answer:\nIf you are using Sveltekit, you can load fonts locally using the `static` directory.\n\nStore your font files under `static/fonts`, and then use either a CSS file or a `` tag to reference your font files.\n\n```\n/* fonts.css */\n\n@font-face {\n font-family: 'Lora';\n font-style: normal;\n font-weight: 500;\n src: url('/fonts/lora-v20-latin-500.eot'); /* IE9 Compat Modes */\n src: local(''), url('/fonts/lora-v20-latin-500.eot?#iefix') format('embedded-opentype'),\n /* IE6-IE8 */ url('/fonts/lora-v20-latin-500.woff2') format('woff2'),\n /* Super Modern Browsers */ url('/fonts/lora-v20-latin-500.woff') format('woff'),\n /* Modern Browsers */ url('/fonts/lora-v20-latin-500.ttf') format('truetype'),\n /* Safari, Android, iOS */ url('/fonts/lora-v20-latin-500.svg#Lora') format('svg'); /* Legacy iOS */\n}\n```\n\nFinally, just import the CSS file in your `__layout.svelte` file:\n\n```\n\n import '/styles/fonts.css';\n\n```\n\n========================================\n\nCode:\n```html\n<h1>Hello World!</h1>\n\n<style>\n @font-face {\n font-family: 'Gelasio';\n font-style: normal;\n font-weight: 400;\n src: local('Gelasio Regular'), local('Gelasio-Regular'), url(https://fonts.gstatic.com/s/gelasio/v1/cIf9MaFfvUQxTTqS9C6hYQ.woff2) format('woff2');\n unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;\n }\n\n h1 {\n font-family: Gelasio\n }\n</style>\n```\n\n```html\n<svelte:head>\n <link href=\"https://fonts.googleapis.com/css?family=Gelasio\" rel=\"stylesheet\">\n</svelte:head>\n```\n\n```text\n@font-face\n```\n\n```text\n.svelte\n```\n\n```text\n<style>\n```\n\n```text\n<link>\n```\n\n```text\n<svelte:head>\n```\n\n```css\n@font-face{\n font-family: 'yourFont';\n src: url('/fonts/yourFont.woff') format('woff');\n}\n```\n\n```text\n/public\n```\n\n```text\n/src\n```\n\n```text\n/public/fonts\n```\n\n```text\nglobal.css\n```\n\n```text\n<svelte:head>\n <style>\n @import url(\"https://fonts.googleapis.com/css?family=Raleway&display=swap\");\n </style>\n</svelte:head>\n```\n\n```css\n/* fonts.css */\n\n@font-face {\n font-family: 'Lora';\n font-style: normal;\n font-weight: 500;\n src: url('/fonts/lora-v20-latin-500.eot'); /* IE9 Compat Modes */\n src: local(''), url('/fonts/lora-v20-latin-500.eot?#iefix') format('embedded-opentype'),\n /* IE6-IE8 */ url('/fonts/lora-v20-latin-500.woff2') format('woff2'),\n /* Super Modern Browsers */ url('/fonts/lora-v20-latin-500.woff') format('woff'),\n /* Modern Browsers */ url('/fonts/lora-v20-latin-500.ttf') format('truetype'),\n /* Safari, Android, iOS */ url('/fonts/lora-v20-latin-500.svg#Lora') format('svg'); /* Legacy iOS */\n}\n```\n\n```html\n<!-- __layout.svelte -->\n\n<script lang=\"ts\">\n import '/styles/fonts.css';\n</script>\n```\n\n```text\nstatic\n```\n\n```text\nstatic/fonts\n```\n\n```text\n<style>\n```\n\n```text\n__layout.svelte\n```\n\n```html\n<style>\n @font-face {\n font-family: 'Open Sans';\n font-style: normal;\n font-weight: 400;\n src: url('%sveltekit.assets%/open-sans-v27-latin-regular.woff2') format('woff2');\n }\n </style>\n```\n\n```html\n<style global>\n body {\n font-family: 'Open Sans', sans-serif;\n font-size: 14px;\n }\n</style>\n```\n\n```html\n<link rel=\"preload\" as=\"font\" href=\"%sveltekit.assets%/open-sans-v27-latin-regular.woff2\" type=\"font/woff2\" crossorigin=\"anonymous\"> \n <link rel=\"preload\" as=\"font\" href=\"%sveltekit.assets%/open-sans-v27-latin-600.woff2\" type=\"font/woff2\" crossorigin=\"anonymous\">\n```\n\n```text\nindex.html\n```\n\n```text\n@font-face {\n font-family: 'Minecraft';\n font-style: normal;\n font-weight: normal;\n src: url('$lib/fonts/minecrafttext.woff') format('woff2');\n}\n```\n\n========================================\n\nComments:\n- Works for me: svelte.dev/repl/8ea0c71d1d2043da8186909afd864aba?version=3.1‌​8.2\n- I get the feeling that local font files (vs locally installed fonts) are treated differently. For example if you had used `src: url('cIf9MaFfvUQxTTqS9C6hYQ.woff2')` with the font as a local file in the svelte directory, it wouldn't have worked. When Eddysanoli says \"where to put my woff files locally\" I assume this is what they mean. I should clarify I only meant your main solution doesn't work— the alternative you wrote certainly does work.\n- The examples above do not answer, \"where to put my woff files locally\". They are examples of using locally installed TrueType or OpenType fonts or using URLs to access fonts hosted by Google. If WOFF files are going to be hosted on the site, they need to go in the static folder. It gets more complicated if the site being deployed is not the root domain.\n- Anybody knows how to make this work with a dynamic font url. I have this project where a component displays a font. So it needs to have its own @font-face. But style tags cannot take variable interpolation afaik. I have tried to set css vars on the style tag but it does not seem to work either.\n- @Mig a stylesheet can be created dynamically with JS and inserted into the DOM. See: developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/…\n- Ah thanks @joshnuss ! I ended up doing something similar. I have realised you can create font face declarations from javascript. I did this on onMount and it works fine. Same thing really except I create a specific font face object instead of a css object.\n- If not working, then rerun dev. (`npm run dev`)\n- what folder does fonts.css go in with this example?\n- This is StackOverflow ;-)","metadata":{"transformedAt":"2026-08-18T18:33:40.668Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":206,"estimatedTokens":1487}}142{"id":"stack-64909382","source":"stackoverflow","questionId":64909382,"title":"How to print both Object key and value with Each block in Svelte?","tags":["svelte"],"text":"Title: How to print both Object key and value with Each block in Svelte?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI wanted to loop through the sections object and print out the key in `h1` and the value in `p` tag. I'm fine with enclosing this in an array.\n\n```\n\n const sections = \n {\"Title 1\": \"paragraph\",\n \"Title 2\": \"paragraph\",\n \"Title 3\": \"paragraph\",\n \"Title 4\": \"paragraph\",\n \"Title 5\": \"paragraph\"}\n\n \n{#each sections as section}\n \n\n### {title}\n\n {paragraph}\n\n{/each}\n```\n\n========================================\n\nCode:\n```svelte\n<script>\n const sections = \n {\"Title 1\": \"paragraph\",\n \"Title 2\": \"paragraph\",\n \"Title 3\": \"paragraph\",\n \"Title 4\": \"paragraph\",\n \"Title 5\": \"paragraph\"}\n</script>\n \n{#each sections as section}\n <h1>{title}</h1>\n <p>{paragraph}</p>\n{/each}\n```\n\n```text\nh1\n```\n\n```text\np\n```\n\n```svelte\n<script>\n const sections = {\n \"Title 1\": \"paragraph\",\n \"Title 2\": \"paragraph\",\n \"Title 3\": \"paragraph\",\n \"Title 4\": \"paragraph\",\n \"Title 5\": \"paragraph\"\n }\n // Object.entries() converts an Object into an array of arrays, \n // each sub array first index is the a key and the second index is a value\n // Object.entries({key: value, key:value}) => [[key, value], [key,value]]\n</script>\n\n{#each Object.entries(sections) as [title, paragraph]}\n <h1>{title}</h1>\n <p>{paragraph}</p>\n{/each}\n```\n\n========================================\n\nComments:\n- did you want something like that !! : Title 1 : paragraph Title 2 : paragraph Title 3 : paragraph Title 4 : paragraph Title 5 : paragraph\n- Yes, so for the purpose of this question I kept it simple. But it is actually a section. Think of it like posts. The heading being the post title and paragraph the post itself.","metadata":{"transformedAt":"2026-08-18T18:33:40.668Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":79,"estimatedTokens":444}}143{"id":"stack-60677782","source":"stackoverflow","questionId":60677782,"title":"How to disable Svelte warning \"Unused CSS selector\"","tags":["css","svelte"],"text":"Title: How to disable Svelte warning \"Unused CSS selector\"\nTags: css, svelte\nSource: Stack Overflow\n\nQuestion:\nThe approach of my graphic designer for formatting our Svelte application is having a systematic set of classes in LESS, importing the appropriate LESS file in the component or page, and then applying those classes wherever he needs them. As a result we have an abundant amount of unused classes, which we might use at a later point.\n\nThe great thing about Svelte is that unused CSS is not compiled, so all those (yet) redundant classes are not in the way anyway. However, whenever we compile, we get a big list of warnings: \"Unused CSS selector\". This is a major nuisance, because it makes it harder to notice when an actual error is created. Plus it just looks ugly.\n\nI checked the documentation and there is a way to suppress warnings, but that only works for the HTML part.\n\nIs there any way of getting rid of these warnings? Note that we use Svelte Preprocess.\n\n========================================\n\nTop Answer:\nI found this solution a bit smoother which I modified slightly:\n\n```\n// rollup.config.js\n...\nsvelte({\n ...\n onwarn: (warning, handler) => {\n const { code, frame } = warning;\n if (code === \"css-unused-selector\")\n return;\n\n handler(warning);\n },\n ...\n}),\n...\n```\n\n========================================\n\nCode:\n```js\n// svelte.config.js\nimport adapter from '@sveltejs/adapter-auto';\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n kit: {\n adapter: adapter()\n },\n onwarn: (warning, handler) => {\n const { code, frame } = warning;\n // console.log(code); // <= uncomment to check other warnings\n if (code === \"css_unused_selector\")\n return;\n if (code === \"a11y_invalid_attribute\")\n return;\n handler(warning);\n }\n};\nexport default config;\n```\n\n```text\ncss-unused-selector\n```\n\n```text\na11y-invalid-attribute\n```\n\n```text\nsvelte.config.js\n```\n\n```text\ncss-unused-selector\n```\n\n```text\ncss_unused_selector\n```\n\n```text\nthis.stylesheet.warn_on_unused_selectors(this);\n```\n\n```js\n// rollup.config.js\n...\nsvelte({\n ...\n onwarn: (warning, handler) => {\n const { code, frame } = warning;\n if (code === \"css-unused-selector\")\n return;\n\n handler(warning);\n },\n ...\n}),\n...\n```\n\n```js\n// rollup.config.js\n...\nconst warnIgnores = {\n 'css-unused-selector': {\n capture: /.*\"(.*)\"$/,\n ignore: [\n /^\\.p\\d+/,\n /^\\.sm\\d+/,\n /^\\.md\\d+/,\n /^\\.lg\\d+/,\n /^\\.xg\\d+/,\n /^\\.all\\d+/,\n /^\\.row(::after)?/\n ]\n }\n}\n...\nsvelte({\n ...\n // Explicitely ignore warnings\n onwarn: (warning, handler) => {\n const { message, code } = warning;\n const patterns = warnIgnores[code];\n if (patterns != undefined) {\n /* Find the meat. */\n const meat = message.match(patterns.capture);\n if (meat != null) {\n for (var i = 0; i < patterns.ignore.length; i++) {\n if (meat[1].match(patterns.ignore[i]) != null) {\n return;\n }\n }\n }\n }\n handler(warning);\n },\n ...\n});\n```\n\n```text\nexplicit\n```\n\n```text\nignore patterns\n```\n\n```js\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vitest/config';\n\nexport default defineConfig({\n plugins: [sveltekit()],\n build: {\n rollupOptions: {\n onwarn: (warning, handler) => {\n const { code, frame } = warning;\n if (code === \"anchor-is-valid\" || code === \"a11y-autofocus\") {\n return;\n }\n // or it might be css_unused_selector, depending on the vite version\n if (code === \"css-unused-selector\" && frame && frame.includes(\"shape\")) {\n return;\n }\n handler(warning);\n }\n }\n },\n test: {\n include: ['src/**/*.{test,spec}.{js,ts}']\n }\n});\n```\n\n```text\nrollup.config.js\n```\n\n```text\nvite.config.js\n```\n\n```json\n\"svelte.plugin.svelte.compilerWarnings\": {\n \"css-unused-selector\": \"ignore\",\n }\n```\n\n```js\nimport adapter from '@sveltejs/adapter-auto';\nimport { vitePreprocess } from '@sveltejs/kit/vite';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://kit.svelte.dev/docs/integrations#preprocessors\n // for more information about preprocessors\n preprocess: vitePreprocess(),\n onwarn: (warning, handler) => {\n if (warning.code === 'css-unused-selector') {\n return;\n }\n handler(warning);\n },\n kit: {\n // adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list.\n // If your environment is not supported or you settled on a specific environment, switch out the adapter.\n // See https://kit.svelte.dev/docs/adapters for more information about adapters.\n adapter: adapter()\n },\n};\n\nexport default config;\n```\n\n========================================\n\nComments:\n- github.com/sveltejs/svelte/issues/1594\n- This is the only way that actually addresses the issue, for me (which was the *massive* performance hit that I get because it's generating 1000s of warnings per file, VSCode stops autocompleting or formatting my code on save, system locks to a halt, etc). Thank you\n- You're welcome, but...check the other answer, by Fractalf. If you use Rollup, you can just take over his code suggestion for in the config file.\n- Yeah I am using rollup and tried that method. Didn't work for me. Performance was still bad.\n- Just want to mention, this works in SvelteKit the same: add the onWarn function to the \"config\" object root in svelte.config.js\n- If you use svelte as a vite plugin, this goes into `vite.config.js`\n- i think you should make a full answer how to make it with vite or sveltekit\n- Do you perhaps know how to write this kind of conditional ignoring, but to have it apply only to imported files? I would like to keep the warnings of unused selectors that come from the same component, but if I for example import my `_forms.scss` and not use one of the many form elements from it, then seeing the warning is absurd, and those are the ones I would want to ignore.\n- Not sure, but please do a `console.log` on `message` and loop for the file name. If found, modify the code to extract the filename by regex and predict it.\n- as of 2024, vite 5 and sveltekit 5 - it doesn't work. Code runs, but the css-unused-selector is never raised. also had to configure it in vite.config.js, defineConfig.build.rollupOptions.onwarn\n- You also have a duplicate `preprocess` key in your config.\n- To add: catching the text (/ message) contained in the CLI output use `warning.message.startsWith('text')`.\n- There's no way to disable it for one line?\n- For an updated version, the file should be `svelte.config.ts` and the import of `vitePreprocess` should be from `@sveltejs/vite-plugin-svelte`. And in the code, dashes need to be replaced by underscores.\n- Not sure it has always been like that, but in my current version (5) the codes have underscores, not dashes. So I have to write `css_unused_selector` instead.","metadata":{"transformedAt":"2026-08-18T18:33:40.668Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":234,"estimatedTokens":1793}}144{"id":"stack-56180458","source":"stackoverflow","questionId":56180458,"title":"ReferenceError: document is not defined in Svelte 3","tags":["svelte","sapper"],"text":"Title: ReferenceError: document is not defined in Svelte 3\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI'm trying in the `` to manually `document.createElement` and then to `appendChild` an `audio` every time an `eventListener` is called to replace it. **Everything works fine in the browser**, apart a **really quick error when the page loads but this lasts less then 100ms**. There is an error in the Terminal as well \n\n```\nReferenceError: document is not defined\n at Object (webpack:///./src/components/Record/Component.svelte?:26:17)\n```\n\nSeems that the above is called when document is not ready yet but afterwards it is fine, how to fix it? Or what is the preferred way to destroy and recreate components in Svelte world (Sapper)?\n\n========================================\n\nTop Answer:\nSapper works well with most third-party libraries you are likely to come across. However, sometimes, a third-party library comes bundled in a way which allows it to work with multiple different module loaders. Sometimes, this code creates a dependency on window, such as checking for the existence of window.global might do.\n\nSince there is no window in a server-side environment like Sapper's, the action of simply importing such a module can cause the import to fail, and terminate the Sapper's server with an error such as:\n\nReferenceError: window is not defined\n\nThe way to get around this is to use a dynamic import for your component, from within the onMount function (which is only called on the client), so that your import code is never called on the server.\n\n\r\n\r\n\n```\n\n import { onMount } from 'svelte';\n\n let MyComponent;\n\n onMount(async () => {\n const module = await import('my-non-ssr-component');\n MyComponent = module.default;\n });\n\n```\n\n========================================\n\nCode:\n```text\nReferenceError: document is not defined\n at Object (webpack:///./src/components/Record/Component.svelte?:26:17)\n```\n\n```text\n<script>\n```\n\n```text\ndocument.createElement\n```\n\n```text\nappendChild\n```\n\n```text\naudio\n```\n\n```text\neventListener\n```\n\n```html\n<script>\n import { onMount } from 'svelte';\n\n onMount(() => {\n document.createElement(...);\n \n // ...\n });\n</script>\n```\n\n```text\ndocument\n```\n\n```text\nonMount\n```\n\n```js\n<script>\n import { onMount } from 'svelte';\n\n let MyComponent;\n\n onMount(async () => {\n const module = await import('my-non-ssr-component');\n MyComponent = module.default;\n });\n</script>\n\n<svelte:component this={MyComponent} foo=\"bar\"/>\n```\n\n```text\n(async () => {\n if (somethingIsTrue) {\n const { default: myDefault, foo, bar } = await import('/modules/my-module.js');\n }\n})();\n```\n\n```text\nconst themeState = {\n active: undefined,\n selected: undefined,\n themes: [],\n}\n\nonMount(async () => {\n const { default: Themer, auto, system } = await import('themer.js')\n\n themeState = {\n active: undefined,\n selected: light,\n themes: [light, dark, auto, system],\n }\n\n const themer = new Themer({\n debug: true,\n onUpdate: (theme) => (themeState.active = theme),\n themes: { light, dark, auto, system },\n })\n\n function noThemeSupport({ theme }) {\n return theme === 'system' && !themer.themeSupportCheck()\n }\n\n function setTheme(theme) {\n themeState.selected = theme\n themer.set(theme)\n }\n\n themer.set(themeState.selected)\n})\n```\n\n```text\ntheme.js\n```\n\n```text\ntheme.js\n```\n\n```text\ntheme.js\n```\n\n```html\nlet mounted = false;\n onMount(() => {\n mounted = true;\n });\n \n // add grid\n $: if(mounted) d3.selectAll('g.yAxis g.tick')\n .append(\"line\")\n .attr(\"class\", \"gridline\")\n .attr(\"x1\", 0)\n .attr(\"y1\", 0)\n .attr(\"x2\", width_workable)\n .attr(\"y2\", 0)\n .attr(\"stroke\", \"#9ca5aecf\") // line color\n .attr(\"stroke-dasharray\",\"4\"); // make it dashed;;\n```\n\n```html\n$: d3.select(elem).selectAll('g.tick')\n .append(\"line\")\n .attr(\"class\", \"gridline\")\n .attr(\"x1\", 0)\n .attr(\"y1\", 0)\n .attr(\"x2\", width_workable)\n .attr(\"y2\", 0)\n .attr(\"stroke\", \"#9ca5aecf\") // line color\n .attr(\"stroke-dasharray\",\"4\"); // make it dashed;;\n```\n\n========================================\n\nComments:\n- Need to switch mindset to remember that initially this is all n the server.\n- if you get this error when using onDestroy, try `onMount(() => { return () => { // on destroy code }})`\n- wont it still give error ... as it will try to import d3 server side?\n- not in my case @SheeceGardazi","metadata":{"transformedAt":"2026-08-18T18:33:40.668Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":196,"estimatedTokens":1144}}145{"id":"stack-58964087","source":"stackoverflow","questionId":58964087,"title":"How to update an array after splice in Svelte?","tags":["javascript","arrays","svelte"],"text":"Title: How to update an array after splice in Svelte?\nTags: javascript, arrays, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm learning Svelte, and read in the documentation that arrays need to be reassigned in order for a component or page to update it. For that they devised a more idiomatic solution. Instead of writing:\n\n```\nmessages.push('hello');\nmessages = messages;\n```\n\nyou can write instead:\n\n```\nmessages = [...messages, 'hello'];\n```\n\nAlright, makes sense. But then the documentation says:\n\nYou can use similar patterns to replace pop, shift, unshift and splice.\n\nBut how? I cannot see how you can *remove* items from an array. More to the point, how could I write the following more idiomatically?\n\n```\nmessages.splice(messages.indexOf('hello'), 1);\nmessages = messages;\n```\n\n========================================\n\nTop Answer:\nAs mentioned, Svelte's reactivity is triggered by assignments. The current Svelte tutorial uses JavaScript's (ES6) spread syntax (three dots) to add the next-higher number to an array, providing a more idiomatic solution than a redundant assignment using `push`:\n\n```\nfunction pushNumber() { \n numbers = [...numbers, lastnumber]; // 1, 2, 3, 4, 5\n}\n```\n\nYou could use spread syntax to replace `pop`, `shift`, `unshift` and `splice`though it might increase the time and complexity of the operation in some cases:\n\n```\nfunction unshiftNumber() { \n numbers = [firstnumber, ...numbers]; // 0, 1, 2, 3, 4\n}\n\nfunction popNumber() {\n numbers = [...numbers.slice(0,numbers.length - 1)]; // 1, 2, 3\n}\n\nfunction shiftNumber() {\n numbers = [...numbers.slice(1,numbers.length)]; // 2, 3, 4\n}\n\nfunction spliceNumber() {\n numbers = [firstnumber, ...numbers.slice(0,numbers.length-1)]; // 0, 1, 2, 3\n}\n```\n\nSpread is just one way to do it, though. The purpose behind not using pop/push etc is to encourage immutability. So any removal can just be a filter, for example.\n\n========================================\n\nCode:\n```js\nmessages.push('hello');\nmessages = messages;\n```\n\n```js\nmessages = [...messages, 'hello'];\n```\n\n```js\nmessages.splice(messages.indexOf('hello'), 1);\nmessages = messages;\n```\n\n```text\nmessages = messages.filter(m => m !== 'hello');\n```\n\n```text\n'hello'\n```\n\n```text\nmessages = [...messages.splice(messages.indexOf('hello'), 1)];\n```\n\n```text\nmessages = messages.splice(messages.indexOf('hello'), 1);\n```\n\n```text\nmessages\n```\n\n```text\nmessages\n```\n\n```text\nlet\n```\n\n```text\nvar\n```\n\n```text\nconst\n```\n\n```js\nmessages.splice(messages.indexOf('hello'), 1);\nmessages = messages;\n```\n\n```js\nmessages = messages.filter(message => message !== \"hello\")\n```\n\n```js\nlet i = messages.indexOf(\"hello\"); \nmessages = [...messages.slice(0, i), ...messages.slice(i + 1)];\n```\n\n```text\n\"hello\"\n```\n\n```text\n\"hello\"\n```\n\n```text\nindexOf\n```\n\n```text\n-1\n```\n\n```text\n\"hello\"\n```\n\n```text\n\"hello\"\n```\n\n```text\npush\n```\n\n```text\n\"hello\"\n```\n\n```text\nlet messages = ['something', 'another', 'hello', 'word', 'another', 'again'];\n\nconst indexOfHello = messages.indexOf('hello');\n\nmessages = [...messages.slice(0, indexOfHello), ...messages.slice(indexOfHello + 1)];\n```\n\n```text\npush\n```\n\n```text\npop\n```\n\n```text\narray.splice(start, deleteCount, itemstoAdd, addThisToo);\n```\n\n```text\narray.slice(start, end);\n```\n\n```js\nfunction pushNumber() { \n numbers = [...numbers, lastnumber]; // 1, 2, 3, 4, 5\n}\n```\n\n```js\nfunction unshiftNumber() { \n numbers = [firstnumber, ...numbers]; // 0, 1, 2, 3, 4\n}\n\nfunction popNumber() {\n numbers = [...numbers.slice(0,numbers.length - 1)]; // 1, 2, 3\n}\n\nfunction shiftNumber() {\n numbers = [...numbers.slice(1,numbers.length)]; // 2, 3, 4\n}\n\nfunction spliceNumber() {\n numbers = [firstnumber, ...numbers.slice(0,numbers.length-1)]; // 0, 1, 2, 3\n}\n```\n\n```text\npush\n```\n\n```text\npop\n```\n\n```text\nshift\n```\n\n```text\nunshift\n```\n\n```text\nsplice\n```\n\n```js\nlet elements = ['a','b', 'c'];\nlet idx = 1;\nelements = elements.filter( (e,i) => i !== idx );\n// => ['a', 'c']\n```\n\n```text\nfilter\n```\n\n```text\nindex\n```\n\n========================================\n\nComments:\n- Svelte's reactivity is triggered by assignments. Therefore push, pop, slice etc do not work. Please use an \"=\" while assigning the values.\n- Oh, that's an elegant solution! I should actually learn all the JS array functions better to know what's possible. But yep, this will work. Thanks! :)\n- `filter()` is also ~15% faster in Chrome: jsbench.me/5uljggpmmx/1\n- hrm, this is inaccurate, the splice method modifies the array in place, and returns the deleted elements developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…\n- This is a more canonical answer and whilst the accepted answer does completely answer the question, it's more thorough and refers to idiomatic svelte...","metadata":{"transformedAt":"2026-08-18T18:33:40.668Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":38,"totalLines":252,"estimatedTokens":1184}}146{"id":"stack-74243719","source":"stackoverflow","questionId":74243719,"title":"How to change page title dynamically in Sveltekit?","tags":["svelte","sveltekit"],"text":"Title: How to change page title dynamically in Sveltekit?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm learning SvelteKit and this might be a very elementary question. But I could not figure out how to change the tab's title.\n\nIn my `src/+layout.svelte` I have:\n\n```\n\n let title=\"My Site Homepage\"\n \n \n \n \n \n \n ...\n {title}\n \n \n```\n\nThen in my `/src/faq/+page.svelte` I'd like to change the title to 'FAQ'\n\nSo I put\n\n```\n\n let title=\"FAQ\" \n\n```\n\nBut when I visit `http://localhost:5173/faq` the tab's title is not changed.\nSo I'm wondering how can I do that? Is there an idomatic way to do so?\n\n========================================\n\nTop Answer:\nInside the main `+layout.svelte` file you could use the page store:\n\n```\n\n //...\n import { page } from \"$app/stores\";\n\n const appName = \"My App\";\n $: title = [appName, ...$page.url.pathname.split(\"/\").slice(1)].filter(Boolean).join(\" - \");\n\n {title}\n\n```\n\nwill result for example in:\n\nRoute\nTitle\n\n`/`\n`My App`\n\n`/about`\n`My App - about`\n\n`/products/345`\n`My App - products - 345`\n\n========================================\n\nCode:\n```text\n<script>\n let title=\"My Site Homepage\"\n \n </script>\n <head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n ...\n <title>{title}</title>\n \n </head>\n```\n\n```text\n<script>\n let title=\"FAQ\" \n</script>\n```\n\n```text\nsrc/+layout.svelte\n```\n\n```text\n/src/faq/+page.svelte\n```\n\n```text\nhttp://localhost:5173/faq\n```\n\n```text\n<svelte:head>\n <title>FAQ</title> \n</svelte:head>\n```\n\n```text\n<head>\n```\n\n```text\n//../components/meta-title.svelte\n\n<svelte:head>\n <title>{title}</title>\n</svelte:head>\n\n<script>\n export let title = \"default title for page\"\n</script>\n\n\n//../pages/_layout.svelte\n\n<Meta title=\"This is a dynamic title\" />\n```\n\n```html\n<script>\n //...\n import { page } from \"$app/stores\";\n\n const appName = \"My App\";\n $: title = [appName, ...$page.url.pathname.split(\"/\").slice(1)].filter(Boolean).join(\" - \");\n</script>\n\n<svelte:head>\n <title>{title}</title>\n</svelte:head>\n```\n\n```text\n+layout.svelte\n```\n\n```text\n/\n```\n\n```text\nMy App\n```\n\n```text\n/about\n```\n\n```text\nMy App - about\n```\n\n```text\n/products/345\n```\n\n```text\nMy App - products - 345\n```\n\n========================================\n\nComments:\n- If you want to enforce a certain format for titles (like `Page title | Website name`) and not want to add the second bit every page you could use a store. If you just need to change the title based on what happens in the page you can just use a variable for that page.\n- I think you also need `%sveltekit.head%` in your `app.html` file, but any scaffolding should have already done that for you","metadata":{"transformedAt":"2026-08-18T18:33:40.668Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":178,"estimatedTokens":698}}147{"id":"stack-65484019","source":"stackoverflow","questionId":65484019,"title":"How can I manually compile a svelte component down to the final javascript and css that sapper/svelte produces?","tags":["server-side-rendering","svelte","sapper"],"text":"Title: How can I manually compile a svelte component down to the final javascript and css that sapper/svelte produces?\nTags: server-side-rendering, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nOur company produces an automation framework that is written in svelte/sapper. One feature is that developers can create custom ui widgets, currently using plain js/html/css and our client side api. These widgets are stored in the database and not on the file system.\n\nI think it would be a big plus to allow them to create widgets as svelte components since it contains all of the markup, js and css in one location and would give them all of the benefits of svelte's reactivity.\n\nI have gotten as far as creating an endpoint that compiles components using svelte's server API but that just seems to generate a module that is ready for rollup-plugin-svelte/sapper/babel to finish the job of producing something the browser can use.\n\nHow can I manually compile a svelte component down to the final javascript and css that sapper/svelte produces.\n\n========================================\n\nTop Answer:\nThanks to the detailed post by @rixo I was able to get this working. I basically created a rollup.widget.js like this:\n\n```\nimport json from '@rollup/plugin-json';\nimport resolve from '@rollup/plugin-node-resolve';\nimport commonjs from '@rollup/plugin-commonjs';\nimport svelte from 'rollup-plugin-svelte';\nimport path from 'path';\nimport fs from 'fs';\n\nlet basePath = path.join(__dirname, '../widgets');\nlet srcFiles = fs\n .readdirSync(basePath)\n .filter((f) => path.extname(f) === '.svelte')\n .map((m) => path.join(basePath, m));\n\nexport default {\n input: srcFiles,\n output: {\n format: 'es',\n dir: basePath,\n sourcemap: true,\n },\n plugins: [\n json(),\n svelte({\n emitCss: false,\n compilerOptions: {\n dev: false,\n },\n }),\n resolve({\n browser: true,\n dedupe: ['svelte'],\n }),\n commonjs(),\n ],\n};\n```\n\nThen generate the svelte components from the database and compile:\n\n```\nconst loadConfigFile = require('rollup/dist/loadConfigFile');\n\nfunction compile(widgets) {\n return new Promise(function (resolve, reject) {\n let basePath = path.join(__dirname, '../widgets');\n\n if (!fs.existsSync(basePath)) {\n fs.mkdirSync(basePath);\n }\n\n for (let w of widgets) {\n if (w.config.source) {\n let srcFile = path.join(basePath, w.name + '.svelte');\n fs.writeFileSync(srcFile, w.config.source);\n console.log('writing widget source file:', srcFile);\n }\n }\n\n //ripped off directly from the rollup docs\n loadConfigFile(path.resolve(__dirname, 'rollup.widgets.js'), {\n format: 'es',\n })\n .then(async ({ options, warnings }) => {\n console.log(`widget warning count: ${warnings.count}`);\n warnings.flush();\n\n for (const optionsObj of options) {\n const bundle = await rollup(optionsObj);\n await Promise.all(optionsObj.output.map(bundle.write));\n }\n\n resolve({ success: true });\n })\n .catch(function (x) {\n reject(x);\n });\n });\n}\n```\n\nAnd then consume the dynamic widget as @rixo proposed:\n\n```\n\n import { onMount, onDestroy, tick } from 'svelte';\n import Widget from '../containers/Widget.svelte';\n\n export let title = '';\n export let name = '';\n export let config = {};\n\n let component;\n let target;\n\n $: if (name) {\n loadComponent()\n .then((f) => {})\n .catch((x) => console.warn(x.message));\n }\n\n onMount(async function () {\n console.log('svelte widget mounted');\n });\n\n onDestroy(cleanup);\n\n async function cleanup() {\n if (component) {\n console.log('cleaning up svelte widget');\n component.$destroy();\n component = null;\n await tick();\n }\n }\n\n async function loadComponent() {\n await cleanup();\n let url = `/widgets/${name}.js?${parseInt(Math.random() * 1000000)}`;\n let comp = await import(url);\n component = new comp.default({\n target: target,\n props: config.props || {},\n });\n console.log('loading svelte widget component:', url);\n }\n\n \n\n```\n\nA few notes/observations:\n\n- I had much better luck using rollup/dist/loadConfigFile than trying to use rollup.rollup directly.\n\n- I went down a rabbit hole of trying to create both client and server globals for all of the svelte modules and marking them as external in the widget rollup so that everything used the same svelte internals. This ended up being a mess and gave the widgets access to more than I wanted.\n\n- If you try to embed your dynamically compiled widget in your main app with\n\n========================================\n\nCode:\n```js\nimport { onMount } from 'svelte'\nimport { readable } from 'svelte/store'\nimport { fade } from 'svelte/transition'\nimport Foo from './Foo.svelte'\n```\n\n```js\n// those ones are inescapable (bellow is just an example, you'll \n// get different imports depending on what the compiled component \n// actually does / uses)\nimport {\n SvelteComponent,\n detach,\n element,\n init,\n insert,\n noop,\n safe_not_equal,\n} from 'svelte/internal'\n```\n\n```js\nimport svelte from 'rollup-plugin-svelte'\nimport commonjs from '@rollup/plugin-commonjs'\nimport resolve from '@rollup/plugin-node-resolve'\nimport css from 'rollup-plugin-css-only'\nimport { terser } from 'rollup-plugin-terser'\n\nconst production = !process.env.ROLLUP_WATCH\n\n// include CSS in component's JS for ease of use\n//\n// set to true to get separate CSS for the component (but then,\n// you'll need to inject it yourself at runtime somehow)\n//\nconst emitCss = false\n\nconst cmp = 'Foo'\n\nexport default {\n // our widget as input\n input: `widgets/${cmp}.svelte`,\n\n output: {\n format: 'es',\n file: `public/build/widgets/${cmp}.js`,\n sourcemap: true,\n },\n\n // usual plugins for Svelte... customize as needed\n plugins: [\n svelte({\n emitCss,\n compilerOptions: {\n dev: !production,\n },\n }),\n\n emitCss && css({ output: `${cmp}.css` }),\n\n resolve({\n browser: true,\n dedupe: ['svelte'],\n }),\n commonjs(),\n production && terser(),\n ],\n}\n```\n\n```sh\nrollup --config rollup.config.Foo.js\n```\n\n```js\nconst widget = 'Foo'\nconst url = `/build/widgets/${widget}.js`\n\nconst { default: WidgetComponent } = await import(url)\n\nconst cmp = new WidgetComponent({ target, props })\n```\n\n```js\n... // same as above essentially\n\n// using Rollup's --configXxx feature to dynamically generate config\nexport default ({ configWidget: cmp }) => ({\n input: `widgets/${cmp}.svelte`,\n output: {\n ...\n file: `public/build/widgets/${cmp}.js`,\n },\n ...\n})\n```\n\n```sh\nrollup --config rollup.config.widget.js --configTarget Bar\n```\n\n```js\n...\n\nexport default {\n input: ['widgets/Foo.svelte', 'widgets/Bar.svelte', ...],\n output: {\n format: 'es',\n dir: 'public/build/widgets',\n },\n ...\n}\n```\n\n```html\n<script>\n // as we've seen, in real life, this would surely be a \n // dynamic import but whatever, you get the idea\n import Foo from '/build/widgets/Foo.js'\n</script>\n\n<!-- NO -->\n<Foo />\n\n<!-- NO -->\n<svelte:component this={Foo} />\n```\n\n```js\n...\n\nconst foo = new Foo({ target: document.querySelector('#foo') })\n\nconst bar = new Bar({ target: document.querySelector('#bar') })\n```\n\n```html\n<script>\n import { onDestroy } from 'svelte'\n\n let component\n export { component as this }\n\n let target\n let cmp\n\n const create = () => {\n cmp = new component({\n target,\n props: $$restProps,\n })\n }\n\n const cleanup = () => {\n if (!cmp) return\n cmp.$destroy()\n cmp = null\n }\n\n $: if (component && target) {\n cleanup()\n create()\n }\n\n $: if (cmp) {\n cmp.$set($$restProps)\n }\n\n onDestroy(cleanup)\n</script>\n\n<div bind:this={target} />\n```\n\n```html\n<script>\n import Widget from './Widget.svelte'\n\n const widgetName = 'Foo'\n\n let widget\n\n import(`/build/widgets/${widgetName}.js`)\n .then(module => {\n widget = module.default\n })\n .catch(err => {\n console.error(`Failed to load ${widgetName}`, err)\n })\n</script>\n\n{#if widget}\n <Widget this={widget} prop=\"Foo\" otherProp=\"Bar\" />\n{/if}\n```\n\n```text\nimport\n```\n\n```text\n.svelte\n```\n\n```text\n.js\n```\n\n```text\n.css\n```\n\n```text\nnode_modules\n```\n\n```text\nFoo.svelte\n```\n\n```text\nrollup.config.Foo.js\n```\n\n```text\npublic/build/Foo.js\n```\n\n```text\noutput.format\n```\n\n```text\nes\n```\n\n```text\nexport default ...\n```\n\n```text\nFoo\n```\n\n```text\nrollup.config.widget.js\n```\n\n```text\nsvelte\n```\n\n```text\nsvelte/*\n```\n\n```text\nrollup.config.widget-all.js\n```\n\n```text\ninput\n```\n\n```text\noutput.file\n```\n\n```text\noutput.dir\n```\n\n```text\nsvelte/internal\n```\n\n```text\nApp.svelte\n```\n\n```text\nFoo.svelte\n```\n\n```text\nFoo\n```\n\n```text\nApp\n```\n\n```text\nApp.svelte\n```\n\n```text\ndedupe: ['svelte']\n```\n\n```text\nfoo\n```\n\n```text\nbar\n```\n\n```text\nFoo\n```\n\n```text\nBar\n```\n\n```text\n<svelte:component />\n```\n\n```text\nWidget.svelte\n```\n\n```text\nsetContext\n```\n\n```text\ngetContext\n```\n\n```text\nWidget\n```\n\n```js\nimport json from '@rollup/plugin-json';\nimport resolve from '@rollup/plugin-node-resolve';\nimport commonjs from '@rollup/plugin-commonjs';\nimport svelte from 'rollup-plugin-svelte';\nimport path from 'path';\nimport fs from 'fs';\n\nlet basePath = path.join(__dirname, '../widgets');\nlet srcFiles = fs\n .readdirSync(basePath)\n .filter((f) => path.extname(f) === '.svelte')\n .map((m) => path.join(basePath, m));\n\nexport default {\n input: srcFiles,\n output: {\n format: 'es',\n dir: basePath,\n sourcemap: true,\n },\n plugins: [\n json(),\n svelte({\n emitCss: false,\n compilerOptions: {\n dev: false,\n },\n }),\n resolve({\n browser: true,\n dedupe: ['svelte'],\n }),\n commonjs(),\n ],\n};\n```\n\n```js\nconst loadConfigFile = require('rollup/dist/loadConfigFile');\n\nfunction compile(widgets) {\n return new Promise(function (resolve, reject) {\n let basePath = path.join(__dirname, '../widgets');\n\n if (!fs.existsSync(basePath)) {\n fs.mkdirSync(basePath);\n }\n\n for (let w of widgets) {\n if (w.config.source) {\n let srcFile = path.join(basePath, w.name + '.svelte');\n fs.writeFileSync(srcFile, w.config.source);\n console.log('writing widget source file:', srcFile);\n }\n }\n\n //ripped off directly from the rollup docs\n loadConfigFile(path.resolve(__dirname, 'rollup.widgets.js'), {\n format: 'es',\n })\n .then(async ({ options, warnings }) => {\n console.log(`widget warning count: ${warnings.count}`);\n warnings.flush();\n\n for (const optionsObj of options) {\n const bundle = await rollup(optionsObj);\n await Promise.all(optionsObj.output.map(bundle.write));\n }\n\n resolve({ success: true });\n })\n .catch(function (x) {\n reject(x);\n });\n });\n}\n```\n\n```html\n<script>\n import { onMount, onDestroy, tick } from 'svelte';\n import Widget from '../containers/Widget.svelte';\n\n export let title = '';\n export let name = '';\n export let config = {};\n\n let component;\n let target;\n\n $: if (name) {\n loadComponent()\n .then((f) => {})\n .catch((x) => console.warn(x.message));\n }\n\n onMount(async function () {\n console.log('svelte widget mounted');\n });\n\n onDestroy(cleanup);\n\n async function cleanup() {\n if (component) {\n console.log('cleaning up svelte widget');\n component.$destroy();\n component = null;\n await tick();\n }\n }\n\n async function loadComponent() {\n await cleanup();\n let url = `/widgets/${name}.js?${parseInt(Math.random() * 1000000)}`;\n let comp = await import(url);\n component = new comp.default({\n target: target,\n props: config.props || {},\n });\n console.log('loading svelte widget component:', url);\n }\n</script>\n<Widget name=\"{name}\" title=\"{title}\" {...config}>\n <div bind:this=\"{target}\" class=\"svelte-widget-wrapper\"></div>\n</Widget>\n```\n\n========================================\n\nComments:\n- You can use the REPL here, and click on the \"JS output\" or \"CSS output\" tab on the right. svelte.dev/repl/hello-world?version=3\n- @rixo, Wow! What an amazing writeup! I was able to remove the `svelte` & `svelte/internals` runtime by using the `external` option to rollup. Specifically, `external: ['svelte', 'svelte/internal']` Now I can late bind in the browser or in a parent bundler. Thanks again for the writeup!\n- Exactly what I was looking for. Thank you! @rixo: is there a way to listen for dispatched events on the proxy/wrapper component? The typical \"on\" directive combined with the child component's \"dispatch\" action does not work.\n- Incredible answer and extremely helpful. Thank you !\n- @rixo With svelte 5 we no longer have Class based components. do you have any notion how to implement this feature with 5? there is an active discussion in the svelte repo: github.com/sveltejs/svelte/discussions/14298\n- Also wondering if this can be achieved using esbuild. Will have a play this week and report back if I manage to get something working.\n- Interesting. I'm definitely curious to know how the esbuild approach turns out.\n- I threw up an esbuild demo at github.com/mateothegreat/svelte-dynamic-component-engine. Hope it helps everybody!","metadata":{"transformedAt":"2026-08-18T18:33:40.669Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":50,"totalLines":636,"estimatedTokens":3308}}148{"id":"stack-69321948","source":"stackoverflow","questionId":69321948,"title":"How to add a custom 404 page and a different Error page (for other errors) in SvelteKit?","tags":["svelte","sveltekit"],"text":"Title: How to add a custom 404 page and a different Error page (for other errors) in SvelteKit?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nBasically, how to do the ff. in SvelteKit:\n\n- Add a custom 404 page first.\n\n- Have a different generic Error page that will show a message/description about the error in SvelteKit\n\n========================================\n\nTop Answer:\n**December 2022 solution**\n\nas per docs: https://kit.svelte.dev/docs/advanced-routing#rest-parameters-404-pages\n\ncreate: `src/routes/[...path]/+page.js`\ncontaining:\n\n```\nimport { error } from '@sveltejs/kit';\n\nexport function load() {\n throw error(404, '/not-found whatever you want');\n}\n```\n\nalso create: `src/routes/[...path]/+error.svelte`\ncontaining (for example):\n\n```\n\n import { page } from '$app/stores';\n\n \n\n### It seems there has been an error, sorry about that.\n\n {#if $page?.error}\n \n {#if $page?.status}\n Page status: {$page?.status}\n\n {/if}\n {#if $page?.error?.message}\n Error message: {$page?.error?.message}\n\n {/if}\n \n {/if}\n\n```\n\nbtw, maybe you have some style in layouts, maybe even layout groups\nso be sure to put a layout file in the same dir to apply them, e.g.:\n\n```\nsrc/routes/[...path]/+layout.svelte\n```\n\n========================================\n\nCode:\n```text\nsrc/routes/blog/[slug]/+error.svelte\n\n<script>\n import { page } from '$app/stores';\n</script>\n\n<h1>{$page.status}: {$page.error.message}</h1>\n```\n\n```text\n<script context=\"module\">\n export function load({ error, status }) {\n return {\n props: {\n title: `${status}: ${error.message}`\n }\n };\n }\n</script>\n\n<script>\n export let title;\n</script>\n\n<h1>{title}</h1>\n```\n\n```text\n<script context=\"module\">\n export function load({ error, status }) {\n return {\n props: {\n message: error.message,\n status // same as status: status\n }\n };\n }\n</script>\n\n<script>\n import ErrorScreen from '../components/screens/ErrorScreen.svelte'; // your own Error screen component\n import NotFoundScreen from '../components/screens/NotFoundScreen.svelte'; // your own 404 screen component\n\n export let message;\n export let status;\n</script>\n\n{#if status == 404} <!-- Used '==' instead of '===' to match string/number status code (just to be sure) -->\n <NotFoundScreen />\n{:else}\n <ErrorScreen {message} {status} />\n{/if}\n```\n\n```text\nload\n```\n\n```text\n+error.svelte\n```\n\n```text\nsrc/routes/blog/+error.svelte\n```\n\n```text\nsrc/routes/+error.svelte\n```\n\n```text\n__error.svelte\n```\n\n```text\nprops\n```\n\n```text\nload\n```\n\n```text\n#if status == 404\n```\n\n```text\n#if status == 500\n```\n\n```text\n404\n```\n\n```text\nimport { error } from '@sveltejs/kit';\n\nexport function load() {\n throw error(404, '/not-found whatever you want');\n}\n```\n\n```text\n<script>\n import { page } from '$app/stores';\n</script>\n\n<div>\n <h1>It seems there has been an error, sorry about that.</h1>\n {#if $page?.error}\n <div class=\"mt-4 p-4 border-y-2\">\n {#if $page?.status}\n <p>Page status: {$page?.status}</p>\n {/if}\n {#if $page?.error?.message}\n <p>Error message: {$page?.error?.message}</p>\n {/if}\n </div>\n {/if}\n</div>\n```\n\n```text\nsrc/routes/[...path]/+layout.svelte\n```\n\n```text\nsrc/routes/[...path]/+page.js\n```\n\n```text\nsrc/routes/[...path]/+error.svelte\n```\n\n========================================\n\nComments:\n- You can also start by copying the default sveltekit error page `node_modules/@sveltejs/kit/assets/components/error.svelte` to `src/layouts/__error.svelte` and then customize it.\n- You need to include status in ErrorScreen also, otherwise: Property 'status' is missing in type '{ message: any; }' but required in type '{ message: any; status: any; }'\n- Is there a way to print the entire trace? For example, on which line number/file the error occurs, etc?\n- @vphilipnyc yes, that's possible. \"error\" (in the load function) has a property named \"stack\". So when you add it to the \"prop\" object, you can use it in your template.\n- gpt4o is still recommending this outdated solution :)\n- @Christian yeh..","metadata":{"transformedAt":"2026-08-18T18:33:40.669Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":209,"estimatedTokens":1043}}149{"id":"stack-56891190","source":"stackoverflow","questionId":56891190,"title":"How to trigger/force update a Svelte component","tags":["svelte"],"text":"Title: How to trigger/force update a Svelte component\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI am trying to get my head around the svelte 3 reactivity thing...\n\nI wanted to force refreshing a UI on a button click. I am using a custom component `AsyncFetcher` that accepts HTTP post data, and returns `data` object (http post result) for its slot.\n\nI wanted to have a disable functionality. So when the \"Disable\" button is clicked an http api is called followed by a refresh of the data view.\n\n```\n\n export let id\n\n function onDisable() {\n fetch('disable-api-url', {id: id})\n // Then ??\n // What to do after the fetch call, to refresh the view\n }\n\n {data.name}\n\n Refresh\n Disable Item\n\n```\n\nI tried doing `on:click={() => id=id}` to trick it to refresh to no avail. If `id` would have been an object rather than string `id={...id}` would have worked, which unfortunately, is not the case here.\n\nWhat would be a correct way to achieve this?\n\n========================================\n\nTop Answer:\nWhile Rich Harris gives a completely serviceable answer, here's a solution for forcing Svelte to update a component to reflect **an external change** of its data (also posted here).\n\n**main.js**; vanilla from the examples online, no special changes:\n\n```\nimport App from './App.svelte';\n\nvar app = new App({\n target: document.body\n});\n\nexport default app;\n```\n\n**index.html**; Note `window.neek = {...}`:\n\n```\n\n Svelte app\n \n window.neek = { nick: true, camp: { bell: \"Neek\" }, counter: 0 };\n \n \n\n```\n\n**App.svelte**; Note `$: notneek = window.neek` and `window.neek.update = ...`:\n\n```\n\n let name = 'world';\n $: notneek = window.neek;\n\n function handleClick() {\n notneek.counter += 1;\n }\n\n window.neek.update = function () {\n notneek = notneek;\n }\n\n### Hello { notneek.camp.bell }!\n\n Clicked {notneek.counter} {notneek.counter === 1 ? 'time' : 'times'}\n\n```\n\nSince the `update` function is within the scope of `App.svelte`, it is able to force the re-render when called via `window.neek.update()`. This setup uses `window.neek.counter` for the internal data utilized by the button (via `notneek.counter`) and allows for the deep properties (e.g. `neek.camp.bell = \"ish\"`) to be updated outside of the component and reflected once `neek.update()` is called.\n\nIn the console, type `window.neek.camp.bell = \"Bill\"` and note that `Hello Neek!` has not been updated. Now, type `window.neek.update()` in the console and the UI will update to `Hello Bill!`.\n\nBest of all, you can be as granular as you want within the `update` function so that only the pieces you want to be synchronized will be.\n\n========================================\n\nCode:\n```html\n<script>\n export let id\n\n function onDisable() {\n fetch('disable-api-url', {id: id})\n // Then ??\n // What to do after the fetch call, to refresh the view\n }\n</script>\n\n<AsyncFetcher postParam={id} let:data>\n {data.name}\n\n <button on:click={??}>Refresh</button>\n <button on:click={onDisable}>Disable Item</button>\n</AsyncFetcher>\n```\n\n```text\nAsyncFetcher\n```\n\n```text\ndata\n```\n\n```text\non:click={() => id=id}\n```\n\n```text\nid\n```\n\n```text\nid={...id}\n```\n\n```html\n<script>\n import { onMount } from 'svelte';\n\n let initialData;\n let otherData;\n\n onMount(async () => {\n const res = await fetch('some-url');\n initialData = await res.json();\n });\n\n async function update() {\n const res = await fetch('some-other-url');\n otherData = await res.json();\n }\n</script>\n\n{#if initialData}\n <p>the data is {initialData.something}</p>\n{/if}\n\n<button on:click={update}>update</button>\n```\n\n```text\nonMount\n```\n\n```text\nimport App from './App.svelte';\n\nvar app = new App({\n target: document.body\n});\n\nexport default app;\n```\n\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <title>Svelte app</title>\n <script>\n window.neek = { nick: true, camp: { bell: \"Neek\" }, counter: 0 };\n </script>\n <script defer src='/build/bundle.js'></script>\n</head>\n<body>\n</body>\n</html>\n```\n\n```text\n<script>\n let name = 'world';\n $: notneek = window.neek;\n\n function handleClick() {\n notneek.counter += 1;\n }\n\n window.neek.update = function () {\n notneek = notneek;\n }\n</script>\n\n<h1>Hello { notneek.camp.bell }!</h1>\n\n<button on:click={handleClick}>\n Clicked {notneek.counter} {notneek.counter === 1 ? 'time' : 'times'}\n</button>\n```\n\n```text\nwindow.neek = {...}\n```\n\n```text\n$: notneek = window.neek\n```\n\n```text\nwindow.neek.update = ...\n```\n\n```text\nupdate\n```\n\n```text\nApp.svelte\n```\n\n```text\nwindow.neek.update()\n```\n\n```text\nwindow.neek.counter\n```\n\n```text\nnotneek.counter\n```\n\n```text\nneek.camp.bell = \"ish\"\n```\n\n```text\nneek.update()\n```\n\n```text\nwindow.neek.camp.bell = \"Bill\"\n```\n\n```text\nHello Neek!\n```\n\n```text\nwindow.neek.update()\n```\n\n```text\nHello Bill!\n```\n\n```text\nupdate\n```\n\n```html\n<script>\n function sleep(millisec = 0) {\n return new Promise((resolve, reject) => {\n setTimeout(_ => resolve(), millisec);\n });\n };\n let result = '';\n async function runBenchmark() {\n for (let step = 0; step < 10; step++) {\n\n // this needs 100% cpu, so no time for svelte render\n cpuburn(); result += `${step}: 1.234 sec\\n`;\n\n // unblock the JS event loop, so svelte can render\n await sleep(10);\n }\n }\n</script>\n\n<pre>{result}</pre>\n```\n\n```text\nawait sleep(10)\n```\n\n```text\n$$svelte.forceTickSync()\n```\n\n```text\n<script>\n // Await immediately resolved promise to react to value change.\n const forceUpdate = async (_) => {};\n let doRerender = 0;\n</script>\n{#await forceUpdate(doRerender) then _}\n <ForcedToRerender on:click={() => doRerender++} />\n{/await}\n```\n\n```text\n<script>\n import ForcedToRerender from './ForcedToRerender.svelte'\n let visible = true\n let rerender = () =>\n {\n visible=false\n setTimeout(()=>{visible = true}, 100)\n }\n</script>\n{#if visible}\n <ForcedToRerender />\n{/if}\n<button on:click={rerender}>Rerender</button>\n```\n\n```text\n<script>\n import { onMount } from 'svelte'\n let num = 0\n let rnd = () => num = Math.random()\n onMount(rnd)\n</script>\n<div on:click={rnd}>\n {num}\n</div>\n```\n\n```html\n<script>\n async function fetchData() {\n const res = await fetch('/api')\n const data = await res.json()\n\n if (res.ok) {\n return data\n } else {\n throw new Error(data)\n }\n }\n</script>\n\n<style>\n .error {\n color: red;\n }\n</style>\n\n{#await fetchData}\n <p>Fetching...</p>\n{:then data}\n <div>{JSON.stringify(data)}</div>\n{:catch error}\n <div class=\"error\">{error.message}</div>\n{/await}\n```\n\n```html\n<script>\n async function fetchData() {\n const res = await fetch('/api')\n const data = await res.json\n\n if (res.ok) {\n return data\n } else {\n throw new Error(data)\n }\n }\n\n let promise = fetchData()\n</script>\n\n<style>\n .error {\n color: red;\n }\n</style>\n\n<button on:click=\"{() => {promise = fetchdata()}}\">Refresh</button>\n\n{#await promise}\n <p>Fetching...</p>\n{:then data}\n <div>{JSON.stringify(data)}</div>\n{:catch error}\n <div class=\"error\">{error.message}</div>\n{/await}\n```\n\n```text\n{#key category_on}\n<Testone a={category_on} />\n{/key}\n```\n\n```text\n{#key value_to_watch}\n```\n\n```text\ncategory_on\n```\n\n```text\n<Testone/>\n```\n\n```js\nLastUpdate: number = $state(0);\n OnPropertyChanged() {\n this.LastUpdate = Date.now()\n }\n```\n\n```js\nfunction(){\n ... \n sub.OnPropertyChanged() ;\n ...\n }\n```\n\n```html\n{#key sub.LastUpdate}\n<Content ...\n{/key}\n```\n\n========================================\n\nComments:\n- This worked perfectly for my use case. I had a list of items and I wanted to do something on a ctrl+click, but on OSX that brings up a context menu, so I had to use `on:contextmenu|preventDefault` but then my UI did not update, even though the state was being set. Using this and adding a `doRerender++` to my contextmenu handler works perfectly.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Wow! this was an awesome answer. I just refactored my code from onMount() to this and it worked right away. Such a more beautiful solution. Thank you!\n- Interesting. What if I want to trigger the key from a deeply nested component on page.svelte? Should I use setContext / getContext?","metadata":{"transformedAt":"2026-08-18T18:33:40.669Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":41,"totalLines":443,"estimatedTokens":2141}}150{"id":"stack-71091332","source":"stackoverflow","questionId":71091332,"title":"What is the difference between set() and update() method in Svelte Store?","tags":["svelte","svelte-store"],"text":"Title: What is the difference between set() and update() method in Svelte Store?\nTags: svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI'm new to Svelte Store. Here in svelte tutorial, they used `update()` method in `` and `` components to update value. But in ``, they used `set()` method to reset value. What exactly is the difference between `update()` and `set()` method in svelte store?\n\n========================================\n\nCode:\n```text\nupdate()\n```\n\n```text\n<Incrementer/>\n```\n\n```text\n<Decrementer/>\n```\n\n```text\n<Resetter/>\n```\n\n```text\nset()\n```\n\n```text\nupdate()\n```\n\n```text\nset()\n```\n\n```text\nset\n```\n\n```text\nupdate\n```\n\n```text\nupdate\n```\n\n```text\nupdate\n```\n\n```text\nsubscribe\n```\n\n```text\nset\n```\n\n```text\n$store = value\n```\n\n```text\nset\n```\n\n========================================\n\nComments:\n- `So you can use update if the next value should be dependent on the current value` => this line answers my question. Thanks.\n- But then you could use update in every case, why set() even exists?\n- @Knemay `set` is simpler than `update`, you do not need to pass a function.\n- this help me understands set and update. Basically they are the same, use as you like haha","metadata":{"transformedAt":"2026-08-18T18:33:40.669Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":77,"estimatedTokens":298}}151{"id":"stack-58362558","source":"stackoverflow","questionId":58362558,"title":"Is there a convenient way to reference a DOM element in Svelte components?","tags":["javascript","html","svelte"],"text":"Title: Is there a convenient way to reference a DOM element in Svelte components?\nTags: javascript, html, svelte\nSource: Stack Overflow\n\nQuestion:\nI am used to libs/frameworks like React or Angular which both have convenient ways to access actual DOM elements that belong to logical components. React has the `createRef` utility and Angular has among other things the template variables in combination with eg. `@ViewChild`. \n\nThose references not only make it easy to access the DOM without querying the elements explicitly every time , they also stay up to date with the DOM so that they always hold reference to the current element. I just started with Svelte for my pet project but although I went through Svelte's documentation and google a lot, I didn't find anything similar in concept & usage. I suppose it might have something to do with the Svelte's runtime-less concept, but still don't know why there wouldn't be such a utility. \n\nSo the question is, is there a similar utility in Svelte?\n\n========================================\n\nCode:\n```text\ncreateRef\n```\n\n```text\n@ViewChild\n```\n\n```html\n<script>\n import { onMount } from 'svelte';\n\n let myInput;\n\n onMount(() => {\n myInput.value = 'Hello world!';\n });\n</script>\n\n<input type=\"text\" bind:this={myInput}/>\n```\n\n```html\n<script>\n import { onMount } from 'svelte';\n\n let myInput;\n\n function MyInput (node) {\n myInput = node;\n myInput.value = 'Hello world!';\n }\n</script>\n\n<input type=\"text\" use:MyInput/>\n```\n\n```text\nbind:this\n```\n\n```text\nuse:action\n```\n\n========================================\n\nComments:\n- @skyboyer i think you pasted wrong URL. I'm guessing it should be this one: svelte.dev/tutorial/bind-this\n- Yes, that's exactly what I was looking for. Thank you guys!\n- I think `use:action` is what you're after svelte.dev/docs#use_action\n- @SuperUberDuper it's not wrong, but by using Svelte's bindings (especially when you don't need to access DOM element, just value, e.g., `bind:value={myInputValue}`) you get two-way value changes, without having to implement them yourself. Compiler will take care of keeping them up-to-date for you.\n- Both are pretty slick ;)\n- this doesn't seem to work anymore.\n- thanks @chovy! I updated version numbers in REPL links, it should work again now.","metadata":{"transformedAt":"2026-08-18T18:33:40.669Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":69,"estimatedTokens":577}}152{"id":"stack-62405066","source":"stackoverflow","questionId":62405066,"title":"Is there a way to declare props as optional in Svelte","tags":["javascript","svelte"],"text":"Title: Is there a way to declare props as optional in Svelte\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI have created some components which take an optional prop like `hide={true}`. My problem is that these annoying error messages always flood my console when I don't pass that prop:\n\n```\n was created without expected prop 'hide'\n```\n\nIs there some way to declare the props as optional?\n\n========================================\n\nTop Answer:\nIn some cases you don't want a default value so it's better to make the default `null`.\n\n### MyComponent.svelte\n\n```\n\n export let myProp = null // Default value is null\n\n{#if myProp }\nHas Prop: {myProp}\n{:else}\nNo Prop\n{/if}\n\n```\n\n### App.svelte\n\n```\n\n```\n\n### Result\n\n```\nNo Prop\n\nHas Propyep\n\n```\n\n### Update for Svelte 5 (3/7/24)\n\nIn Svelte 5 you declare your props with Runes like this:\n\n```\nlet {hide} = $props(); // hide is undefined\n```\n\n**For defaults:**\n\n```\nlet {hide=true} = $props();\n```\n\n**With types you could do something like this:**\n\n```\ninterface ComponentProps {\n optional?: boolean;\n optionalWithDefault?: boolean;\n required: boolean;\n}\nlet {optional, optionalWithDefault = true, required} = $props();\n```\n\n========================================\n\nCode:\n```text\n<MyComponent> was created without expected prop 'hide'\n```\n\n```text\nhide={true}\n```\n\n```html\n<script>\n export let i = 123 // Default value is now 123\n</script>\n\n<!-- Output is \"i = 123\" -->\n<p>i = {i}</p>\n```\n\n```html\n<script>\n import MyComponent from './MyComponent.svelte'\n</script>\n\n<!-- No error here! -->\n<MyComponent/>\n```\n\n```text\nexport let hide\n```\n\n```text\nexport let hide = false\n```\n\n```html\n<script>\n export let myProp = null // Default value is null\n</script>\n\n<div class:has-some-prop={myProp}>\n{#if myProp }\nHas Prop: {myProp}\n{:else}\nNo Prop\n{/if}\n</div>\n```\n\n```html\n<MyComponent/>\n<MyComponent myProp='yep'/>\n```\n\n```html\n<div>No Prop</div>\n\n<div class:has-some-prop>\nHas Prop<span>yep</span>\n</div>\n```\n\n```js\nlet {hide} = $props(); // hide is undefined\n```\n\n```js\nlet {hide=true} = $props();\n```\n\n```text\ninterface ComponentProps {\n optional?: boolean;\n optionalWithDefault?: boolean;\n required: boolean;\n}\nlet {optional, optionalWithDefault = true, required} = $props<ComponentProps>();\n```\n\n```text\nnull\n```\n\n========================================\n\nComments:\n- Yeah, I also thought of that workaround. Seems to be the only way currently.\n- I don't see that as a workaround. See, you have a component that expects a property (and does not have a default) and you don't pass one. Then you have a good chance that the app will not work correctly. Each component should define defaults for the properties and work even if none as passed. If you can't assign default values to properties, then check those error messages for missing props or throw an error is component is mounted without a required prop.\n- Correct — it's not a workaround, it's *how it's designed to work*\n- Ok, if that was the intention then I will declare default props in the future. Thanks for the explanation.\n- In the particular case of classes, aside from using null, you can also assign a default value of an empty string ('').","metadata":{"transformedAt":"2026-08-18T18:33:40.669Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":165,"estimatedTokens":794}}153{"id":"stack-59027947","source":"stackoverflow","questionId":59027947,"title":"How to have a conditional attribute in Svelte 3?","tags":["html","svelte","svelte-3","svelte-component"],"text":"Title: How to have a conditional attribute in Svelte 3?\nTags: html, svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nIs there a simpler way to write the following checkbox component:\n\n```\n\n export let disabled = false;\n\n{#if disabled}\n \n \n \n \n{:else}\n \n \n \n \n{/if}\n```\n\nHaving `` is not acceptable because Bulma have a CSS class `.checkbox[disabled]`.\n\n========================================\n\nCode:\n```text\n<script>\n export let disabled = false;\n</script>\n\n{#if disabled}\n <label class=\"checkbox\" disabled>\n <input type=\"checkbox\" {disabled} />\n <slot></slot>\n </label>\n{:else}\n <label class=\"checkbox\">\n <input type=\"checkbox\" {disabled} />\n <slot></slot>\n </label>\n{/if}\n```\n\n```text\n<label disabled=\"false\">\n```\n\n```text\n.checkbox[disabled]\n```\n\n```html\n<label class=\"checkbox\" disabled={disabled || null}>\n <input type=\"checkbox\" {disabled} />\n <slot></slot>\n</label>\n```\n\n```html\n<input required={false} placeholder=\"This input field is not required\">\n<div title={null}>This div has no title attribute</div>\n```\n\n```text\ndisabled || null\n```\n\n```text\ndisabled || undefined\n```\n\n```text\nnull\n```\n\n```text\nundefined\n```\n\n========================================\n\nComments:\n- found this article which can be helpful\n- The `autofocus` in Svelte only works when it has no value - not even an empty string or true / false can be. How to solve it? What it comes from?\n- `attributes are included unless their value is nullish (null or undefined).` is a really useful way to toggle attributes","metadata":{"transformedAt":"2026-08-18T18:33:40.669Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":89,"estimatedTokens":383}}154{"id":"stack-70446474","source":"stackoverflow","questionId":70446474,"title":"How to set vite (preview) production port?","tags":["reactjs","vue.js","svelte","vite"],"text":"Title: How to set vite (preview) production port?\nTags: reactjs, vue.js, svelte, vite\nSource: Stack Overflow\n\nQuestion:\nI have been looking arround on how to set a production port for vite but I can't find way\nI have tried this vite js config\n\n```\nserver: {\n host: true,\n },\n preview:{\n port:5005\n }\n```\n\nbut it seems like it can't work\n\n========================================\n\nTop Answer:\nIn package.json, add this code\n\n```\n\"scripts\": {\n \"serve\": \"vite --port 8000\"\n},\n```\n\nIn terminal, run the command\n\n```\nnpm run serve\n```\n\n========================================\n\nCode:\n```js\nserver: {\n host: true,\n },\n preview:{\n port:5005\n }\n```\n\n```js\nexport default defineConfig({\n server: {\n port: 3030\n },\n preview: {\n port: 8080\n }\n})\n```\n\n```js\n\"scripts\": {\n \"serve\": \"vite preview --port 6000\"\n },\n```\n\n```text\n--port\n```\n\n```text\npackage.json\n```\n\n```text\n\"scripts\": {\n \"serve\": \"vite --port 8000\"\n},\n```\n\n```text\nnpm run serve\n```\n\n```text\n\"dev\": \"vite --port=8080\"\n```\n\n========================================\n\nComments:\n- You use `server.host` instead of `server.port`. I know this is old, but noone mentioned this before.. Maybe it helps somebody with the same trouble :)\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:40.669Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":92,"estimatedTokens":371}}155{"id":"stack-74805197","source":"stackoverflow","questionId":74805197,"title":"How to redirect to page in SvelteKit?","tags":["http-redirect","svelte","sveltekit"],"text":"Title: How to redirect to page in SvelteKit?\nTags: http-redirect, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a page with content rendered from a SvelteKit store. If the store is invalid, a user needs do be redirected to the homepage. Unfortunately, I can't find a way to redirect a user even without checking any conditions, so let's focus on a simpler question: **how to always redirect from somepage to homepage?**\n\nI have tried the following, none of this works for me:\n\n- Using `` before script tag on the page as follows:\n\n```\n\n export async function load() {\n return {\n status: 302,\n redirect: \"/\"\n };\n }\n\n```\n\n- Using PageLoad in +page.js file:\n\n```\n/** @type {import('./$types').PageLoad} */\nexport function load() {\n return {\n status: 302,\n redirect: '/'\n };\n}\n```\n\nWhen I use the code mentioned above, the website works as if nothing was changed, I get no errors, but the redirection does not happen. If I get to the page unexpectedly (type it's address in the search bar, the store is not ready), I get redirected to the error page, because an error happens (which I want to prevent by homepage redirection). If I get to the page expectedly (the store is fine), the page gets rendered normally, no redirect happens.\n\n========================================\n\nTop Answer:\nBased on the documentation page you would use goto(theurl). Example:\n\n```\nimport { goto } from '$app/navigation';\n// ...Your other imports\n \ngoto('/redirectpage');\n```\n\nOr if you prefer using native approach, then in file **.svelte** you would do this,\n\nIf you are **not using** SSR then this:\n\n```\nwindow.location.href = '/redirectpage';\n```\n\nOr if you are **using** SSR then this:\n\n```\nimport { browser } from '$app/environment';\n// ...Your other imports\n \nif (browser) { // to prevent error window is not defined, because it's SSR\n window.location.href = '/redirectpage';\n}\n```\n\n========================================\n\nCode:\n```text\n<script context=\"module\">\n export async function load() {\n return {\n status: 302,\n redirect: \"/\"\n };\n }\n</script>\n```\n\n```text\n/** @type {import('./$types').PageLoad} */\nexport function load() {\n return {\n status: 302,\n redirect: '/'\n };\n}\n```\n\n```text\n<script context=\"module\">\n```\n\n```js\nimport { redirect } from '@sveltejs/kit';\n \nexport function load() {\n // ...\n redirect(302, '/'); // needs `throw` in v1\n}\n```\n\n```text\ngoto\n```\n\n```js\nimport { goto } from '$app/navigation';\n// ...Your other imports\n \ngoto('/redirectpage');\n```\n\n```js\nwindow.location.href = '/redirectpage';\n```\n\n```js\nimport { browser } from '$app/environment';\n// ...Your other imports\n \nif (browser) { // to prevent error window is not defined, because it's SSR\n window.location.href = '/redirectpage';\n}\n```\n\n```text\n// src/routes/page-to-redirect/+page.server.ts\n\nimport { redirect } from '@sveltejs/kit';\n\nexport function load() {\n throw redirect(302, '/redirect-to-this-url');\n}\n```\n\n```text\n+page.server.ts\n```\n\n========================================\n\nComments:\n- Yes but what if I want to do it outside of the load function? Eg, in a `+page.svelte` file\n- Note, for sveltekit 2.0 you can just use `redirect(302, '/');`, no need to throw anything anymore.\n- Note, for sveltekit 2.0 you can just use `redirect(302, '/');`, no need to throw anything anymore.","metadata":{"transformedAt":"2026-08-18T18:33:40.669Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":148,"estimatedTokens":841}}156{"id":"stack-61089042","source":"stackoverflow","questionId":61089042,"title":"Using Svelte, how can I escape curly braces in the HTML?","tags":["svelte"],"text":"Title: Using Svelte, how can I escape curly braces in the HTML?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI want to be able to show a code example in my Svelte component, but the example has curly braces, i.e\n\n```\n\n//no JS needed\n\nHere's a sample function\n\n`function test(e) {\n console.log(e)\n }\n````\n\nNotice how the function has curly braces? That seems to be confusing the Svelte compiler. Is there a way to escape those other than this?\n\n```\n\n//no JS needed\n\nHere's a sample function\n\n`function test(e) {'{'}\n console.log(e)\n {'}'}\n````\n\n========================================\n\nCode:\n```text\n<script>\n//no JS needed\n</script>\n\n<p>Here's a sample function</p>\n<pre><code>\n function test(e) {\n console.log(e)\n }\n</code></pre>\n```\n\n```text\n<script>\n//no JS needed\n</script>\n\n<p>Here's a sample function</p>\n<pre><code>\n function test(e) {'{'}\n console.log(e)\n {'}'}\n</code></pre>\n```\n\n```svelte\n<h3>Escaping every curly brace</h3>\n<pre><code>\n function test(e) {'{'}\n console.log(e)\n {'}'}\n</code></pre>\n\n\n<h3>Wrapping the whole code block in a string literal</h3>\n<pre><code>\n {`\n function test(e) {\n console.log(e)\n }\n `}\n</code></pre>\n\n\n<h3>Using { and }</h3>\n<pre><code>\n function test(e) {\n console.log(e)\n }\n</code></pre>\n```\n\n```text\n{'{'}\n```\n\n```text\n{'}'}\n```\n\n```text\n{\n```\n\n```text\n}\n```\n\n```text\n{\n```\n\n```text\n}\n```\n\n```text\n{\n```\n\n```text\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.669Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":118,"estimatedTokens":362}}157{"id":"stack-56083580","source":"stackoverflow","questionId":56083580,"title":"Svelte: Is there a way to make global css variables in scope of svelte components?","tags":["css","css-variables","svelte"],"text":"Title: Svelte: Is there a way to make global css variables in scope of svelte components?\nTags: css, css-variables, svelte\nSource: Stack Overflow\n\nQuestion:\nI have set my global.css file which I import in index.js\n\n```\n--root {\n --main-color: red;\n}\n* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n```\n\nindex.js\n\n```\nimport \"./global.css\";\nimport App from \"./App.svelte\";\n\nconst app = new App({\n target: document.body\n});\n```\n\nMy webpack setup\n\n```\nconst path = require(\"path\");\nconst HtmlWebpackPlugin = require(\"html-webpack-plugin\");\nconst ExtractTextPlugin = require(\"extract-text-webpack-plugin\");\n\nmodule.exports = {\n entry: \"./src/index.js\",\n output: {\n filename: \"bundle.js\",\n path: path.resolve(__dirname, \"dist\")\n },\n module: {\n rules: [\n {\n test: /\\.(html|svelte)$/,\n exclude: /node_modules/,\n use: {\n loader: \"svelte-loader\",\n options: {\n emitCss: true,\n hotReload: true\n }\n }\n },\n {\n test: /\\.css$/,\n use: ExtractTextPlugin.extract({\n fallback: { loader: \"style-loader\", options: { sourceMap: true } },\n use: [\n { loader: \"css-loader\", options: { sourceMap: true } },\n {\n loader: \"postcss-loader\",\n options: {\n sourceMap: true,\n ident: \"postcss\",\n plugins: loader => [\n require(\"postcss-import\")({}),\n require(\"postcss-preset-env\")(),\n require(\"cssnano\")()\n ]\n }\n }\n ]\n })\n }\n ]\n },\n plugins: [new HtmlWebpackPlugin(), new ExtractTextPlugin(\"styles.css\")]\n};\n```\n\nWorks perfect for setting up global css for the entire app. But I am trying to use the --main-color in my svelte components. Is there a way to inject them down to all the components' css ? \n\nSince I import global.css first, it should work as it emits a file with --root{} first then rest of the component styles.\n\n========================================\n\nTop Answer:\nYou can place global styles under `/routes/index.svelte` file, like the example below:\n\n```\n\n :global(:root){\n --header-color: purple\n }\n\n```\n\nAnd simply use it anywhere like normally how you use CSS variables like so:\n\n```\nh1 {\n color: var(--header-color);\n }\n```\n\n========================================\n\nCode:\n```css\n--root {\n --main-color: red;\n}\n* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n```\n\n```js\nimport \"./global.css\";\nimport App from \"./App.svelte\";\n\nconst app = new App({\n target: document.body\n});\n```\n\n```js\nconst path = require(\"path\");\nconst HtmlWebpackPlugin = require(\"html-webpack-plugin\");\nconst ExtractTextPlugin = require(\"extract-text-webpack-plugin\");\n\nmodule.exports = {\n entry: \"./src/index.js\",\n output: {\n filename: \"bundle.js\",\n path: path.resolve(__dirname, \"dist\")\n },\n module: {\n rules: [\n {\n test: /\\.(html|svelte)$/,\n exclude: /node_modules/,\n use: {\n loader: \"svelte-loader\",\n options: {\n emitCss: true,\n hotReload: true\n }\n }\n },\n {\n test: /\\.css$/,\n use: ExtractTextPlugin.extract({\n fallback: { loader: \"style-loader\", options: { sourceMap: true } },\n use: [\n { loader: \"css-loader\", options: { sourceMap: true } },\n {\n loader: \"postcss-loader\",\n options: {\n sourceMap: true,\n ident: \"postcss\",\n plugins: loader => [\n require(\"postcss-import\")({}),\n require(\"postcss-preset-env\")(),\n require(\"cssnano\")()\n ]\n }\n }\n ]\n })\n }\n ]\n },\n plugins: [new HtmlWebpackPlugin(), new ExtractTextPlugin(\"styles.css\")]\n};\n```\n\n```text\n:root{}\n```\n\n```text\n--root{}\n```\n\n```text\n<style>\n :global(:root){\n --header-color: purple\n }\n</style>\n```\n\n```text\nh1 {\n color: var(--header-color);\n }\n```\n\n```text\n/routes/index.svelte\n```\n\n========================================\n\nComments:\n- Didn't you mean \":root\" in the selector? I've never seen a \"--root\" selector.\n- Please make your answer a bit more descriptive next time\n- which file is the \"main component\"? App.svelte?\n- is there a way to pass a var() to :global() from child to parent? I am asking here if you know tell me stackoverflow.com/questions/73848397/… thank you\n- do we get intellisense for those variables?","metadata":{"transformedAt":"2026-08-18T18:33:40.669Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":215,"estimatedTokens":1059}}158{"id":"stack-61303237","source":"stackoverflow","questionId":61303237,"title":"How to set dynamic html tag according to props in Svelte","tags":["javascript","svelte","svelte-3"],"text":"Title: How to set dynamic html tag according to props in Svelte\nTags: javascript, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI'm creating a `Heading` component in `svelte` as a part of learning the basics of this framework. The component behavior is pretty straight-forward. \n\nThe component will have a prop named `level`, which will render the appropriate `` tag accordingly.\n\nFor eg. \n\n```\n would render \n\n### content\n\n \n would render \n\n### content\n\n```\n\nI can achieve this currently with,\n\n```\n\n export let level = 3;\n\n{#if level === 1}\n \n \n \n{:else if level === 2}\n \n \n \n{:else if level === 3}\n \n \n \n{:else if level === 4}\n \n \n \n{:else if level === 5}\n \n \n \n{/if}\n```\n\nBut this kind of feels like a very naive approach. \nIs there any better way to achieve this behaviour in `svelte ?`\n\n========================================\n\nTop Answer:\nSvelte has native support for this starting with 3.47.0, using the `svelte:element` tag. Examples:\n\n```\nthis will be rendered as a top-level heading\n\nwill render the element named in 'tag'\n\nwill not render for falsey values\n```\n\nSee the docs or the tutorial for more details.\n\n========================================\n\nCode:\n```text\n<Heading level={3}> would render <h3>content</h3> \n<Heading level={1}> would render <h1>content</h1>\n```\n\n```text\n<script>\n export let level = 3;\n</script>\n\n{#if level === 1}\n <h1>\n <slot></slot>\n </h1>\n{:else if level === 2}\n <h2>\n <slot></slot>\n </h2>\n{:else if level === 3}\n <h3>\n <slot></slot>\n </h3>\n{:else if level === 4}\n <h4>\n <slot></slot>\n </h4>\n{:else if level === 5}\n <h5>\n <slot></slot>\n </h5>\n{/if}\n```\n\n```text\nHeading\n```\n\n```text\nsvelte\n```\n\n```text\nlevel\n```\n\n```text\n<h>\n```\n\n```text\nsvelte ?\n```\n\n```svelte\n<script>\n import { setContext, getContext } from 'svelte'\n\n let level\n\n // if we find a context has already been set in this component tree, \n // it came from a parent/ancestor instance of Section.svelte\n\n if (getContext('headingLevel')) {\n // Increment the context because this is the next nesting level\n level = getContext('headingLevel') + 1\n setContext('headingLevel', level)\n } else {\n // otherwise this instance is the first of its kind in the hierarchy\n level = 2\n setContext('headingLevel', level)\n }\n</script>\n\n<section>\n <slot />\n</section>\n```\n\n```svelte\n<script>\n import { getContext } from 'svelte'\n\n // prop to insert your desired contents into the heading tag\n export let message\n\n // get the context, but make sure we can't go higher than <h6>\n let level = Math.min(getContext('headingLevel'), 6)\n\n const render = () => `\n <h${level}>\n ${message}\n </h${level}>\n `\n\n</script>\n\n{@html render()}\n```\n\n```svelte\n<Section>\n <HeadingTag message={\"hello\"} />\n <!-- renders <h2>hello</h2> -->\n <Section>\n <HeadingTag message={\"hello\"} />\n <!-- renders <h3>hello</h3> -->\n <Section>\n <HeadingTag message={\"hello\"} />\n <!-- renders <h4>hello</h4> -->\n </Section>\n </Section>\n</Section>\n\n<Section>\n <HeadingTag message={\"hello\"} />\n <!-- renders <h2>hello</h2> -->\n</Section>\n```\n\n```svelte\n<script>\n import { setContext, getContext } from 'svelte'\n\n let level\n\n if (getContext('headingLevel')) {\n level = getContext('headingLevel') + 1\n setContext('headingLevel', level)\n } else {\n // this and the HTML below are the only things that changed\n level = 1\n setContext('headingLevel', level)\n }\n</script>\n\n{#if level === 1}\n <main>\n <slot />\n </main>\n{:else}\n <section>\n <slot />\n <section>\n{/if}\n```\n\n```text\nSection.svelte\n```\n\n```text\nHeadingTag.svelte\n```\n\n```text\nMyPage.svelte\n```\n\n```text\n<h2>\n```\n\n```text\n<h1>\n```\n\n```text\n<main>\n```\n\n```text\n<h1>\n```\n\n```text\nSection.svelte\n```\n\n```text\n<script>\nexport let level = 3;\nlet displayText = \"<h\" + level + \">\" +\n \"Sample header text\" +\n \"</h\" + level + \">\";\n</script>\n\n<main>\n <div>\n {@html displayText}\n </div>\n</main>\n```\n\n```html\n<svelte:element this=\"h1\">this will be rendered as a top-level heading</svelte:element>\n\n<svelte:element this={tag}>will render the element named in 'tag'</svelte:element>\n\n<svelte:element this={null}>will not render for falsey values</svelte:element>\n```\n\n```text\nsvelte:element\n```\n\n========================================\n\nComments:\n- This very simple solution was exactly what I was looking for to generate dynamic HTML in general. Thanks!\n- This should go without saying, but saying it anyways. Be very careful using `@html` as it can make you vulnerable to XSS attacks. Make sure anything dynamically inserted into the string is sanitized first. For instance, imagine that `level` came from a CMS that didn't validate types. If a malicious actor somehow managed to get level to look like: `2>/*Any code here*/<h2` then they could execute arbitrary code\n- I find that pretty elegant. Thanks so much for sharing this pattern.","metadata":{"transformedAt":"2026-08-18T18:33:40.669Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":284,"estimatedTokens":1229}}159{"id":"stack-65109375","source":"stackoverflow","questionId":65109375,"title":"Svelte (rollup) - Error: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)","tags":["svelte","rollup"],"text":"Title: Svelte (rollup) - Error: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)\nTags: svelte, rollup\nSource: Stack Overflow\n\nQuestion:\nI am doing **nothing** to trigger this error. The app works fine one second, and doesn't the next.\n\nWhy is this happening? It is not due to the missing `@rollup/plugin-json` plugin because it worked previously without it.\n\n### Error\n\n```\nhttps://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency\npath (imported by path?commonjs-external)\nhttp (imported by http?commonjs-external)\nnet (imported by net?commonjs-external)\nurl (imported by url?commonjs-external)\n[!] Error: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)\nnode_modules/mime-db/db.json (2:40)\n1: {\n2: \"application/1d-interleaved-parityfec\": {\n ^\n3: \"source\": \"iana\"\n4: },\nError: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)\n at error (/mnt/c/ivan/dev/lab/atlas-biotek/node_modules/rollup/dist/shared/rollup.js:5265:30)\n at Module.error (/mnt/c/ivan/dev/lab/atlas-biotek/node_modules/rollup/dist/shared/rollup.js:9835:16)\n at tryParse (/mnt/c/ivan/dev/lab/atlas-biotek/node_modules/rollup/dist/shared/rollup.js:9716:23)\n at Module.setSource (/mnt/c/ivan/dev/lab/atlas-biotek/node_modules/rollup/dist/shared/rollup.js:10142:19)\n at ModuleLoader.addModuleSource (/mnt/c/ivan/dev/lab/atlas-biotek/node_modules/rollup/dist/shared/rollup.js:18312:20)\n```\n\n### Adding the plugin\n\n```\nnpm i @rollup/plugin-json --save-dev\n```\n\n**rollup.js.config**\n\n```\nimport json from \"@rollup/plugin-json\";\n\nexport default {\n plugins: [\n commonjs(),\n json(), //\n\n========================================\n\nTop Answer:\nIf you are using Typescript, I added the `json()` plugin after `typescript`:\n\nFile: **rollup.config.js**\n\n```\nimport typescript from \"rollup-plugin-typescript2\";\nimport resolve from \"@rollup/plugin-node-resolve\";\nimport commonjs from \"@rollup/plugin-commonjs\";\nimport replace from \"@rollup/plugin-replace\";\nimport json from \"@rollup/plugin-json\";\n\nconst plugins = [\n typescript({\n tsconfig: \"./tsconfig-build.json\",\n }),\n json(), <<------------- HERE\n resolve(),\n commonjs(),\n replace({\n ...\n preventAssignment: true,\n }),\n];\n```\n\n========================================\n\nCode:\n```text\nhttps://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency\npath (imported by path?commonjs-external)\nhttp (imported by http?commonjs-external)\nnet (imported by net?commonjs-external)\nurl (imported by url?commonjs-external)\n[!] Error: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)\nnode_modules/mime-db/db.json (2:40)\n1: {\n2: \"application/1d-interleaved-parityfec\": {\n ^\n3: \"source\": \"iana\"\n4: },\nError: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)\n at error (/mnt/c/ivan/dev/lab/atlas-biotek/node_modules/rollup/dist/shared/rollup.js:5265:30)\n at Module.error (/mnt/c/ivan/dev/lab/atlas-biotek/node_modules/rollup/dist/shared/rollup.js:9835:16)\n at tryParse (/mnt/c/ivan/dev/lab/atlas-biotek/node_modules/rollup/dist/shared/rollup.js:9716:23)\n at Module.setSource (/mnt/c/ivan/dev/lab/atlas-biotek/node_modules/rollup/dist/shared/rollup.js:10142:19)\n at ModuleLoader.addModuleSource (/mnt/c/ivan/dev/lab/atlas-biotek/node_modules/rollup/dist/shared/rollup.js:18312:20)\n```\n\n```text\nnpm i @rollup/plugin-json --save-dev\n```\n\n```js\nimport json from \"@rollup/plugin-json\";\n\nexport default {\n plugins: [\n commonjs(),\n json(), // <---- put after commonjs\n ]\n}\n```\n\n```text\nUncaught ReferenceError: require$$0$1 is not defined\n at main.js:5\n(anonymous) @ main.js:5\n```\n\n```text\n@rollup/plugin-json\n```\n\n```js\nimport { is } from \"express/lib/request\";\n```\n\n```js\nimport typescript from \"rollup-plugin-typescript2\";\nimport resolve from \"@rollup/plugin-node-resolve\";\nimport commonjs from \"@rollup/plugin-commonjs\";\nimport replace from \"@rollup/plugin-replace\";\nimport json from \"@rollup/plugin-json\";\n\n\nconst plugins = [\n typescript({\n tsconfig: \"./tsconfig-build.json\",\n }),\n json(), <<------------- HERE\n resolve(),\n commonjs(),\n replace({\n ...\n preventAssignment: true,\n }),\n];\n```\n\n```text\njson()\n```\n\n```text\ntypescript\n```\n\n========================================\n\nComments:\n- In my case vscode autocompleted ` import { width } from \"tailwindcss/lib/plugins\";` It took some time to figure it out.\n- Then how do I use modules in the client without causing the error?","metadata":{"transformedAt":"2026-08-18T18:33:40.669Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":164,"estimatedTokens":1140}}160{"id":"stack-65092054","source":"stackoverflow","questionId":65092054,"title":"How to use Svelte store with tree-like nested object?","tags":["svelte","svelte-store"],"text":"Title: How to use Svelte store with tree-like nested object?\nTags: svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\nThe Svelte official tutorial employs such complex object in its document for ``\n\n```\nlet root = [\n {\n type: 'folder',\n name: 'Important work stuff',\n files: [\n { type: 'file', name: 'quarterly-results.xlsx' }\n ]\n },\n {\n type: 'folder',\n name: 'Animal GIFs',\n files: [\n {\n type: 'folder',\n name: 'Dogs',\n files: [\n { type: 'file', name: 'treadmill.gif' },\n { type: 'file', name: 'rope-jumping.gif' }\n ]\n },\n {\n type: 'folder',\n name: 'Goats',\n files: [\n { type: 'file', name: 'parkour.gif' },\n { type: 'file', name: 'rampage.gif' }\n ]\n },\n { type: 'file', name: 'cat-roomba.gif' },\n { type: 'file', name: 'duck-shuffle.gif' },\n { type: 'file', name: 'monkey-on-a-pig.gif' }\n ]\n },\n { type: 'file', name: 'TODO.md' }\n];\n```\n\nIf this object needs to be reactive and placed inside a store, how should it be done? Should the tree be wrapped as a single store, or each file and folder is its own store and stores are nested accordingly?\n\nIn both cases, it seems whenever the top-level properties are changed (svelte store considers update from objects always fresh), the whole tree will be checked for change?\n\n========================================\n\nTop Answer:\nNote to myself:\n\nhttps://github.com/sveltejs/svelte/issues/1435#issuecomment-735233175\n\nStart with a single store with all your global state and then split\noff views from that main store. As a proof of concept I have written a\ntool called subStore.\nExamples and links to repl can be found here\nhttps://github.com/bradphelan/immer.loves.svelte\n\nAnd https://github.com/PixievoltNo1/svelte-writable-derived#making-an-object-store-from-several-single-value-stores\n\n========================================\n\nCode:\n```js\nlet root = [\n {\n type: 'folder',\n name: 'Important work stuff',\n files: [\n { type: 'file', name: 'quarterly-results.xlsx' }\n ]\n },\n {\n type: 'folder',\n name: 'Animal GIFs',\n files: [\n {\n type: 'folder',\n name: 'Dogs',\n files: [\n { type: 'file', name: 'treadmill.gif' },\n { type: 'file', name: 'rope-jumping.gif' }\n ]\n },\n {\n type: 'folder',\n name: 'Goats',\n files: [\n { type: 'file', name: 'parkour.gif' },\n { type: 'file', name: 'rampage.gif' }\n ]\n },\n { type: 'file', name: 'cat-roomba.gif' },\n { type: 'file', name: 'duck-shuffle.gif' },\n { type: 'file', name: 'monkey-on-a-pig.gif' }\n ]\n },\n { type: 'file', name: 'TODO.md' }\n];\n```\n\n```text\n<svelte:self>\n```\n\n```html\n<script>\n import { writable } from 'svelte/store'\n\n const x = writable(0)\n\n const onClick = () => {\n $x = $x + 1\n }\n</script>\n\n<button on:click={onClick}>+</button>\n\n<span>{$x}</span>\n```\n\n```html\n<script>\n import { writable } from 'svelte/store'\n\n const x = writable({\n count: 0,\n })\n\n const onClick = () => {\n $x.count = $x.count + 1\n }\n</script>\n\n<button on:click={onClick}>+</button>\n\n<span>{$x.count}</span>\n```\n\n```html\n<script>\n export let value\n</script>\n\n<input bind:value />\n```\n\n```html\n<script>\n import Child from './Child.svelte'\n\n let value = ''\n\n $: console.log(value)\n</script>\n\n<Child bind:value />\n```\n\n```html\n<script>\n import { writable } from 'svelte/store'\n\n const x = writable({\n count: 0,\n })\n \n const y = writable([\n { count: 0 },\n { count: 1 },\n ])\n\n const onClick = () => {\n $x.count = $x.count + 1\n }\n</script>\n\n<button on:click={onClick}>+</button>\n\n<span>{$x.count}</span>\n\n<hr />\n\n{#each $y as item, i}\n <div>\n <button on:click={() => item.count++}>$y[{i}]: +</button>\n </div>\n{/each}\n\n<pre>{JSON.stringify($y)}</pre>\n```\n\n```js\nimport { readable, writable, derived } from 'svelte/store'\n\n// a big writable store\nexport const root = writable([\n {\n type: 'folder',\n name: 'Important work stuff',\n files: [{ type: 'file', name: 'quarterly-results.xlsx' }],\n },\n {\n type: 'folder',\n name: 'Animal GIFs',\n files: [\n {\n type: 'folder',\n name: 'Dogs',\n files: [\n { type: 'file', name: 'treadmill.gif' },\n { type: 'file', name: 'rope-jumping.gif' },\n ],\n },\n {\n type: 'folder',\n name: 'Goats',\n files: [\n { type: 'file', name: 'parkour.gif' },\n { type: 'file', name: 'rampage.gif' },\n ],\n },\n { type: 'file', name: 'cat-roomba.gif' },\n { type: 'file', name: 'duck-shuffle.gif' },\n { type: 'file', name: 'monkey-on-a-pig.gif' },\n ],\n },\n { type: 'file', name: 'TODO.md' },\n])\n```\n\n```html\n<script>\n import { root } from './stores.js'\n import Folder from './Folder.svelte'\n\n $: console.log($root)\n</script>\n\n<div class=\"hbox\">\n <div>\n <!-- NOTE binding to the store itself: bind=files={root} -->\n <Folder readonly expanded bind:files={$root} file={{ name: 'Home' }} />\n </div>\n <pre>{JSON.stringify($root, null, 2)}</pre>\n</div>\n\n<style>\n .hbox {\n display: flex;\n justify-content: space-around;\n }\n</style>\n```\n\n```html\n<script>\n import File from './File.svelte'\n\n export let readonly = false\n export let expanded = false\n\n export let file\n export let files\n\n function toggle() {\n expanded = !expanded\n }\n</script>\n\n{#if readonly}\n <!-- NOTE bindings must keep referencing the \"entry\" variable \n (here: `file.`) to be tracked -->\n <span class:expanded on:click={toggle}>{file.name}</span>\n{:else}\n <label>\n <span class:expanded on:click={toggle} />\n <input bind:value={file.name} />\n </label>\n{/if}\n\n{#if expanded}\n <ul>\n {#each files as file}\n <li>\n {#if file.type === 'folder'}\n <!-- NOTE the intermediate variable created by the #each loop \n (here: local `file` variable) preserves tracking, though -->\n <svelte:self bind:file bind:files={file.files} />\n {:else}\n <File bind:file />\n {/if}\n </li>\n {/each}\n </ul>\n{/if}\n\n<style>\n span {\n padding: 0 0 0 1.5em;\n background: url(tutorial/icons/folder.svg) 0 0.1em no-repeat;\n background-size: 1em 1em;\n font-weight: bold;\n cursor: pointer;\n min-height: 1em;\n display: inline-block;\n }\n\n .expanded {\n background-image: url(tutorial/icons/folder-open.svg);\n }\n\n ul {\n padding: 0.2em 0 0 0.5em;\n margin: 0 0 0 0.5em;\n list-style: none;\n border-left: 1px solid #eee;\n }\n\n li {\n padding: 0.2em 0;\n }\n</style>\n```\n\n```html\n<script>\n export let file\n\n $: type = file.name.slice(file.name.lastIndexOf('.') + 1)\n</script>\n\n<label>\n <span style=\"background-image: url(tutorial/icons/{type}.svg)\" />\n <input bind:value={file.name} />\n</label>\n\n<style>\n span {\n padding: 0 0 0 1.5em;\n background: 0 0.1em no-repeat;\n background-size: 1em 1em;\n }\n</style>\n```\n\n```text\n$\n```\n\n```text\nChild.svelte\n```\n\n```text\nApp.svelte\n```\n\n```text\n{#each}\n```\n\n```text\nstores.js\n```\n\n```text\nApp.svelte\n```\n\n```text\nFolder.svelte\n```\n\n```text\nFile.svelte\n```\n\n```text\nif\n```\n\n```text\nfiles\n```\n\n========================================\n\nComments:\n- Thanks for the crash course, however the example really demonstrates how to use complex object directly in svelte, not through a store, since you unwrap the store in the root and then the child components only deals with plain objects.\n- Also, when a file name is changed, the store really doesn't know that, since itself is never notified the change. In other words, the file name change is unobservable from outside world, unless the component emits a custom even or something, but that means stores don't play any part in this.\n- Really? What makes you think that? I thought the JSON dump on the right demonstrated that the store was indeed modified. Have you tried subscribing to the store manually to confirm it didn't know about the change?\n- Sorry, I should have tried it out before jumping into conclusions. You are right, svelte store is smart enough to detect changes deep within a store data. And when the data is tree-like, I guess you're bound to pass branches down recursively. Thanks for the detailed explanation.\n- I'm surprised! Where is that deep observation of a store documented? Can you provide a link? Really useful indeed.\n- @robsch That's not really a special case of \"deep observation of the store\", it's the general behaviors of, on one hand two way binding and, on the other hand writable stores and store magic notation. \"Deep observation\" emerges from the combination of those behaviors that are mostly documented and illustrated separately in docs and examples. Take away: Svelte gives you powerful simple atoms and behaves predictably when you compose them. Leverage the power, the glue is your thinking, go creative! (Albeit beware of not going too far, simpler is better -- as just illustrated.)\n- chirurgically > surgically","metadata":{"transformedAt":"2026-08-18T18:33:40.670Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":400,"estimatedTokens":2269}}161{"id":"stack-64064506","source":"stackoverflow","questionId":64064506,"title":"export typescript type in svelte file","tags":["typescript","svelte","sapper"],"text":"Title: export typescript type in svelte file\nTags: typescript, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI want to export the type that I defined in one of my files and import it inside another file.\n\n```\nexport type myNewType = {name: string};\n```\n\nlinter show me bellow error when I add `export`:\n\n`Modifiers cannot appear here.`\n\nI can make it work by creating a new `ts` file and import the type from it. I just want to know if there is a way to define type inside `svelte` file or not.\n\n**Update:**\n\nI use the sapper template and it will run without error but `TS` functionality not work and show me errors in `vscode` when importing type and export type from svelte file.\n\n========================================\n\nTop Answer:\nJust in case it helps anyone, I was having an issue importing my own type which I had declared in a .ts file, into another library file:\n\nMy type was declared as follows:\n\n```\nexport type UserAuth = {\n name: string,\n email: string,\n token: ''\n};\n```\n\nAn in my /lib/auth.ts file, I was attempting to import it as follows:\n\n```\nimport { UserAuth } from \"../types/user.auth\";\n```\n\nWhich produced an error that the type has not been exported.\n\nThe following fixed the issue for me:\n\n```\nimport type { UserAuth } from \"../types/user.auth\";\n```\n\n========================================\n\nCode:\n```text\nexport type myNewType = {name: string};\n```\n\n```text\nexport\n```\n\n```text\nModifiers cannot appear here.\n```\n\n```text\nts\n```\n\n```text\nsvelte\n```\n\n```text\nTS\n```\n\n```text\nvscode\n```\n\n```html\n<script context=\"module\" lang=\"ts\">\n export type myNewType = {name: string};\n</script>\n\n<script>\n export let aProp: string;\n</script>\n\n<p>some html</p>\n```\n\n```html\n<script module lang=\"ts\">\n export type myNewType = {name: string};\n</script>\n\n<script>\n let { aProp }: { aProp: string } = $props();\n</script>\n\n<p>some html</p>\n```\n\n```text\nlang=\"ts\"\n```\n\n```text\nexport type UserAuth = {\n name: string,\n email: string,\n token: ''\n};\n```\n\n```text\nimport { UserAuth } from \"../types/user.auth\";\n```\n\n```text\nimport type { UserAuth } from \"../types/user.auth\";\n```\n\n========================================\n\nComments:\n- I guess it's just an issue with the linter. When you run the TypeScript check does it work?\n- yep, it will run with no error. I use sapper but the importing type will also show me an error and autocomplete not working.\n- TypeScript support in svelte is really new so I guess it's just an issue with the linter that you are using (and not the TypeScript compiler used by svelte). Which linter are you using?\n- I didn't set any linter and I guess it's `sapper` default linter\n- This works but doesn't support Svelte's native `export let data`: under different context it becomes unavailable, so I can't for example `export type MyDataType = data` , because it's comming from different script tag :(\n- In Svelte 5 this is now: `...`","metadata":{"transformedAt":"2026-08-18T18:33:40.670Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":134,"estimatedTokens":721}}162{"id":"stack-67049219","source":"stackoverflow","questionId":67049219,"title":"Class styling on a custom component in Svelte does not register","tags":["svelte","sapper"],"text":"Title: Class styling on a custom component in Svelte does not register\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI am using Svelte/Sapper templae and added Attractions UI, but I cannot apply any class/styles to their custom components, like so:\n\n```\n\n .search-box {\n margin-bottom: 10px;\n }\n\n```\n\nI get\n\nUnused CSS selector \".search-box\"\n\nThe only way to make it work so far for me was to apply the `:global` modifier on the style.\n\n========================================\n\nTop Answer:\nThe problem here is that Svelte has no way of knowing that the `class` property refers to a CSS class here or even *where* to apply this class. Something to not forget is that the following are all valid Svelte components:\n\n```\nHello World\n```\n\n```\nHello\nWorld\n```\n\n```\nHello World\n```\n\nIn the first example, it should *probably* be on the span, but where should the class go in the second example, the first or second span ? Or maybe both ? And what about the last example where there is no DOM element at all, you cannot add a class to a textnode.\n\nBecause of this your class is marked as *unused* by Svelte and removed during compilation. This is inline with Svelte *Single File Component* philosophy where all styling for a component is included in the same file. While your construction is counter to that it is sometimes a valid approach, this is what the `:global` is for.\n\nNote that you can export a `class` property from TextField and apply to the element of your choice, you would still need to mark the class as global though:\n\n```\n\n // You must do this because class is a reserved keyword in JavaScript\n let className;\n export { className as class };\n\n \n ...\n \n ...\n\n```\n\n========================================\n\nCode:\n```text\n<TextField class='search-box' type='search' />\n<style>\n .search-box {\n margin-bottom: 10px;\n }\n</style>\n```\n\n```text\n:global\n```\n\n```text\n<div class='local'>\n <TextField class='search-box' type='search' />\n</div>\n\n<style>\n .local :global(.search-box) {\n margin-bottom: 10px;\n }\n</style>\n```\n\n```text\nclass\n```\n\n```text\n:global\n```\n\n```text\n:global\n```\n\n```html\n<span>Hello World</span>\n```\n\n```html\n<span>Hello</span>\n<span>World</span>\n```\n\n```text\nHello World\n```\n\n```html\n<script>\n // You must do this because class is a reserved keyword in JavaScript\n let className;\n export { className as class };\n</script>\n<div>\n <p>\n <span class={className}>...</span>\n <p>\n <button>...</button>\n</div>\n```\n\n```text\nclass\n```\n\n```text\n:global\n```\n\n```text\nclass\n```\n\n========================================\n\nComments:\n- > \"you can export a class property from TextField and apply to the element of your choice\". This is exactly what the mentioned Attractions library does. I believe the question was about how to use such component with such prop without having to use the `:global` modifier\n- Which is impossible, and my answers explains **why** it is not possible.\n- I'm having trouble using $$props.class inside a library which, as I import it from npm, errors with \"The $ prefix is reserved, and cannot be used for variable and import names\" so this approach I guess would work but I'm not sure how do you define a default value with this approach? As now I get annoying warnings about undeclared props\n- Given the way svelte scopes classes this seems to be the only way you can style a child component without creating truly global styles. Just be sure to add `{...$$props}` to your child component so the class is applied :)\n- @stwilz either that or export a prop called \"class\" (which we do in Attractions). This is actually one of the few case where I personally miss Vue's `inheritAttrs` :D\n- You mean the old' `let className = ''; export { className as class};`? That would also work but it's still my least favourite things about Svelte :(","metadata":{"transformedAt":"2026-08-18T18:33:40.670Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":146,"estimatedTokens":957}}163{"id":"stack-58219453","source":"stackoverflow","questionId":58219453,"title":"How do I use jQuery in Svelte","tags":["jquery","svelte","sapper"],"text":"Title: How do I use jQuery in Svelte\nTags: jquery, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nDoing this:\n\n```\nimport $ from 'jquery';\n```\n\nShows the error \n\n```\nThe $ prefix is reserved, and cannot be used for variable and import names svelte(illegal-declaration)\n```\n\n========================================\n\nTop Answer:\nI noticed that if JQuery is already available globally, then you can access it via `window.$` instead of just `$` and the svelte compiler won't complain.\n\n========================================\n\nCode:\n```text\nimport $ from 'jquery';\n```\n\n```text\nThe $ prefix is reserved, and cannot be used for variable and import names svelte(illegal-declaration)\n```\n\n```text\nimport * as $j from 'jquery';\n```\n\n```text\nimport as\n```\n\n```text\nanyName\n```\n\n```text\nwindow.$\n```\n\n```text\n$\n```\n\n```js\nimport jQuery from 'jquery'\n```\n\n========================================\n\nComments:\n- You can also `import jQuery from \"jquery\"` to avoid using the $ shorthand, which is indeed a reserved word in svelte. More generally, check stackoverflow.com/questions/34338411/… for methods to import jQuery using ES6 syntax.\n- Thanks, I figured but what I am trying to do is use a bootstrap component but the problem I am having now is the script runs before the component is mounted so at that point there is no element with the ID I am targeting\n- Thanks, I figured but what I am trying to do is use a bootstrap component but the problem I am having now is the script runs before the component is mounted so at that point there is no element with the ID I am targeting\n- stackoverflow.com/a/57828618/10679649\n- @AneriEmmax to address your other issue (component not mounted) you can use svelte's `onMount` lifecycle method. See the official doc here: svelte.dev/docs#onMount\n- Solution for SvelteKit\n- Eslint says variable name start with `$` is reserved, thus can't start with `$`, so maybe use `j$`.\n- This didn't work for me. Iirc it was due to a rollup error saying that $ is reserved. See my anwer if you're experiencing the same\n- It doesn't work for me too and I am using SvelteKit with Jquery-based UI framework\n- Doing something like `const jq = window.$;` saves a few keystrokes","metadata":{"transformedAt":"2026-08-18T18:33:40.670Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":70,"estimatedTokens":551}}164{"id":"stack-55842088","source":"stackoverflow","questionId":55842088,"title":"Svelte Hot Reloading Issue","tags":["svelte","hot-reload"],"text":"Title: Svelte Hot Reloading Issue\nTags: svelte, hot-reload\nSource: Stack Overflow\n\nQuestion:\nRecently started playing with Svelte using the sveltejs template. Everything is working fine, however when I do any change in the files it doesn't hot reload the changes to the web browser, so I have to manually refresh the page to see the changes. Is there any option in the settings to enable that feature or is it not possible at this point?\n\n========================================\n\nTop Answer:\n**Update 2022-03-24**\n\nHMR is now officially supported in Svelte with Vite, Svelte Kit, and Webpack. The Snowpack plugin for Svelte also has HMR support.\n\nThe information bellow are essentially still current regarding HMR support in the Rollup universe.\n\nWith regard to HMR, today Vite (and Kit that uses it under the hood) is probably the best solution by far. It has excellent HMR support, and is very much faster during dev than bundle optimization oriented tools like Rollup.\n\n(And so, the accepted answer is even more wrong now!)\n\nJust for the kicks of contradicting the author about his own libs, I'm going to argue that the accepted answer is all wrong.\n\nRollup *can* have HMR with rollup-plugin-hot. As previously noted in the comments, Nollup can do it too.\n\nWith just that, you can have updated code pushed to the browser and refresh (i.e. destroy + recreate) your whole app without reloading the page. However that's not terribly better, if at all, than a full page reload.\n\nWhat you want is to replace only the Svelte components that are affected by a code update, so that your current app state is preserved and, as much as possible, you also want the state of updated components to be preserved too. For this, you can use rollup-plugin-svelte-hot with Rollup / Nollup, or svelte-loader-hot with Webpack.\n\nPending official support, I maintain clones of the official templates + HMR: svelte-template-hot for Rollup / Nollup, and svelte-template-webpack-hot for Webpack. There is also sapper-template-hot for Sapper (only supports Webpack). And, for completeness, svelte-native-template (not maintained by me) also includes HMR support.\n\nHMR is still not officially supported by Svelte. The issue mentioned in Rich's answer has been closed. Progress can now be tracked in this issue.\n\n(Of course, Rich's answer was correct when it was initially written. And it is still correct from an official perspective. And this answer is a shameless plug to advertise my own projects because the question ranks pretty high in Google, but I hope it is useful nonetheless.)\n\n========================================\n\nComments:\n- Welcome to Stack Overflow Ben! Svelte 3 doesn't have hot reloading yet, but you could automatically refresh the browser on changes with e.g. the LiveReload Rollup plugin.\n- In 2020, one can wait for SvelteKit svelte.dev/blog/whats-the-deal-with-sveltekit that replaces Rollup (in dev) with Snowpack. Official HMR.\n- A comment from Twitter suggests that Nollup could be used for HMR in a Rollup project — I haven't used it myself, YMMV, but it sounds promising mobile.twitter.com/PepsRyuu/status/1121808611217420290\n- Great job Rich, I am very impressed with v3. Any idea and timeline about TypeScript support?\n- No timeline, no — just 'when we get round to it'. It's a priority though!\n- Just tested `npx degit sveltejs/template my-app` and `npx degit \"sveltejs/sapper-template#rollup\" my-app`, `npm install` and then `npm run dev` and both templates work with HMR out of the box. 2020-05-03\n- You need to review your answer, it's no longer correct\n- Is it expected that the hot reload in the default SvelteKit setup with Vite loses state on every edit? Coming from a React hot reload setup I use at work, it's so jarring.\n- @Antrikshy If you mean all state, no this is not expected, you may have found a bug. If you mean the state of the component affected by the change and its children, yes it is expected. For some reason (assignment syntax, I guess), state preservation in Svelte turned out very confusing in some situations, so we turned it off by default. See: github.com/sveltejs/vite-plugin-svelte/blob/main/docs/….\n- Turns out it was just that off by default behavior. I was able to turn it on and it’s all good now. It certainly felt like I was losing all state, but I was only getting started with this project and it was pretty simple. Maybe that’s why.","metadata":{"transformedAt":"2026-08-18T18:33:40.670Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":47,"estimatedTokens":1101}}165{"id":"stack-64194571","source":"stackoverflow","questionId":64194571,"title":"Cannot find module './App.svelte' or its corresponding type declarations","tags":["javascript","node.js","typescript","electron","svelte"],"text":"Title: Cannot find module './App.svelte' or its corresponding type declarations\nTags: javascript, node.js, typescript, electron, svelte\nSource: Stack Overflow\n\nQuestion:\nI have a setup that integrates electron with svelte along with typescript support.\n\nwhen I run the `rollup` script to compile svelte app, i am getting cannot find module `./App.svelte` error as shown below.\n\n```\nPlugin typescript: @rollup/plugin-typescript TS2307: Cannot find module './App.svelte' or its corresponding type declarations.\n```\n\nHere's my `package.json` configuration :\n\n```\n{\n \"name\": \"tapwire-electron-first\",\n \"productName\": \"tapwire-electron-first\",\n \"version\": \"1.0.0\",\n \"description\": \"My Electron application description\",\n \"main\": \"dist/index.js\",\n \"scripts\": {\n \"electron-start\": \"tsc && electron-forge start\",\n \"electron-package\": \"electron-forge package\",\n \"electron-make\": \"electron-forge make\",\n \"electron-publish\": \"electron-forge publish\",\n \"electron-lint\": \"eslint --ext .ts .\",\n \"svelte-build\": \"rollup -c\",\n \"svelte-dev\": \"rollup -c -w\",\n \"svelte-start\": \"sirv public\",\n \"svelte-validate\": \"svelte-check\",\n \"start\": \"run-p svelte-dev electron-start\"\n },\n \"keywords\": [],\n \"author\": {\n \"name\": \"nateshmbhat\",\n },\n \"license\": \"MIT\",\n \"config\": {\n \"forge\": {\n \"packagerConfig\": {},\n \"makers\": [\n {\n \"name\": \"@electron-forge/maker-squirrel\",\n \"config\": {\n \"name\": \"tapwire_electron_first\"\n }\n },\n {\n \"name\": \"@electron-forge/maker-zip\",\n \"platforms\": [\n \"darwin\"\n ]\n },\n {\n \"name\": \"@electron-forge/maker-deb\",\n \"config\": {}\n },\n {\n \"name\": \"@electron-forge/maker-rpm\",\n \"config\": {}\n }\n ]\n }\n },\n \"devDependencies\": {\n \"@electron-forge/cli\": \"^6.0.0-beta.53\",\n \"@electron-forge/maker-deb\": \"^6.0.0-beta.53\",\n \"@electron-forge/maker-rpm\": \"^6.0.0-beta.53\",\n \"@electron-forge/maker-squirrel\": \"^6.0.0-beta.53\",\n \"@electron-forge/maker-zip\": \"^6.0.0-beta.53\",\n \"@rollup/plugin-commonjs\": \"^15.1.0\",\n \"@rollup/plugin-node-resolve\": \"^9.0.0\",\n \"@rollup/plugin-typescript\": \"^6.0.0\",\n \"@types/node\": \"^14.11.2\",\n \"@typescript-eslint/eslint-plugin\": \"^2.34.0\",\n \"@typescript-eslint/parser\": \"^2.34.0\",\n \"cross-env\": \"^7.0.2\",\n \"electron\": \"10.1.3\",\n \"eslint\": \"^7.10.0\",\n \"eslint-plugin-import\": \"^2.22.1\",\n \"npm-run-all\": \"^4.1.5\",\n \"rollup\": \"^2.28.2\",\n \"rollup-plugin-livereload\": \"^2.0.0\",\n \"rollup-plugin-svelte\": \"^6.0.1\",\n \"rollup-plugin-terser\": \"^7.0.2\",\n \"svelte\": \"^3.29.0\",\n \"svelte-check\": \"^1.0.55\",\n \"svelte-preprocess\": \"^4.3.2\",\n \"typescript\": \"^4.0.3\"\n },\n \"dependencies\": {\n \"concurrently\": \"^5.3.0\",\n \"electron-reload\": \"^1.5.0\",\n \"electron-squirrel-startup\": \"^1.0.0\",\n \"sirv-cli\": \"^1.0.6\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nThe culprit on my end was a stale `global.d.ts`. I had `/// ` set, but was trying to change the project to vanilla Svelte. Fixing it to have `/// ` instead did the trick.\n\n========================================\n\nCode:\n```text\nPlugin typescript: @rollup/plugin-typescript TS2307: Cannot find module './App.svelte' or its corresponding type declarations.\n```\n\n```text\n{\n \"name\": \"tapwire-electron-first\",\n \"productName\": \"tapwire-electron-first\",\n \"version\": \"1.0.0\",\n \"description\": \"My Electron application description\",\n \"main\": \"dist/index.js\",\n \"scripts\": {\n \"electron-start\": \"tsc && electron-forge start\",\n \"electron-package\": \"electron-forge package\",\n \"electron-make\": \"electron-forge make\",\n \"electron-publish\": \"electron-forge publish\",\n \"electron-lint\": \"eslint --ext .ts .\",\n \"svelte-build\": \"rollup -c\",\n \"svelte-dev\": \"rollup -c -w\",\n \"svelte-start\": \"sirv public\",\n \"svelte-validate\": \"svelte-check\",\n \"start\": \"run-p svelte-dev electron-start\"\n },\n \"keywords\": [],\n \"author\": {\n \"name\": \"nateshmbhat\",\n },\n \"license\": \"MIT\",\n \"config\": {\n \"forge\": {\n \"packagerConfig\": {},\n \"makers\": [\n {\n \"name\": \"@electron-forge/maker-squirrel\",\n \"config\": {\n \"name\": \"tapwire_electron_first\"\n }\n },\n {\n \"name\": \"@electron-forge/maker-zip\",\n \"platforms\": [\n \"darwin\"\n ]\n },\n {\n \"name\": \"@electron-forge/maker-deb\",\n \"config\": {}\n },\n {\n \"name\": \"@electron-forge/maker-rpm\",\n \"config\": {}\n }\n ]\n }\n },\n \"devDependencies\": {\n \"@electron-forge/cli\": \"^6.0.0-beta.53\",\n \"@electron-forge/maker-deb\": \"^6.0.0-beta.53\",\n \"@electron-forge/maker-rpm\": \"^6.0.0-beta.53\",\n \"@electron-forge/maker-squirrel\": \"^6.0.0-beta.53\",\n \"@electron-forge/maker-zip\": \"^6.0.0-beta.53\",\n \"@rollup/plugin-commonjs\": \"^15.1.0\",\n \"@rollup/plugin-node-resolve\": \"^9.0.0\",\n \"@rollup/plugin-typescript\": \"^6.0.0\",\n \"@types/node\": \"^14.11.2\",\n \"@typescript-eslint/eslint-plugin\": \"^2.34.0\",\n \"@typescript-eslint/parser\": \"^2.34.0\",\n \"cross-env\": \"^7.0.2\",\n \"electron\": \"10.1.3\",\n \"eslint\": \"^7.10.0\",\n \"eslint-plugin-import\": \"^2.22.1\",\n \"npm-run-all\": \"^4.1.5\",\n \"rollup\": \"^2.28.2\",\n \"rollup-plugin-livereload\": \"^2.0.0\",\n \"rollup-plugin-svelte\": \"^6.0.1\",\n \"rollup-plugin-terser\": \"^7.0.2\",\n \"svelte\": \"^3.29.0\",\n \"svelte-check\": \"^1.0.55\",\n \"svelte-preprocess\": \"^4.3.2\",\n \"typescript\": \"^4.0.3\"\n },\n \"dependencies\": {\n \"concurrently\": \"^5.3.0\",\n \"electron-reload\": \"^1.5.0\",\n \"electron-squirrel-startup\": \"^1.0.0\",\n \"sirv-cli\": \"^1.0.6\"\n }\n}\n```\n\n```text\nrollup\n```\n\n```text\n./App.svelte\n```\n\n```text\npackage.json\n```\n\n```text\nnpm i --save-dev @tsconfig/svelte\n```\n\n```text\n{\n \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n}\n```\n\n```text\n@tsconfig/svelte\n```\n\n```text\ntsconfig.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\n\"skipLibCheck\": false,\n```\n\n```text\nreact-ts\n```\n\n```text\ntsc\n```\n\n```text\ntsconfig.json\n```\n\n```text\nglobal.d.ts\n```\n\n```text\n/// <reference types=\"@sveltejs/kit\" />\n```\n\n```text\n/// <reference types=\"svelte\" />\n```\n\n```text\n// svelte-shim.d.ts\n\ndeclare module \"*.svelte\" {\n import type { ComponentType } from \"svelte\";\n const component: ComponentType;\n export default component;\n}\n```\n\n```text\nComponentType\n```\n\n```text\ncompilerOptions.checkJS\n```\n\n```text\n.svelte\n```\n\n```text\n.js\n```\n\n```text\nselect Typescript version\n```\n\n```text\nuse workspace version\n```\n\n========================================\n\nComments:\n- Use a well tested starter pack for electron and svelte : github.com/nateshmbhat/svelte-electron-ts-starter\n- See official docs on Svelte with TypeScript\n- in my case, this file was missing altogether\n- If you're using Vite, you may have to change the setting in `vite-end.d.ts`.\n- Yeah, for me this line was just missing. They tell you to add it in github.com/tsconfig/bases#svelte-tsconfigjson","metadata":{"transformedAt":"2026-08-18T18:33:40.670Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":303,"estimatedTokens":1678}}166{"id":"stack-67245743","source":"stackoverflow","questionId":67245743,"title":"config.kit.adapter should be an object with an \"adapt\" method","tags":["javascript","svelte","sveltekit"],"text":"Title: config.kit.adapter should be an object with an \"adapt\" method\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI want to use the @sveltejs/adapter-static in my Svelte Kit app (want to turn it into an SPA).\nI installed the adapter static with npm i @sveltejs/adapter-static.\n\nThe code in the svelte.config.cjs looks like this\n\n```\nkit: {\n // By default, `npm run build` will create a standard Node app.\n // You can create optimized builds for different platforms by\n // specifying a different adapter\n adapter: adapter({\n fallback: 'app.html'\n }),\n```\n\nWhen I start my app with `npm run dev` I get the following error:\n`config.kit.adapter should be an object with an \"adapt\" method`\n\nHow can I fix this?\n\n========================================\n\nCode:\n```text\nkit: {\n // By default, `npm run build` will create a standard Node app.\n // You can create optimized builds for different platforms by\n // specifying a different adapter\n adapter: adapter({\n fallback: 'app.html'\n }),\n```\n\n```text\nnpm run dev\n```\n\n```text\nconfig.kit.adapter should be an object with an \"adapt\" method\n```\n\n```text\nnpm i -D @sveltejs/adapter-static@next\n```\n\n========================================\n\nComments:\n- Thank you, this worked. I feel kinda dumb now haha :)\n- hehe no problem ^^ @Fugi\n- Did not work for me!! Is there any other workaround?\n- @MBParvezRony not that I am aware of. You should ask on the Svelte Discord server. They have a pretty good response time and quality answers most of the time.\n- how do i specify an output directory?\n- using @next just introduces whatever other bugs the next version brings! Technically it solves this issue, but it also brings a firehose of problems\n- @Jan this should be known since SvelteKit is still in development. You can see github.com/sveltejs/kit/milestones for further information on the progress of SvelteKit towards version 1.0.","metadata":{"transformedAt":"2026-08-18T18:33:40.670Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":60,"estimatedTokens":479}}167{"id":"stack-56607606","source":"stackoverflow","questionId":56607606,"title":"Styling dynamic HTML via in-component tag (Unused CSS selector)","tags":["css","svelte"],"text":"Title: Styling dynamic HTML via in-component tag (Unused CSS selector)\nTags: css, svelte\nSource: Stack Overflow\n\nQuestion:\nI am trying to add some styling to an HTML tag rendered inside of the `{@html...}` tag of a Svelte component, but it appears that it only inherits the parent's styling (the container of the `{@html...}` tag). Moreover, the \"Unused CSS selector\" error pops up displaying that my styling selector for that specific HTML tag inside of the Svelte `{@html...}` tag merely doesn't work. Is Svelte built that way and is there a method for styling tags that are rendered inside of the Svelte `{@html...}` tag?\n\nI've tried steps provided in the official Svelte tutorial, but they don't clearly show how to do it.\n\n```\n\n p{\n color: red;\n }\n h1{\n color: blue;\n }\n\n let string = \"\n\n### what\n\n\"; \n\n{@html string}\n\nno\n\n```\n\nI want the `h1` tag to be blue, not inherit the red color from the p tag\n\n========================================\n\nTop Answer:\nIt could be a bug (but it seems difficult for Svelte to know what could be there in that string). \n\nAs (an ugly) workaround, you may choose to specify required style inlined. For example,\n\n```\n\n let string = `\n\n### what\n\n`; \n\n```\n\n**EDIT**: And Svelte creator has answered the official way is using `:global`.\n\n========================================\n\nCode:\n```html\n<style>\n p{\n color: red;\n }\n h1{\n color: blue;\n }\n</style>\n\n<script>\n let string = \"<h1>what</h1>\"; \n</script>\n\n<p>{@html string}</p>\n<p>no</p>\n```\n\n```text\n{@html...}\n```\n\n```text\n{@html...}\n```\n\n```text\n{@html...}\n```\n\n```text\n{@html...}\n```\n\n```text\nh1\n```\n\n```css\n:global(h1) { color: blue }\n```\n\n```css\np :global(h1) { color: blue }\n```\n\n```text\n:global(...)\n```\n\n```text\n<h1>\n```\n\n```text\n{@html ...}\n```\n\n```text\n<h1>\n```\n\n```text\n<p>\n```\n\n```text\n<script>\n let string = `<h1 style=\"color:blue;\">what</h1>`; \n</script>\n```\n\n```text\n:global\n```\n\n========================================\n\nComments:\n- Is there a way to keep it scoped to the component?\n- @Arandomcoder The answer says \"To restrict it to elements inside this component, put the selector inside a local one\" and gives an example of that.\n- Global screws up external components\n- Works as a solution, but overall strikes me as \"odd\" and \"framework-specific\" and a web anti-pattern. @rich-harris is there a term that describes this better or a part of the docs that explains why we'd have to rethread the local style via the :global modifier?","metadata":{"transformedAt":"2026-08-18T18:33:40.670Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":137,"estimatedTokens":619}}168{"id":"stack-64245188","source":"stackoverflow","questionId":64245188,"title":"How to differentiate between Svelte dev mode and build mode?","tags":["svelte","svelte-3"],"text":"Title: How to differentiate between Svelte dev mode and build mode?\nTags: svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nThe dev mode using `npm run dev`, the release mode using `npm build`\n\nHow could i know that it's currently built on dev mode or not in the code, for example:\n\n```\n\n import {onMount} from 'svelte';\n\n onMount(function(){\n if(DEVMODE) { // --> what's the correct one?\n console.log('this is x.svelte');\n }\n })\n\n```\n\n========================================\n\nTop Answer:\nIf you are using sveltekit:\n\n```\nimport { dev } from '$app/environment';\n\nif (dev) {\n //do in dev mode\n}\n```\n\n========================================\n\nCode:\n```svelte\n<script>\n import {onMount} from 'svelte';\n\n onMount(function(){\n if(DEVMODE) { // --> what's the correct one?\n console.log('this is x.svelte');\n }\n })\n</script>\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm build\n```\n\n```js\nimport replace from \"@rollup/plugin-replace\";\nconst production = !process.env.ROLLUP_WATCH;\n```\n\n```js\nreplace({\n isProduction: production,\n }),\n```\n\n```js\nplugins: [\n replace({\n isProduction: production,\n }),\n svelte({\n // options\n }),\n]\n```\n\n```js\nif (!isProduction){ console.log('Developement Mode'); }\n```\n\n```text\nrollup.config.js\n```\n\n```text\nplugins:[ ]\n```\n\n```text\nrollup.config.js\n```\n\n```text\nisProduction\n```\n\n```js\nimport { dev } from '$app/environment';\n\nif (dev) {\n //do in dev mode\n}\n```\n\n```text\nconst isProduction = (): boolean => {\n // Check if is client side\n if (typeof window !== 'undefined' && window.document !== undefined) {\n // check production hostname\n if (window?.location.hostname !== undefined && \n window.location.hostname === 'YOUR_PRODUCTION_HOSTNAME') {\n return true\n } else {\n return false\n }\n } else {\n return false\n }\n}\n```\n\n```text\n<script>\n let isProduction = import.meta.env.MODE === 'production';\n\n if (!isProduction) {\n console.log(\"Developement Mode\");\n } else {\n console.log(\"Production Mode\");\n }\n</script>\n```\n\n```text\nimport.meta.env.DEV\n```\n\n```text\nimport.meta.env.PROD\n```\n\n```text\nimport.meta.env.MODE\n```\n\n========================================\n\nComments:\n- What do i have to import in order to access \"isProduction\" in a svelte component? Because when i do it the way you described, i get a ReferenceError: isProduction is not defined..\n- `{isProduction ? \"Production Mode\" : \"Development Mode\"}` works fine for me.\n- IN 2022. To access `isProduction`, you should use `JSON.parse(isProduction)`.\n- no need to use rollup only for accessing build mode, it's a separate plugin. Just use `process.env.NODE_ENV` anywhere in the app. it should return `development` or `production` as string.\n- Question is about Svelte, nor Sveltekit\n- Useful answer nonetheless as Sveltekit becomes increasingly popular and Google leads here.\n- @EricDelaCruz there is no \"dev mode\" in vanilla svelte, svelte is just a compiler\n- @KTibow What OP means is when you started your app in dev or production mode.\n- @EricDelaCruz there is no \"start\"ing of an app, as I said, Svelte is just a compiler. We could assume the poster is using Svelte with Vite, or assume they're using SvelteKit, but we have no way to tell as the commands are the same for each. And SvelteKit is much more common.\n- Just use `process.env.NODE_ENV` anywhere in the app. it should return `development` or `production` as string.\n- Doesn't work (anymore)\n- Eric it still works for me, can you explain what are you using exactly that it doesn't work for you?\n- Just tried this solution and it works fine","metadata":{"transformedAt":"2026-08-18T18:33:40.670Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":164,"estimatedTokens":899}}169{"id":"stack-56839098","source":"stackoverflow","questionId":56839098,"title":"Import javascript file in svelte","tags":["javascript","html","import","svelte"],"text":"Title: Import javascript file in svelte\nTags: javascript, html, import, svelte\nSource: Stack Overflow\n\nQuestion:\nSo today I discovered Svelte and I absolutley love the concept. I only got one problem I wrote a small **helper.js** file and can't seem to import it. Every time I try to reference the class I get \n\n ReferenceError: Helper is not defined\n\n*main.js file:*\n\n```\nimport App from './App.svelte';\nimport './helper.js';\n\nvar app = new App({\n target: document.body\n});\nexport default app;\n```\n\n*App.svelte file:*\n\n```\n\n let helper = new Helper();\n\n### Hello\n\n```\n\n*helper.js file:*\n\n```\nclass Helper {\n constructor() {\n console.log(\"working\");\n }\n}\n```\n\n========================================\n\nCode:\n```text\nimport App from './App.svelte';\nimport './helper.js';\n\nvar app = new App({\n target: document.body\n});\nexport default app;\n```\n\n```text\n<script>\n let helper = new Helper();\n</script>\n\n<h1>Hello</h1>\n```\n\n```text\nclass Helper {\n constructor() {\n console.log(\"working\");\n }\n}\n```\n\n```html\n<script>\n import Helper from './helper.js';\n let helper = new Helper();\n</script>\n\n<h1>Hello</h1>\n```\n\n========================================\n\nComments:\n- Thanks that worked but I also had to add 'export' in the Helper.js file. On that note: would there be another option to add the whole file without the 'import' statement. Like a would do?\n- No, that would be a bad idea — you'll end up building much more maintainable software if your imports and exports are explicit\n- What about if you've got a legacy js file. How do you include it? It doesn't export anything.\n- Add it as a `` tag\n- What to do when js module isn't exported with `default`?\n- @RichHarris In the above, will the application be reactive to any changes in the `helper` instance?","metadata":{"transformedAt":"2026-08-18T18:33:40.670Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":88,"estimatedTokens":442}}170{"id":"stack-57062741","source":"stackoverflow","questionId":57062741,"title":"Svelte equivalent of React's props.children?","tags":["javascript","node.js","svelte"],"text":"Title: Svelte equivalent of React's props.children?\nTags: javascript, node.js, svelte\nSource: Stack Overflow\n\nQuestion:\nI haven't found this feature anywhere in svelte 3..\nI want it to be something like this..\n\nApp.svelte\n\n```\n\n Can't connect to the server!\n\n`\n```\n\nError.svelte\n\n```\n{props.children}\n```\n\nI want App.svelte to show:\n\n```\nCan't connect to the server!\n\n```\n\nI only know how to do this with React's props.children.\n\n========================================\n\nTop Answer:\nIf you're looking for the Svelte 5 version of `children`, `` has been deprecated and now uses `children` from the `$props()` rune.\n\nSo for example:\n\n```\n//Error.svelte\n\n let { children } = $props();\n\n {@render children?.()}\n\n```\n\nSee more in the migration docs.\n\n========================================\n\nCode:\n```html\n<Error>\n <p>Can't connect to the server!</p>\n</Error>`\n```\n\n```html\n<div>{props.children}</div>\n```\n\n```html\n<div><p>Can't connect to the server!</p></div>\n```\n\n```text\n<div>\n <slot />\n</div>\n```\n\n```html\n//Error.svelte\n\n<script>\n let { children } = $props();\n</script>\n\n<div>\n {@render children?.()}\n</div>\n```\n\n```text\nchildren\n```\n\n```text\n<slot />\n```\n\n```text\nchildren\n```\n\n```text\n$props()\n```\n\n========================================\n\nComments:\n- It is the standard name from the web-components standard - so good on svelte to use this name/approach.\n- In case you want multiple children you can use named slots ``\n- At least for Svelte 5, this will give you the warning: Using `` to render parent content is deprecated. Use `{@render ...}` tags instead.\n- Right answer in 2024","metadata":{"transformedAt":"2026-08-18T18:33:40.671Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":108,"estimatedTokens":399}}171{"id":"stack-67036699","source":"stackoverflow","questionId":67036699,"title":"Is it possible to do type casting inside an each block in svelte","tags":["typescript","typescript-typings","svelte"],"text":"Title: Is it possible to do type casting inside an each block in svelte\nTags: typescript, typescript-typings, svelte\nSource: Stack Overflow\n\nQuestion:\nI have these types:\n\n```\ntype Exercise = {\n type: string\n prompt: string\n answer: string\n}\n\ntype ComplexExercise = {\n type: string\n prompt: string,\n subExercises: Exercise[]\n}\n```\n\nIm trying to make a component that fetches data from an api and renders it according to the type\n\n```\n\n let promise = getExercise(params.exerciseId).then((ex) => (exercise = ex));\n let exercise: ComplexExercise | Exercise;\n\n...\n\n{#await promise}\n Loading exercise\n\n{:then}\n {#if exercise.type !== \"COMPLEX\"}\n \n {:else}\n {#each exercise.subExercises as ex}\n \n {/each}\n {/if}\n{/await}\n```\n\nI get the following error\n\n```\nProperty 'subExercises' does not exist on type Exercise\n```\n\nCasting it throws this error\n\n```\n{#each (exercise as ComplexExercise).subExercises as ex}\n ^ Unexpected token svelte(parse-error)\n```\n\nOnly thing that seems work is setting exercise type to any, I'm avoiding it for the obvious reason.\nAny help is appreciated\n\n========================================\n\nCode:\n```text\ntype Exercise = {\n type: string\n prompt: string\n answer: string\n}\n\ntype ComplexExercise = {\n type: string\n prompt: string,\n subExercises: Exercise[]\n}\n```\n\n```html\n<script lang=\"ts\">\n let promise = getExercise(params.exerciseId).then((ex) => (exercise = ex));\n let exercise: ComplexExercise | Exercise;\n</script>\n...\n\n{#await promise}\n <p>Loading exercise</p>\n{:then}\n {#if exercise.type !== \"COMPLEX\"}\n <BaseEditor {exercise} />\n {:else}\n {#each exercise.subExercises as ex}\n <BaseEditor {ex} />\n {/each}\n {/if}\n{/await}\n```\n\n```sh\nProperty 'subExercises' does not exist on type Exercise\n```\n\n```html\n{#each (exercise as ComplexExercise).subExercises as ex}\n ^ Unexpected token svelte(parse-error)\n```\n\n```text\ntype Exercise = {\n type: \"SIMPLE\"\n prompt: string\n answer: string\n}\n\ntype ComplexExercise = {\n type: \"COMPLEX\"\n prompt: string,\n subExercises: Exercise[]\n}\n```\n\n```text\ntype\n```\n\n```text\n{#if exercise.type !== \"COMPLEX\"}\n```\n\n```text\nComplexExercise\n```\n\n========================================\n\nComments:\n- Typescript is only supported within the `` tags, not in the markup.\n- This works for me well since I don't have many types and they are very unlikely to change, thanks alot","metadata":{"transformedAt":"2026-08-18T18:33:40.671Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":137,"estimatedTokens":591}}172{"id":"stack-69271131","source":"stackoverflow","questionId":69271131,"title":"SvelteKit: Run function at route change (for access token, without doing it at a layout file)","tags":["routes","access-token","svelte","sveltekit"],"text":"Title: SvelteKit: Run function at route change (for access token, without doing it at a layout file)\nTags: routes, access-token, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI just started with SvelteKit and I have a question regarding **functions, that should run on every route change**. I did not find much, helpful information about it.\n\nJust to run it at the **layout files (which I do not prefer**, because I might probably use multiple layout files and prefer one global place.)\n\n**In Vue.js**, I do something like that, to check at every route change, if there is an access token (at the end of the router file):\n\n```\n// src/router/index.ts\nrouter.beforeEach((to, from, next) => {\n AUTHENTICATION.default.fetchAccessToken();\n if (to.options.protected && !AUTHENTICATION.default.tokenData) {\n next(\"/\");\n } else next();\n});\n```\n\n**How would I achive that in SvelteKit?**\n\nWould that work with **svelte-routing in SvelteKit?**\n... and is that **in general a good idea, to check an access token**?\n\nThank you in advance\n\n========================================\n\nCode:\n```text\n// src/router/index.ts\nrouter.beforeEach((to, from, next) => {\n AUTHENTICATION.default.fetchAccessToken();\n if (to.options.protected && !AUTHENTICATION.default.tokenData) {\n next(\"/\");\n } else next();\n});\n```\n\n```js\nimport { navigating } from '$app/stores';\n```\n\n```js\n$: if($navigating) myFunction();\n```\n\n```js\n$effect(() => {\n if ($navigating) {\n myFunction();\n }\n});\n```\n\n```js\n{#if $navigating}\n <LoadingIndicator />\n{/if}\n```\n\n```text\nnavigating\n```\n\n```text\nnavigating\n```\n\n```text\n{ from, to, type }\n```\n\n```text\nfrom\n```\n\n```text\nto\n```\n\n```text\npage\n```\n\n```text\nnull\n```\n\n```text\n<script>\n```\n\n```text\n$:\n```\n\n```text\n$effect\n```\n\n========================================\n\nComments:\n- Hi there. Thanks, that looks quite good and is very helpful. Do you have an idea, where to place that, to have it at a single point and I do not need to import it in every layout-file or so?\n- I think a root __layout file is the best place for this. That's why I should move the whole app into an /app folder.\n- In 2022.09.01 - The default(just like root) layout `src/routes/+layout.svelte` is the best place for this. Read more.","metadata":{"transformedAt":"2026-08-18T18:33:40.671Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":109,"estimatedTokens":559}}173{"id":"stack-57339349","source":"stackoverflow","questionId":57339349,"title":"Svelte route gives me 404","tags":["javascript","user-interface","routes","svelte"],"text":"Title: Svelte route gives me 404\nTags: javascript, user-interface, routes, svelte\nSource: Stack Overflow\n\nQuestion:\nI created a simple router for my app in Svelte.\nIt is working if I'm accessing the link from the nav bar.\nIf I reload the page, it give me 404.. why ?\n\n```\n\n \n Home\n About\n \n \n \n \n \n\n```\n\nAfter reload:\nThis localhost page can’t be found No webpage was found for the web address: http://localhost:5000/charts\n\n========================================\n\nTop Answer:\nAs mentioned in one of the comments above, if using roll-up, the following combination of scripts will work when calling `npm run dev`\n\n```\n\"scripts\": {\n \"build\": \"rollup -c\",\n \"dev\": \"rollup -c -w\",\n \"start\": \"sirv public --single\"\n }\n```\n\n========================================\n\nCode:\n```text\n<Router url=\"{url}\">\n <nav>\n <Link to=\"/\">Home</Link>\n <Link to=\"charts\">About</Link>\n </nav>\n <div>\n <Route path=\"charts\" component=\"{About}\" />\n <Route path=\"/\"><Home /></Route>\n </div>\n</Router>\n```\n\n```text\n\"scripts\": {\n \"start\": \"sirv public --single\",\n \"start:dev\": \"sirv public --dev --single\"\n},\n```\n\n```text\nindex.html\n```\n\n```text\n/\n```\n\n```text\nsirv\n```\n\n```text\n--single\n```\n\n```text\nchart\n```\n\n```js\n\"scripts\": {\n \"build\": \"rollup -c\",\n \"dev\": \"rollup -c -w\",\n \"start\": \"sirv public --single\"\n }\n```\n\n```text\nnpm run dev\n```\n\n```text\nindex.html\n```\n\n```text\n/*\n```\n\n```text\n/\n```\n\n```text\n*\n```\n\n```text\n/\n```\n\n```text\n/index.html\n```\n\n```text\nwww.example.com/about\n```\n\n```text\nwww.example.com/index.html\n```\n\n```text\nRewrite\n```\n\n```text\nRedirect\n```\n\n```text\n\"start\": \"sirv public --no-clear\"\n```\n\n```text\n\"start\": \"sirv public -s --no-clear\"\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- Is there a solution when rollup is involved?\n- @LSR I think that rollup will call npm run start when it finishes building, so a config like this should work: `\"scripts\": {dev\": \"rollup -c -w\", \"start\": \"sirv public --single\"}`\n- Anyone who's using rollup, the above modifications to script works.","metadata":{"transformedAt":"2026-08-18T18:33:40.671Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":151,"estimatedTokens":509}}174{"id":"stack-66965954","source":"stackoverflow","questionId":66965954,"title":"Build error after updating Svelte: Package subpath './compiler.js' is not defined by \"exports\"","tags":["javascript","npm","package.json","svelte"],"text":"Title: Build error after updating Svelte: Package subpath './compiler.js' is not defined by \"exports\"\nTags: javascript, npm, package.json, svelte\nSource: Stack Overflow\n\nQuestion:\n### Problem\n\nI was on *Svelte* version 3.0.0 and used `npm i svelte@latest` to update to the most recent version. Now I can't get the app to run, I always get this errror:\n\n[!] Error: Package subpath './compiler.js' is not defined by \"exports\" in /home/blub/coding/bla/node_modules/svelte/package.json\nError [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './compiler.js' is not defined by \"exports\" in /home/blub/coding/bla/node_modules/svelte/package.json\n\n### Failed Solutions\n\nI also updated *rollup-plugin-svelte* to version 5.2.0, but that did not help. Are there any other dependencies I also have to update? Here is a list of my dependencies:\n\n```\n\"devDependencies\": {\n \"node-sass\": \"^4.12.0\",\n \"npm-run-all\": \"^4.1.5\",\n \"rollup\": \"^2.44.0\",\n \"rollup-plugin-commonjs\": \"^10.0.0\",\n \"rollup-plugin-livereload\": \"^1.0.0\",\n \"rollup-plugin-node-resolve\": \"^5.2.0\",\n \"rollup-plugin-svelte\": \"^5.2.3\",\n \"rollup-plugin-terser\": \"^4.0.4\",\n \"svelte\": \"^3.37.0\",\n \"svelte-preprocess-sass\": \"^0.2.0\"\n },\n \"dependencies\": {\n \"axios\": \"^0.19.0\",\n \"sirv-cli\": \"^0.4.4\"\n },\n```\n\n========================================\n\nTop Answer:\nI had an old Svelte project and did not have time to update it all. I found downgrading Svelte to 3.29.4 fixed the issue.\n\n```\nnpm i -D svelte@3.29.4\n```\n\n========================================\n\nCode:\n```text\n\"devDependencies\": {\n \"node-sass\": \"^4.12.0\",\n \"npm-run-all\": \"^4.1.5\",\n \"rollup\": \"^2.44.0\",\n \"rollup-plugin-commonjs\": \"^10.0.0\",\n \"rollup-plugin-livereload\": \"^1.0.0\",\n \"rollup-plugin-node-resolve\": \"^5.2.0\",\n \"rollup-plugin-svelte\": \"^5.2.3\",\n \"rollup-plugin-terser\": \"^4.0.4\",\n \"svelte\": \"^3.37.0\",\n \"svelte-preprocess-sass\": \"^0.2.0\"\n },\n \"dependencies\": {\n \"axios\": \"^0.19.0\",\n \"sirv-cli\": \"^0.4.4\"\n },\n```\n\n```text\nnpm i svelte@latest\n```\n\n```sh\nnpm i -D rollup-plugin-svelte@6.1.1\n# or with yarn\nyarn add -D rollup-plugin-svelte@6.1.1\n```\n\n```text\nv3.29.5\n```\n\n```text\nrollup-plugin-svelte\n```\n\n```text\nv6.1.1\n```\n\n```text\nnpm i -D svelte@3.29.4\n```\n\n========================================\n\nComments:\n- I guess this one is fix in the `v6.1.1` of `rollup-plugin-svelte`.\n- Yes, updating it fixed my issue. Thanks. Do you want to post this as an answer so that I can accept it?\n- Here is the command to update `rollup-plugin-svelte` to at least `v6.1.1`. `npm i rollup-plugin-svelte@6.1.1`","metadata":{"transformedAt":"2026-08-18T18:33:40.671Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":98,"estimatedTokens":639}}175{"id":"stack-71668489","source":"stackoverflow","questionId":71668489,"title":"SvelteKit: How to Use Named Slots Based on Route","tags":["svelte","sveltekit"],"text":"Title: SvelteKit: How to Use Named Slots Based on Route\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am fairly new to SvelteKit and can't figure out an issue related to slots. I'm trying to make an app layout that has a master and detail pane where the contents of the master and detail are determined based on the route.\n\nLet's say I have a `__layout.svelte` file like this:\n\n```\n//-------------------------\n// routes/__layout.svelte\n//-------------------------\n\n \n \n\n```\n\nThen I have another page like this (with several more route pages that are similar):\n\n```\n//-------------------------\n// routes/users.svelte\n//-------------------------\n\n Users master content...\n\n Users detail content...\n\n```\n\nWhen I navigate to `http://localhost:3000/users` I just get an error that says I can't use `slot=\"\"` in `users.svelte` because it's not inside a child component.\n\nAm I going about this all wrong? How would you pull off a similar app layout in SvelteKit?\n\n========================================\n\nCode:\n```text\n//-------------------------\n// routes/__layout.svelte\n//-------------------------\n<main>\n <slot name=\"master\" />\n <slot name=\"detail\" />\n</main>\n```\n\n```text\n//-------------------------\n// routes/users.svelte\n//-------------------------\n\n<div slot=\"master\">\n Users master content...\n</div>\n\n<div slot=\"detail\">\n Users detail content...\n</div>\n```\n\n```text\n__layout.svelte\n```\n\n```text\nhttp://localhost:3000/users\n```\n\n```text\nslot=\"\"\n```\n\n```text\nusers.svelte\n```\n\n```text\n//-------------------------\n// lib/MasterDetail.svelte\n//-------------------------\n<main>\n <slot name=\"master\" />\n <slot name=\"detail\" />\n</main>\n```\n\n```text\n//-------------------------\n// routes/users.svelte\n//-------------------------\n<script>\nimport MasterDetail from \"$lib/MasterDetail.svelte\"\n</script>\n\n<MasterDetail>\n <div slot=\"master\">\n Users master content...\n </div>\n\n <div slot=\"detail\">\n Users detail content...\n </div>\n</MasterDetail>\n```\n\n========================================\n\nComments:\n- Great answer, thank you! Knowing that the `__layout` can only have a single, default slot is the key piece I was missing. I have tried your suggested alternative and it works great. Thanks again!\n- I am having a similar issue where this does not seem to work. Basically I have full screen panels on some pages and they need to have the highest z-index. However in my layout I had to fiddle with z-index of main to make a \"reveal\" footer. On the pages with a panel, I'd like to put it outside of the `main` tag. I could solve it by having the main tag on each page, but it is not ideal. The alternative is have the panels in the layout and trigger them from pages, but again, not ideal. If anybody has a workaround for this?...\n- @Mig you could look into using portals github.com/romkor/svelte-portal for the full screen panels. That allows for differences in the component tree and dom tree.\n- @BobFanger Ah nice thank you! It is a bit like what we do with `svelte:head` for the head tag. Exactly what I'd like to do sometimes. I'll give it a try.","metadata":{"transformedAt":"2026-08-18T18:33:40.671Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":115,"estimatedTokens":768}}176{"id":"stack-65703633","source":"stackoverflow","questionId":65703633,"title":"Typing svelte $store variable","tags":["typescript","types","svelte","svelte-store"],"text":"Title: Typing svelte $store variable\nTags: typescript, types, svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI wanted to know if it is possible de type the dollar sign value of a custom svelte store ?\n\nFrom this example :\n\n**app.svelte**\n\n```\n\n import { count } from './stores.js';\n\n### The count is {$count}\n\n+\n-\nreset\n```\n\n**stores.js**\n\n```\nimport { writable } from 'svelte/store';\n\nfunction createCount() {\n const { subscribe, set, update } = writable(0);\n\n return {\n subscribe,\n increment: () => {},\n decrement: () => {},\n reset: () => {}\n };\n}\n\nexport const count = createCount();\n```\n\nHow do you type the variable `{$count}` with your own typescript interface ?\n\nThank you for your help\n\n========================================\n\nCode:\n```html\n<script>\n import { count } from './stores.js';\n</script>\n\n<h1>The count is {$count}</h1>\n\n<button on:click={count.increment}>+</button>\n<button on:click={count.decrement}>-</button>\n<button on:click={count.reset}>reset</button>\n```\n\n```js\nimport { writable } from 'svelte/store';\n\nfunction createCount() {\n const { subscribe, set, update } = writable(0);\n\n return {\n subscribe,\n increment: () => {},\n decrement: () => {},\n reset: () => {}\n };\n}\n\nexport const count = createCount();\n```\n\n```text\n{$count}\n```\n\n```text\nimport { Writable, writable } from \"svelte/store\"\n\ntype CountStore = {\n subscribe: Writable<number>[\"subscribe\"]\n \n increment: () => void\n decrement: () => void\n reset: () => void\n}\n\nfunction createCount(): CountStore {\n.\n.\n.\n```\n\n```text\nstores.js\n```\n\n```text\nstores.ts\n```\n\n```text\njs\n```\n\n```text\nts\n```\n\n========================================\n\nComments:\n- Just in case, this does not work in while using Vite for a Svelte project.\n- Is ther guidance on how to do this using vite?\n- Although it is an old question, I think there is something wrong! Why do you import `writable` twice? Please correct me if I'm wrong.\n- @MBParvezRony 10x for the correction.\n- This really does not answer the question if you're not using Typescript. :(","metadata":{"transformedAt":"2026-08-18T18:33:40.671Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":122,"estimatedTokens":516}}177{"id":"stack-51399018","source":"stackoverflow","questionId":51399018,"title":"Svelte conditional element class reported as a syntax error","tags":["javascript","css","svelte"],"text":"Title: Svelte conditional element class reported as a syntax error\nTags: javascript, css, svelte\nSource: Stack Overflow\n\nQuestion:\nI am making an `if` block per the Svelte Guide for if blocks. It seems simple enough, but Svelte thinks it's a syntax error:\n\n```\n[!] (svelte plugin) ParseError: Unexpected character '#'\npublic\\js\\templates\\works.html\n3: \n4: {#each works as work, index}\n5: \n ^\n6: \n7: \n```\n\nWhy isn't `{#if index === currentIndex }` considered valid? How can I do a conditional in Svelte?\n\nNot I could create seperate `class=` blocks for **every possible outcome**, but that's a massive amount of work.\n\n========================================\n\nTop Answer:\nSince Svelte 2.13 you can also do\n\n```\n...\n```\n\nSee https://svelte.dev/docs#class_name\n\n========================================\n\nCode:\n```text\n[!] (svelte plugin) ParseError: Unexpected character '#'\npublic\\js\\templates\\works.html\n3: <div class=\"slides js_slides\">\n4: {#each works as work, index}\n5: <div class=\"js_slide {#if index === currentIndex }selected{/if} {#if index === 0 }first{/if}\">\n ^\n6: <img src=\"/images/work/screenshots/{ works[index].slug }-0.{ works[index].imageExtension }\"/>\n7: </div>\n```\n\n```text\nif\n```\n\n```text\n{#if index === currentIndex }\n```\n\n```text\nclass=\n```\n\n```html\n<div class=\"\n js_slide\n {index === currentIndex ? 'selected' : ''}\n {index === 0 ? 'first' : ''}\n\">\n <img src=\"/images/work/screenshots/{ works[index].slug }-0.{ works[index].imageExtension }\"/>\n</div>\n```\n\n```text\n<!-- language: lang-html -->\n\n<div class=\"js_slide {getClass(work, index, currentIndex)}\">\n <img src=\"/images/work/screenshots/{ works[index].slug }-0.{ works[index].imageExtension }\"/>\n</div>\n```\n\n```text\n{#if...\n```\n\n```text\n{#each...\n```\n\n```text\ndata-selected={index === currentIndex}\n```\n\n```text\ndata=first={index === 0}\n```\n\n```text\n[data-selected=true]\n```\n\n```text\n<div class:selected={index === currentIndex}>...</div>\n```\n\n```text\n{#each Array.from(Array(b+1).keys()).slice(a) as i }\n\n <div class=\"{ i===4 ? \"border-l-2 border-blue-500\" : \"\"} p-3 space-y-4\">\n some sample text\n </div>\n{/each}\n```\n\n```text\n{#each Array.from(Array(15+1).keys()).slice(1) as i }\n\n <div class=\"{ i===3 ? \"border-l-2 border-blue-500\" : \"\"} p-3 space-y-4\">\n some sample text\n </div>\n{/each}\n```\n\n========================================\n\nComments:\n- Blocks (`{#if...`, `{#each...` etc) can't be used inside attributes. Instead, the convention is to use ternary expressions (`{index === currentIndex ? 'selected' : ''} {index === 0 ? 'first' : ''}`, or to use a helper (e.g. `class={getClass(work, index, currentIndex)}`). Some people prefer to do things like `data-selected={index === currentIndex} data=first={index === 0}`\n- thanks — have moved my comment to an answer\n- See also stackoverflow.com/questions/45324684/…\n- Teneary expressions does not seem to work right now in svelte 3. BUG! See also this question: :stackoverflow.com/questions/58081289/…\n- What is the bug? Ternary expressions work fine: svelte.dev/repl/c45c86b0f3784013a7ab8e3c54a27e2d?version=3.1‌​2.1","metadata":{"transformedAt":"2026-08-18T18:33:40.671Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":127,"estimatedTokens":792}}178{"id":"stack-70494033","source":"stackoverflow","questionId":70494033,"title":"Setting static asset cache TTL in SvelteKit","tags":["svelte","vite","sveltekit"],"text":"Title: Setting static asset cache TTL in SvelteKit\nTags: svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am serving font and CSS files from `/static` using the default SvelteKit application template. I am using SvelteKit Node.js adapter.\n\nThe default cache time-to-live (TTL) seems to be 4 hours for `/static` files. I am not sure if this is set by SvelteKit/Vite itself or does any of the middleboxes like CloudFlare make this assumption.\n\nHow can I override this in SvelteKit? I assume this needs to be configured in Vite somehow, so that the `/static` files are server with correct HTTP caching headers. As the font files do not change, I would like to set them to be immutable and avoid the user web browser redownloading the files again.\n\nhttps://i.sstatic.net/tB4Hh.png\n\n========================================\n\nTop Answer:\nI've been having trouble with fonts in sveltekit recently, and it seems that the currently accepted answer is a tiny bit outdated, so I'll add some new relevant info.\n\nThe `/static` folder is not handled the same way, currently there are no cache settings hardcoded to handle the static assets, so no cache headers are sent at all.\n\nCache headers are still sent for whatever Vite puts in `/${manifest.appPath}/immutable/`, and after looking at some discussions on svelkit discord, it seems that the easiest way to handle cache headers for fonts is to put them under `/src` instead of static and let vite handle it with the css `url()`.\n\nFor example (in svelte context), you can put your fonts under `/src/lib/fonts` and in a css file (that must also be under `/src` or imported in a way Vite handles it):\n\n```\n@font-face {\n font-family: 'Inter';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('$lib/fonts/Inter-Regular.woff2') format('woff2');\n}\n```\n\nAnd Vite will now rebase the url and serve the font under `/${manifest.appPath}/immutable/` thus sending the cache control headers properly.\n\nSvelte currently does not uses `E-Tag` header for that, but vite will append a hash to the font (like `Inter-Regular.COLGFB3M.woff2`) and will automatically map it to the css file aswell, so modifying the font without changing it's name should not be a problem.\n\nYou can also solve this other ways, like setting an nginx reverse proxy or configuring a service worker to handle the cache.\n\n========================================\n\nCode:\n```text\n/static\n```\n\n```text\n/static\n```\n\n```text\n/static\n```\n\n```text\n/tmp # wget -S \"http://localhost:3000/fonts.css\"\n\n--2021-12-31 00:35:00-- http://localhost:3000/fonts.css\nResolving localhost (localhost)... 127.0.0.1\nConnecting to localhost (localhost)|127.0.0.1|:3000... connected.\nHTTP request sent, awaiting response...\n HTTP/1.1 200 OK\n Vary: Accept-Encoding\n Content-Length: 2249\n Content-Type: text/css\n Last-Modified: Thu, 30 Dec 2021 23:34:41 GMT\n ETag: W/\"2249-1640907281407\"\n Cache-Control: public,max-age=31536000,immutable\n Date: Thu, 30 Dec 2021 23:35:00 GMT\n Connection: keep-alive\n Keep-Alive: timeout=5\nLength: 2249 (2.2K) [text/css]\n```\n\n```text\n@sveltejs/adapter-node@next\n```\n\n```text\ncache-control\n```\n\n```html\n<script context=\"module\">\n export async function load({ params, fetch }) {\n //...\n return {\n maxage: 60 // 1 minute\n };\n }\n</script>\n```\n\n```css\n@font-face {\n font-family: 'Inter';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('$lib/fonts/Inter-Regular.woff2') format('woff2');\n}\n```\n\n```text\n/static\n```\n\n```text\n/${manifest.appPath}/immutable/\n```\n\n```text\n/src\n```\n\n```text\nurl()\n```\n\n```text\n/src/lib/fonts\n```\n\n```text\n/src\n```\n\n```text\n/${manifest.appPath}/immutable/\n```\n\n```text\nE-Tag\n```\n\n```text\nInter-Regular.COLGFB3M.woff2\n```\n\n========================================\n\nComments:\n- I have the exact same question, and I wonder how you solved it. The accepted answer doesn't really explain what you did? It only sets the `public,max-age=31536000,immutable` cache header for files within the `/${manifest.appPath}/immutable/` path, which doesn't include the `/static` folder where my font files are also placed.\n- Your question is different. This question is not about setting TTL for pages, but setting TTL for static assets. I suggest that you post self-answer on a new self-question and I can upvote stackoverflow.com/help/self-answer","metadata":{"transformedAt":"2026-08-18T18:33:40.671Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":145,"estimatedTokens":1093}}179{"id":"stack-58376357","source":"stackoverflow","questionId":58376357,"title":"How to inject a service into svelte grandchild components?","tags":["dependency-injection","svelte"],"text":"Title: How to inject a service into svelte grandchild components?\nTags: dependency-injection, svelte\nSource: Stack Overflow\n\nQuestion:\nI have several service classes (with some \"get data for these params\" and some \"calculate stuff for these params\" methods) I'd like to inject into several components in my Svelte component hierarchy. At the moment, I'm seeing the following options for that, none of them very attractive:\n\n- **Pass the services as props**. Some intermediate components don't need the services and would just pass them on. And it bloats the number of props.\n\n- **Wrap the services with a store**. This feels like misusing the reactive store feature for something it was not meant for. The data that comes out of the service is mostly static and not very reactive.\n\n- **Use the services in the top-level component, pass down the results as props to child components**. This would bloat the number of props even more, as I have some \"layout\" components in between the root and the child components. Those layout components would then have to pass on all the props.\n\nIn Vue, I would write a plugin that adds to the properties available in all Vue components. What is the Svelte way to do this?\n\n========================================\n\nTop Answer:\nOne option is to use the es6 feature where exported vars are able to be changed *from within the file they are declared in* & helps in the situation that \"the services need some setup that I do in my entry point js. The setup comes from the browser environment, so I can't \"bake in\" the config values\" e.g.\n\n***main.js***\n\n```\nimport AppUI from './App.html'\nimport { AppStore } from './store.js'\nimport { HttpService } from './http.js'\nimport { cfg } from './cfg.js'\nimport { initMain } from './services.js'\n\n// we're off\ninitMain( AppUI, AppStore, HttpService, cfg )\n```\n\n***services.js***\n\n```\nlet app, store, http\n\nfunction initMain( App, Store, HttpService, cfg ) {\n\n http = new HttpService(cfg) \n store = new Store(cfg) \n app = new App({ store, target: document.body }) \n }\n\n}\n\nexport { initMain, app, store, http }\n```\n\n========================================\n\nCode:\n```html\n<script>\n import config from './config';\n import createServices from './services';\n import App from './App.svelte';\n\n const services = createServices(config);\n</script>\n\n{#await promise then services}\n <App {services} />\n{/await}\n```\n\n```html\n<script>\n import Child from './Child.svelte';\n export let services;\n\n setContext('services', services);\n</script>\n\n<Child /> <-- contains Grandchild.svelte\n```\n\n```html\n<script>\n const services = getContext('services');\n const promise = services.getData();\n</script>\n\n{#await promise then data}\n <div>Hello {data.username}!</div>\n{/await}\n```\n\n```js\nimport { writable } from 'svelte/store';\n\nexport const serviceStore = writable(null);\n```\n\n```html\n<script>\n import serviceStore from './services-store';\n import Child from './Child.svelte';\n\n export let services;\n\n serviceStore.set(services);\n</script>\n\n<Child /> <-- contains Grandchild.svelte\n```\n\n```html\n<script>\n import serviceStore from './services-store';\n\n const promise = $serviceStore.getData();\n</script>\n\n{#await promise then data}\n <div>Hello {data.username}!</div>\n{:catch err}\n <p>Error! {err.message}</p>\n{/await}\n```\n\n```js\nimport serviceStore from './services-store';\n\nlet mockService;\nbeforeEach(async () => {\n mockService = { getData: jest.fn().mockResolvedValue('helloitsjoe') };\n serviceStore.set(mockService);\n});\n\n...\n\nit('shows username', async () => {\n render(Grandchild);\n const name = await findByText('helloitsjoe');\n expect(name).toBeTruthy();\n});\n\nit('shows error', async () => {\n // Override mock service\n mockService.getData.mockRejectedValue(new Error('oh no!'));\n render(Grandchild);\n const message = await findByText('oh no!');\n expect(message).toBeTruthy();\n});\n```\n\n```text\nimport()\n```\n\n```text\nsetContext\n```\n\n```text\nonMount\n```\n\n```text\nApp\n```\n\n```text\nsetContext\n```\n\n```text\nApp\n```\n\n```text\n{#await promise}\n```\n\n```text\n@testing-library/svelte\n```\n\n```text\ngetContext\n```\n\n```text\nsetContext\n```\n\n```text\nTestContextWrapper.svelte\n```\n\n```text\nimport AppUI from './App.html'\nimport { AppStore } from './store.js'\nimport { HttpService } from './http.js'\nimport { cfg } from './cfg.js'\nimport { initMain } from './services.js'\n\n// we're off\ninitMain( AppUI, AppStore, HttpService, cfg )\n```\n\n```text\nlet app, store, http\n\nfunction initMain( App, Store, HttpService, cfg ) {\n\n http = new HttpService(cfg) \n store = new Store(cfg) \n app = new App({ store, target: document.body }) \n }\n\n}\n\nexport { initMain, app, store, http }\n```\n\n========================================\n\nComments:\n- If it is not reactive you have the set and get Context;\n- Is there a reason you can't just import them from a separate JavaScript file?\n- The services need some setup that I do in my entry point js. The setup comes from the browser environment, so I can't \"bake in\" the config values.\n- @chiborg Have you found a way to do hierarchical injections?\n- Thanks for your elaborate explanation on how to achieve this. It all does feel like a really large amount of work (with extra caveats) to basically get to IoC (inversion of control) which is just such a proven and versatile tool that I think should come out of the box for more serious frameworks. And I feel this is exactly what a compiler should be able to do, so I'm going to figure out why this was not thought out better. 2 days into Svelte coming from Angular (and I really like Svelte) I already feel this is going to annoy and bite me in the long run.","metadata":{"transformedAt":"2026-08-18T18:33:40.671Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":226,"estimatedTokens":1419}}180{"id":"stack-74969417","source":"stackoverflow","questionId":74969417,"title":"How to import image and use in css in sveltekit","tags":["svelte","sveltekit"],"text":"Title: How to import image and use in css in sveltekit\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm using sveltekit and I'm wondering how to import an image and use it in a CSS background property.\n\nHere's what I've tried:\n\n```\n\n import img from '$lib/images/background-shaded.jpg';\n\n \n\n### Hello World\n\n div {\n background-image: url({img});\n }\n\n```\n\nFor now, I'm just putting the image in the the static folder and using via it's URL. Maybe that's the recommended approach...\n\nThanks.\n\n========================================\n\nCode:\n```html\n<script>\n import img from '$lib/images/background-shaded.jpg';\n</script>\n\n<div>\n <h1>Hello World</h1>\n</div>\n\n<style>\n div {\n background-image: url({img});\n }\n</style>\n```\n\n```css\ndiv {\n background-image: url(\"$lib/images/background-shaded.jpg\");\n}\n```\n\n========================================\n\nComments:\n- How can I make it work with inline styling?\n- @pasta64: Import the image in the script as shown in the question and insert the URL in the `style` attribute. Pretty much what is in the question's CSS, just in the attribute.\n- Ok, thanks. I was searching for a faster way because I have a big array of images...\n- @pasta64: You could maybe use a glob import (eager) and loop over the list via `{#each}`.\n- I had to put double quotes around the path, like this: `background-image: url(\"$lib/images/background-shaded.jpg\");`, otherwise I got a compile error.\n- @TylerCollier: Some preprocessors take care of that automatically, may also depend on exact path. Also added quotes to the answer for better compatibility 👍","metadata":{"transformedAt":"2026-08-18T18:33:40.671Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":61,"estimatedTokens":403}}181{"id":"stack-79329972","source":"stackoverflow","questionId":79329972,"title":"What is the correct TypeScript type for the `children` property in Svelte 5?","tags":["svelte","svelte-5"],"text":"Title: What is the correct TypeScript type for the `children` property in Svelte 5?\nTags: svelte, svelte-5\nSource: Stack Overflow\n\nQuestion:\nIn Svelte 5 it now retrieves children from the the `$props()` rune. I wasn't able to find any documentation stating how the props reserved `children` property should be typed and the type is not included in the `$props()` rune by default.\n\n```\n\n interface Props {\n children: ?????; // What do I type this as?\n }\n const { children }: Props = $props();\n\n {@render children?.()}\n\n```\n\n========================================\n\nCode:\n```html\n<script lang=\"ts\">\n interface Props {\n children: ?????; // What do I type this as?\n }\n const { children }: Props = $props();\n</script>\n\n<div>\n {@render children?.()}\n</div>\n```\n\n```text\n$props()\n```\n\n```text\nchildren\n```\n\n```text\n$props()\n```\n\n```html\n<script lang=\"ts\">\n import type { Snippet } from 'svelte';\n\n interface Props {\n children: Snippet;\n }\n const { children }: Props = $props();\n</script>\n\n<div>\n {@render children?.()}\n</div>\n```\n\n```text\nchildren\n```\n\n```text\nSnippet\n```\n\n```text\n'svelte'\n```\n\n========================================\n\nComments:\n- Docs on this are here.","metadata":{"transformedAt":"2026-08-18T18:33:40.671Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":77,"estimatedTokens":302}}182{"id":"stack-68159400","source":"stackoverflow","questionId":68159400,"title":"when clicked on an href the new URL doesn't reload the page in Svelte","tags":["svelte","sapper"],"text":"Title: when clicked on an href the new URL doesn't reload the page in Svelte\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI'm currently trying to redirect the user to a new page when they clicked on a href link.\nThe problem is that the url does change per se, but only when I manually hit \"reload\", the page actually refreshes and shows the new data.\n\nHow I build the href-link:\n\n```\nresultString += \"\";\nresultString += this.note['name'][i]['#text'];\nresultString += \"\";\n```\n\nThe resultString then gets pushed to an array and is correctly read out in another component.\n\nThe problem is, that when redirected, the id in the url visibly changes and is updated in the url but the page doesn't reload.\n\nfor example:\non page with `'id=xy'` the URL is: `'/edition/id=xy'` and on this page, the href `'/edition/id=z'` is displayed.\nWhen clicking on this href, the url changes visibly to `'/edition/id=z'` but the page doesn't reload.\n\nDoes anyone know how to solve this?\n\n========================================\n\nTop Answer:\nOnce I encountered the same behavior. I don't remember what it was, but I cured it with **target=\"_self\"**\n\n========================================\n\nCode:\n```js\nresultString += \"<a href='/edition/id=\" + this.note['name'][i]['hkg:persKey'] + \"'>\";\nresultString += this.note['name'][i]['#text'];\nresultString += \"</a>\";\n```\n\n```text\n'id=xy'\n```\n\n```text\n'/edition/id=xy'\n```\n\n```text\n'/edition/id=z'\n```\n\n```text\n'/edition/id=z'\n```\n\n```text\n<a rel=\"external\" href=\"path\">Path</a>\n```\n\n```text\nrel=external\n```\n\n```text\n<a data-sveltekit-reload href=\"/path\">Path</a>\n```\n\n```ts\nconst {data} = $props();\n\n\n// Wrong => if the data changes, the title doesn’t\nconst title = data.title;\n\n// Good => the title is now reactive\nconst title = $derived(data.title);\n```\n\n```ts\nexport let data: PageData;\n\n$: title = data.title; // <-- add `$:` before to make this reactive\n```\n\n```text\n$derived()\n```\n\n```text\nrel=\"external\"\n```\n\n```text\ndata-sveltekit-reload\n```\n\n========================================\n\nComments:\n- Any updates on this one? Using `rel=\"external\"` feels like cheating.\n- I was navigating to a local element using `Click` and I noticed it refreshed the whole page every time. Apparently this `target=\"_self\"` is a thing you're supposed to do when linking internally. I dunno how I missed it.\n- Silly feature, break standard linking html :-/\n- Found this question while trying to reload data in my page when the params change, so I don't want the page to really reload. So you can use a reactive statement alongside the params store (from `import { page } from \"$app/stores\";`) : `$: loadData($page.params.id)`","metadata":{"transformedAt":"2026-08-18T18:33:40.671Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":104,"estimatedTokens":663}}183{"id":"stack-59842528","source":"stackoverflow","questionId":59842528,"title":"How can I add the Bootstrap module in a Svelte JavaScript application?","tags":["npm","bootstrap-4","svelte"],"text":"Title: How can I add the Bootstrap module in a Svelte JavaScript application?\nTags: npm, bootstrap-4, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm very new to Svelte (like many of us ^^), and I didn't manage to add Bootstrap to my application. I tried to run 'npm add bootstrap', but it said that I need peer jQuery dependencies. Here is the terminal render.\n\nWhat I don't understand is why the package has been added, and I can't still use the Bootstrap classes. Second point, why does it talk about peer dependencies? What's the link here?\n\nI don't know if I'm missing something, but if you guys got the solution, it will help a lot. Thank you.\n\n```\nnpm add bootstrap\n```\n\nOutput:\n\n```\nnpm WARN bootstrap@4.4.1 requires a peer of jquery@1.9.1 - 3 but none is installed. You must install peer dependencies yourself.\n\nnpm WARN bootstrap@4.4.1 requires a peer of popper.js@^1.16.0 but none is installed. You must install peer dependencies yourself.\nnpm WARN svelte-app@1.0.0 No repository field.\nnpm WARN svelte-app@1.0.0 No license field.\n\n+ bootstrap@4.4.1\nadded 1 package from 2 contributors and audited 9125 packages in 8.047s\nfound 0 vulnerabilities\n```\n\n========================================\n\nTop Answer:\nThis answer is an addition to the TwitchBronBron's answer's second option. (I cannot comment yet..)\n\nInstead of copying all of Bootstrap's files to the `public` folder, you can also pick and choose. For example, I only needed the minified CSS and the bundled minified JavaScript, so I configured the `copy` plugin like this:\n\n```\n//...\nimport copy from \"rollup-plugin-copy\";\n\nexport default {\n //...\n plugins: [\n //...\n copy({\n targets: [\n {\n src: \"node_modules/bootstrap/dist/css/bootstrap.min.css\",\n dest: \"public/vendor/bootstrap/css\",\n },\n {\n src: \"node_modules/bootstrap/dist/js/bootstrap.bundle.min.js\",\n dest: \"public/vendor/bootstrap/js\",\n },\n ],\n }),\n //...\n ],\n //...\n};\n```\n\nThe CSS can be included in the `` tag in `public/index.html`:\n\n```\n\n```\n\nThe JavaScript can be included inside of the `` tag (at the end) in `public/index.html`:\n\n```\n\n```\n\n========================================\n\nCode:\n```none\nnpm add bootstrap\n```\n\n```none\nnpm WARN bootstrap@4.4.1 requires a peer of jquery@1.9.1 - 3 but none is installed. You must install peer dependencies yourself.\n\nnpm WARN bootstrap@4.4.1 requires a peer of popper.js@^1.16.0 but none is installed. You must install peer dependencies yourself.\nnpm WARN svelte-app@1.0.0 No repository field.\nnpm WARN svelte-app@1.0.0 No license field.\n\n+ bootstrap@4.4.1\nadded 1 package from 2 contributors and audited 9125 packages in 8.047s\nfound 0 vulnerabilities\n```\n\n```js\n//...\nimport copy from 'rollup-plugin-copy'\n\nexport default {\n //...\n plugins: [\n //...\n copy({\n targets: [{\n src: 'node_modules/bootstrap/dist/**/*',\n dest: 'public/vendor/bootstrap'\n }]\n }),\n //...\n ],\n //...\n};\n```\n\n```text\nbootstrap\n```\n\n```text\n/public\n```\n\n```text\npublic\n```\n\n```text\npublic/index.html\n```\n\n```text\n<link rel='stylesheet' href='bootstrap/dist/css/bootstrap.min.css'>\n```\n\n```text\n/public\n```\n\n```text\nrollup.config.js\n```\n\n```text\ncopy\n```\n\n```text\npublic/index.html\n```\n\n```text\n<link rel='stylesheet' href='vendor/bootstrap/css/bootstrap.min.css'>\n```\n\n```js\n//...\nimport copy from \"rollup-plugin-copy\";\n\nexport default {\n //...\n plugins: [\n //...\n copy({\n targets: [\n {\n src: \"node_modules/bootstrap/dist/css/bootstrap.min.css\",\n dest: \"public/vendor/bootstrap/css\",\n },\n {\n src: \"node_modules/bootstrap/dist/js/bootstrap.bundle.min.js\",\n dest: \"public/vendor/bootstrap/js\",\n },\n ],\n }),\n //...\n ],\n //...\n};\n```\n\n```html\n<link rel='stylesheet' href='vendor/bootstrap/css/bootstrap.min.css'>\n```\n\n```html\n<script src=\"vendor/bootstrap/js/bootstrap.bundle.min.js\"></script>\n```\n\n```text\npublic\n```\n\n```text\ncopy\n```\n\n```text\n<head>\n```\n\n```text\npublic/index.html\n```\n\n```text\n<body>\n```\n\n```text\npublic/index.html\n```\n\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"utf-8\" />\n <link rel=\"icon\" href=\"%sveltekit.assets%/favicon.png\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <link rel=\"stylesheet\" href=\"../node_modules/bootstrap/dist/css/bootstrap.min.css\">\n %sveltekit.head%\n</head>\n\n<body>\n <div>%sveltekit.body%</div>\n <script src=\"../node_modules/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n</body>\n\n</html>\n```\n\n```text\nnpm install\n```\n\n```text\nyarn\n```\n\n```text\nnpm install bootstrap\n```\n\n```text\nnpm i bootstrap\n```\n\n```text\nyarn add bootstrap\n```\n\n```text\npopper.js\n```\n\n```text\nnpm i @popperjs/core jquery\n```\n\n```js\nimport { onMount } from 'svelte';\n\nonMount(async () => {\n await import('bootstrap/dist/css/bootstrap.css')\n window.bootstrap = await import('bootstrap/dist/js/bootstrap.esm.js')\n // Some code that uses Bootstrap, e.g.:\n const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle=\"tooltip\"]')\n const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl))\n})\n```\n\n```html\n<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <link rel=\"icon\" href=\"%sveltekit.assets%/favicon.png\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <script src=\"%sveltekit.assets%/dist/js/bootstrap.bundle.min.js\"></script>\n %sveltekit.head%\n </head>\n <body data-sveltekit-preload-data=\"hover\">\n <div style=\"display: contents\">%sveltekit.body%</div>\n\n </body>\n</html>\n```\n\n========================================\n\nComments:\n- it's just a warning. Your bootstrap was downloaded to a node_modules folder.\n- Sure that what I thought but like I said I still can't use bootstrap classes\n- StackOverflow should allow two positive votes when someone saves our lives like that! :-)\n- I'd love to see the official Svelte docs show ways to handle this type of scenario, because this is an extremely common thing to do! Glad I could help. :)\n- If you created the app using vite, you need to add this to vite.config.ts instead. In the export default defineConfig, in plugins, add the copy command and copy targets. You may want also want to just include the bootstrap.min.css and bootstrap.min.css.map to save space.\n- I was using vite and had to use `import { viteStaticCopy } from 'vite-plugin-static-copy'` instead of `rollup-plugin-copy`, but otherwise it didn't work.\n- This works until you try `npm run build` and discover that the bootstrap files aren't find anywhere under `build/`.\n- Could I ask: Why the -1? Sure it is a hack, and perhaps not for you. But it worked for me. And it answers the OP's question. I find downvoting an answer without proving a reason is rude, but perhaps that is just me.\n- I didn't downvote, but an explanation would be in order. More than a code dump is expected of a Stack Overflow answer. There are ***way*** too many \"try this\" answers on Stack Overflow. See, e.g., *\"Explanation is vital for a good answer.\"*\n- cont' - But please, *** *** *** *** *** *** *** ***without*** *** *** *** *** *** *** *** *\"Edit:\"*, *\"Update:\"*, or similar (near *\"Changelogs\"*).","metadata":{"transformedAt":"2026-08-18T18:33:40.671Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":301,"estimatedTokens":1823}}184{"id":"stack-58068865","source":"stackoverflow","questionId":58068865,"title":"When to use Svelte's use:action vs onMount and onDestroy?","tags":["javascript","svelte","svelte-component"],"text":"Title: When to use Svelte's use:action vs onMount and onDestroy?\nTags: javascript, svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nIf we have something like a `Tooltip` class that needs to instantiate an instance, update that instance, and destroy that instance in sync with when the component is mounted, updated, and destroyed (as demonstrated in the code below), there seems to be two patterns for doing this.\n\n- Using `use:action`\n\n- Using `onMount` and `onDestroy`\n\nThe `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?\n\nExample of using `use:action`:\n\n```\n\n import Tooltip from './tooltip'\n\n export let text = ''\n\n function initTooltip(node, text) {\n const tooltip = Tooltip(node)\n tooltip.text = text\n return {\n update(text) {\n tooltip.text = text\n },\n destroy() {\n tooltip.destroy()\n }\n }\n }\n\n \n\n```\n\nExample of using `onMount` and `onDestroy`:\n\n```\n\n import Tooltip from './tooltip'\n import { onMount, onDestroy } from 'svelte'\n\n export let text = ''\n\n let node\n let tooltip\n\n onMount(() => {\n tooltip = Tooltip(node)\n tooltip.text = text\n })\n\n $: if (tooltip && tooltip.text !== text) {\n tooltip.text = text\n }\n\n onDestroy(() => {\n if (tooltip) {\n tooltip.destroy()\n }\n })\n\n \n\n```\n\n========================================\n\nCode:\n```text\n<script>\n import Tooltip from './tooltip'\n\n export let text = ''\n\n function initTooltip(node, text) {\n const tooltip = Tooltip(node)\n tooltip.text = text\n return {\n update(text) {\n tooltip.text = text\n },\n destroy() {\n tooltip.destroy()\n }\n }\n }\n</script>\n\n<div use:initTooltip={text}>\n <slot></slot>\n</div>\n```\n\n```text\n<script>\n import Tooltip from './tooltip'\n import { onMount, onDestroy } from 'svelte'\n\n export let text = ''\n\n let node\n let tooltip\n\n onMount(() => {\n tooltip = Tooltip(node)\n tooltip.text = text\n })\n\n $: if (tooltip && tooltip.text !== text) {\n tooltip.text = text\n }\n\n onDestroy(() => {\n if (tooltip) {\n tooltip.destroy()\n }\n })\n</script>\n\n<div bind:this={node}>\n <slot></slot>\n</div>\n```\n\n```text\nTooltip\n```\n\n```text\nuse:action\n```\n\n```text\nonMount\n```\n\n```text\nonDestroy\n```\n\n```text\nuse:action\n```\n\n```text\nuse:action\n```\n\n```text\nonMount\n```\n\n```text\nonDestroy\n```\n\n```text\n{#if ...}\n```\n\n========================================\n\nComments:\n- Is your tooltip a Component or a function in a js file?\n- @voscausa, `Tooltip` is a class in a js file. Calling `Tooltip(node)` will attach some event listeners to that node and return an instance that has a `.destroy()` method, that when called, removes those event listeners.\n- Got it. Thanks, Rich!","metadata":{"transformedAt":"2026-08-18T18:33:40.672Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":170,"estimatedTokens":689}}185{"id":"stack-58715992","source":"stackoverflow","questionId":58715992,"title":"import svelte component ommiting .svelte extension","tags":["rollupjs","svelte"],"text":"Title: import svelte component ommiting .svelte extension\nTags: rollupjs, svelte\nSource: Stack Overflow\n\nQuestion:\nIs there any possibility to configure rollup to import svelte components omitting `.svelte` extension ?\n\n```\nimport MyComp from \"path/MyComp\"\n```\n\nMyComp file has `.svelte` extension\n\n========================================\n\nCode:\n```js\nimport MyComp from \"path/MyComp\"\n```\n\n```text\n.svelte\n```\n\n```text\n.svelte\n```\n\n```js\nconst resolve = require('@rollup/plugin-node-resolve'); // add this to the other requires\n\nreturn {\n ... // the usual things like input, output, ...\n plugins: [\n resolve({\n extensions: ['.svelte', '.js']\n }),\n svelte(),\n ... // any other plugin you are running\n ]\n};\n```\n\n```text\n@rollup/plugin-node-resolve\n```\n\n========================================\n\nComments:\n- Also it is possible to use @rollup/plugin-alias plugin **rollup.config.js** `javascript import path from 'path'; const projectRootDir = path.resolve(__dirname); export default { plugins: [ alias({ resolve: ['.svelte','.js'], entries: [ {find:'src', replacement:path.resolve(projectRootDir, \"src\")} ], }) ]}`","metadata":{"transformedAt":"2026-08-18T18:33:40.672Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":51,"estimatedTokens":288}}186{"id":"stack-56431848","source":"stackoverflow","questionId":56431848,"title":"Dynamically loading component using import or fetch","tags":["svelte"],"text":"Title: Dynamically loading component using import or fetch\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nIs there a way to import components in svelte dynamically using fetch or import? May be a svelte file or module file created from shareable component (still don't know how that works). very new with svelte and very excited.\n\nI found some code in stackoverflow, which worked for v2. Here is the link\n\n```\n\n chat to a customer service representative\n\n{#if ChatBox}\n \n{/if}\n\n export default {\n methods: {\n async loadChatbox() {\n const { default: Chatbox } = await import('./Chatbox.html');\n this.set({ Chatbox });\n }\n }\n };\n\n```\n\n========================================\n\nCode:\n```html\n<button on:click=\"loadChatbox()\">\n chat to a customer service representative\n</button>\n\n{#if ChatBox}\n <svelte:component this={ChatBox}/>\n{/if}\n\n<script>\n export default {\n methods: {\n async loadChatbox() {\n const { default: Chatbox } = await import('./Chatbox.html');\n this.set({ Chatbox });\n }\n }\n };\n</script>\n```\n\n```html\n<!-- App.svelte -->\n<script>\n let Chatbox;\n\n function loadChatbox() {\n import('./ChatBox.svelte').then(res => Chatbox = res.default)\n }\n</script>\n\n<button on:click=\"{loadChatbox}\">Load chatbox</button>\n<svelte:component this=\"{Chatbox}\" />\n\n<!-- ChatBox.svelte -->\n<h1>Dynamically loaded chatbox</h1>\n<input />\n```\n\n```text\nthis\n```\n\n```text\nsvelte:component\n```\n\n========================================\n\nComments:\n- Great, this works. I tried it in the repl and it works as it suppose to but the rollup build fails while doing locally using the sveltejs/template. With the help of this I was also able to load external mjs in runtime to load components. Here are the related project main project, component generator and module server. I had to switch to mjs since import didn't like svelte or html served from server.\n- What do you have to do to get rollup to put the components in the build output?\n- @AndrewMao inlineDynamicImports","metadata":{"transformedAt":"2026-08-18T18:33:40.672Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":84,"estimatedTokens":498}}187{"id":"stack-62733094","source":"stackoverflow","questionId":62733094,"title":"Implement a portal in Svelte","tags":["javascript","svelte"],"text":"Title: Implement a portal in Svelte\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nIn React you can render a component in a different node using Portals:\n\n```\nReactDOM.createPortal( \n ,\n document.getElementById('id')\n);\n```\n\nSame for Vue using the portal-vue package.\n\nBut is there a way to something similar in Svelte?\n\n```\n\n \n \n \n\n```\n\n========================================\n\nTop Answer:\nAnother solution would be to use the svelte-portal library:\n\n```\n\n import Portal from 'svelte-portal';\n\n\n\n \n\n```\n\n========================================\n\nCode:\n```js\nReactDOM.createPortal( \n <Component />,\n document.getElementById('id')\n);\n```\n\n```html\n<body>\n <Header>\n <Modal /> <!-- Modal is rendered here -->\n </Header>\n\n<!-- But the Modal DOM would be injected at the body end -->\n</body>\n```\n\n```html\n<script>\nimport { onMount, onDestroy } from 'svelte'\nlet ref\nlet portal\n\nonMount(() => {\n portal = document.createElement('div')\n portal.className = 'portal'\n document.body.appendChild(portal)\n portal.appendChild(ref)\n})\n\nonDestroy(() => {\n document.body.removeChild(portal)\n})\n\n</script>\n\n<div class=\"portal-clone\">\n <div bind:this={ref}>\n <slot></slot>\n </div>\n</div>\n<style>\n .portal-clone { display: none; }\n</style>\n```\n\n```html\n<Portal>\n <Modal/>\n</Portal>\n```\n\n```text\n<body/>\n```\n\n```html\n<script>\n import Portal from 'svelte-portal';\n</script>\n\n<Portal target=\"body\">\n <Modal/>\n</Portal>\n```\n\n========================================\n\nComments:\n- FYI The general answer to this question would be to just use the DOM methods like you would without any framework. Since Svelte doesn't use a virtual DOM (unlike React or Vue), you don't really need a \"portal\" :)\n- These examples use Svelte actions, another approach that does not require a component, but enhance an existing one: - svelte.dev/repl/86ec36c27be2471f86590e0c18c7198c?version=3.2‌​3.2 - svelte.dev/repl/79e33c2d7695444b994ba74255bb1387?version=3.2‌​4.0","metadata":{"transformedAt":"2026-08-18T18:33:40.672Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":115,"estimatedTokens":507}}188{"id":"stack-74017730","source":"stackoverflow","questionId":74017730,"title":"SvelteKit: redirect() not working on server without disabling ssr","tags":["svelte","sveltekit"],"text":"Title: SvelteKit: redirect() not working on server without disabling ssr\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am using `+layout.server.ts` to redirect unauthenticated users from accessing authorized routes with this code:\n\n```\n/* +layout.server.ts */\n\nexport const load: PageServerLoad = async () => {\n // ...\n\n if (!isAuthenticatedUser && isAccessingAuthorizedRoute) {\n throw redirect(300, \"/sign-in\");\n }\n}\n```\n\nBut when I tested it by accessing an **authorized url** (let's say `/user/profile`), the browser gave me this error:\n\nhttps://i.sstatic.net/XBi8H.png\n\nI didn't know what was the problem. After some workarounds and debugging, I found out the error was caused by **server-side rendering**. Because when I turned off the **SSR** in `+layout.server.ts`, redirect worked as expected and **browser** didn't throw any error. To confirm it, I also tried disabling **SSR** for a single page and only that page was redirecting rightly.\n\nWhy is this happening? I want to use `redirect()` without disabling SSR.\n\n**UPDATE**: I also tried **redirect()** in `+page.ts`, `+page.server.ts` and `+layout.ts`. The same error also happened there when **ssr** was enabled. I don't think my client-side js code is responsible.\n\n========================================\n\nTop Answer:\nWas facing the same problem and figured out the culprit is not the status code but rather the keyword **throw**, and it works fine on +page.server.ts.\n\nDidn't work:\n\n```\nredirect(302, '/login')\n```\n\nDoes work:\n\n```\nthrow redirect(302, '/login')\n```\n\n========================================\n\nCode:\n```ts\n/* +layout.server.ts */\n\nexport const load: PageServerLoad = async () => {\n // ...\n\n if (!isAuthenticatedUser && isAccessingAuthorizedRoute) {\n throw redirect(300, \"/sign-in\");\n }\n}\n```\n\n```text\n+layout.server.ts\n```\n\n```text\n/user/profile\n```\n\n```text\n+layout.server.ts\n```\n\n```text\nredirect()\n```\n\n```text\n+page.ts\n```\n\n```text\n+page.server.ts\n```\n\n```text\n+layout.ts\n```\n\n```ts\n// ...\n\n if (!isAuthenticatedUser && isAccessingAuthorizedRoute) {\n // Wrong!\n throw redirect(300, \"/sign-in\");\n }\n\n// ...\n```\n\n```ts\n// From Svelte Documentation\n\nexport function load({ locals }) {\n if (!locals.user) {\n // Correct!\n throw redirect(307, '/login');\n }\n}\n```\n\n```text\n300\n```\n\n```text\n307\n```\n\n```text\n307\n```\n\n```text\nredirect(302, '/login')\n```\n\n```text\nthrow redirect(302, '/login')\n```\n\n========================================\n\nComments:\n- Something else on your code has the error, the variable tagName is undefined and that is breaking on the client side.\n- I will make a fresh project and try to do the same thing with dummy code\n- @ShrijiKondan I have created a new project. There are 3 svelte pages without any client-side code. I did the same on it with dummy variable and logic. I also tried it in `+page.ts`, `+page.server.ts` and `+layout.ts`. But it doesn't work without disabling SSR. It is bothering me so much.\n- I am seeing the same issue. the ssr fix works for me too but heaven knows why\n- Mysteriously (to me at least) throwing a redirect wouldn't work inside the try of a try-catch but it would if I placed it straight after.\n- @wkille well of course, redirects are made by `throw redirect(...)`, which is throwing an error. SvelteKit catches that error and handles the redirect, but if you catch the error in a try/catch block then SvelteKit can't handle it. See the note in the docs\n- Glad you were able to sort this out. I think it should work with 301 and not 300. I am not sure about this.\n- Yeah, it does work with 301, 308.\n- This works on load and actions but I can't seem to get redirects to work on server hooks.\n- With SvelteKit v2, this is now the opposite where `redirect()` alone works. You do not have to `throw` it. Source: kit.svelte.dev/docs/migrating-to-sveltekit-2","metadata":{"transformedAt":"2026-08-18T18:33:40.672Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":144,"estimatedTokens":965}}189{"id":"stack-58606345","source":"stackoverflow","questionId":58606345,"title":"Svelte head title suffix","tags":["javascript","dom","svelte","svelte-component","svelte-3"],"text":"Title: Svelte head title suffix\nTags: javascript, dom, svelte, svelte-component, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI want to add a head title suffix like `- mywebsite` on each Svelte page.\n\nI'm struggling finding how to do it with ease and simplicity.\n\nOn the svelte website source, we can see they do it manually: https://github.com/sveltejs/svelte/blob/1273f978084aaf4d7c697b2fb456314839c3c90d/site/src/routes/docs/index.svelte#L15\n\nI started creating a component like this:\n\n```\n\n export let title = false;\n\n \n {#if title}\n {title} • WebSite\n {:else}\n Website • Home suffix\n {/if}\n \n\n```\n\nBut:\n\n- I have a ` can only contain text and {tags}svelte(illegal-structure)` error\n\n- I'm not sure it's the easiest way.\n\nHow can an achieve what I want to do?\n\n========================================\n\nTop Answer:\nWhile using a ternary **inside** of the markup works just fine, reactivity statements may help clean it up:\n\n```\n\n export let title = false;\n\n $: fullTitle = title \n ? `${title} • WebSite` \n : 'Website • Home suffix';\n\n {fullTitle}\n\n```\n\n========================================\n\nCode:\n```text\n<script>\n export let title = false;\n</script>\n\n<svelte:head>\n <title>\n {#if title}\n {title} • WebSite\n {:else}\n Website • Home suffix\n {/if}\n </title>\n</svelte:head>\n```\n\n```text\n- mywebsite\n```\n\n```text\n<title> can only contain text and {tags}svelte(illegal-structure)\n```\n\n```html\n<script>\n export let title = false;\n</script>\n\n<svelte:head>\n <title>{title ? `${title} • WebSite` : 'Website • Home suffix'}</title>\n</svelte:head>\n```\n\n```text\n<title>\n```\n\n```text\n{tags}\n```\n\n```xml\n<script>\n export let title = false;\n\n $: fullTitle = title \n ? `${title} • WebSite` \n : 'Website • Home suffix';\n</script>\n\n<svelte:head>\n <title>{fullTitle}</title>\n</svelte:head>\n```\n\n```js\nimport { writable } from 'svelte/store';\n\nfunction createTitle() {\n const {subscribe, set, update} = writable('');\n \n return {\n subscribe,\n set: (value) => {\n set(`${value} • WebSite`)\n },\n clear: () => {\n set('Website • Home suffix');\n }\n }\n}\n\nexport const title = createTitle();\n```\n\n```text\ntitle.set('page title')\n```\n\n```text\ntitle.reset()\n```\n\n========================================\n\nComments:\n- So create a title component to import on every page is the best solution? Nothing more simple/buit-in?\n- If you're making an SPA or using Sapper then you can keep the `` in your top component and update it programmatically\n- @BennyHinrichs are you suggesting to create a `title.js` file to make it? In that case, it is not better than creating a component, am I wrong?\n- In Sapper, you would just put the title logic in your `_layout.svelte` file. See the docs and an example in sapper-template.","metadata":{"transformedAt":"2026-08-18T18:33:40.672Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":146,"estimatedTokens":700}}190{"id":"stack-63651193","source":"stackoverflow","questionId":63651193,"title":"When should I use derived in Svelte custom stores?","tags":["svelte"],"text":"Title: When should I use derived in Svelte custom stores?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI've followed along with the great Svelte tutorial but I'm having trouble understanding *when* I should use `derived` in my custom stores. In this example, I'm creating a game with 3 states:\n\n- `PRE_GAME`\n\n- `IN_GAME`\n\n- `POST_GAME`\n\nI want to return a boolean check for when I'm in one of those states, and *I think* it would be best on the custom store itself.\n\nThis is my current code:\n\n```\nimport { writable, derived } from 'svelte/store';\n\nexport const gamestate = (() {\n const { set, subscribe } = writable('PRE_GAME');\n\n return {\n subscribe,\n set\n };\n})();\n\nexport const preGame = derived(gamestate, ($gamestate) => $gamestate === 'PRE_GAME');\nexport const inGame = derived(gamestate, ($gamestate) => $gamestate === 'IN_GAME');\nexport const postGame = derived(gamestate, ($gamestate) => $gamestate === 'POST_GAME');\n```\n\nIs it possible to move the derived methods onto the `gamestate` store like `gamestate.preGame()`? Does that make sense to do in Svelte? Then I can call `$gameState` and get whichever value, but also return a boolean check when I need an explicit value.\n\nI expected to be able to do check the internal value without needing to derive its value. Maybe something like below, but it always returns false because `gamestate` is a writable object.\n\n```\nexport const createStore = (() {\n const { set, subscribe } = writable('PRE_GAME');\n\n return {\n subscribe,\n set,\n preGame: () => gamestate === 'PRE_GAME',\n inGame: () => gamestate === 'IN_GAME',\n postGame: () => gamestate === 'POST_GAME',\n };\n})();\n```\n\nWhat am I misunderstanding here?\n\n========================================\n\nTop Answer:\nWhat you do is return a subscription to a derived store in your custom store:\n\n```\nimport { derived, writable } from 'svelte/store'\n\nexport const gameState = (() => {\n const store = writable('PRE_GAME')\n const store2 = derived(store, $store => ({\n preGame: $store === 'PRE_GAME',\n inGame: $store === 'IN_GAME',\n postGame: $store === 'POST_GAME' \n }))\n \n return {\n set: store.set,\n subscribe: store2.subscribe\n }\n})()\n```\n\nNow when you do `set` on the store it will set the value on *store*, then *store2* will derive new values and the subscribers will react to those changes:\n\n```\n\n import { gameState } from \"./store.js\"\n\n $gameState='PRE_GAME'}\">go PRE_GAME\n $gameState='IN_GAME'}\">go IN_GAME\n $gameState='POST_GAME'}\">go POST_GAME\n\n{#if $gameState.preGame}\n PRE_GAME\n{/if}\n\n{#if $gameState.inGame}\n IN_GAME\n{/if}\n\n{#if $gameState.postGame}\n POST_GAME\n{/if}\n```\n\n### Alternative\n\nYou can also define different `getters` for each specific state:\n\n```\nimport { derived, writable } from 'svelte/store'\n\nexport const gameState = (() => {\n const store = writable('PRE_GAME')\n const { set, subscribe } = store\n\n return {\n set,\n subscribe,\n get preGame() { return derived(store, $store => $store === 'PRE_GAME') },\n get inGame() { return derived(store, $store => $store === 'IN_GAME') },\n get postGame() { return derived(store, $store=> $store === 'POST_GAME') },\n }\n})()\n```\n\nNow the only problem is that doing `$gameState.preGame` does not exists because that tries to get the *preGame* prop from the content of *$gameState*, and doing `gameState.$preGame` or similar is **invalid syntax**. To get around that you can destructure the props out of the store where you need them:\n\n```\n\n import { gameState } from './store.js'\n const { preGame, inGame, postGame } = gameState\n\nCurrent State: {$gameState}\n{#if preGame}PRE_GAME{/if}\n{#if inGame}IN_GAME{/if}\n{#if postGame}POST_GAME{/if}\n```\n\n========================================\n\nCode:\n```js\nimport { writable, derived } from 'svelte/store';\n\nexport const gamestate = (() {\n const { set, subscribe } = writable('PRE_GAME');\n\n return {\n subscribe,\n set\n };\n})();\n\nexport const preGame = derived(gamestate, ($gamestate) => $gamestate === 'PRE_GAME');\nexport const inGame = derived(gamestate, ($gamestate) => $gamestate === 'IN_GAME');\nexport const postGame = derived(gamestate, ($gamestate) => $gamestate === 'POST_GAME');\n```\n\n```js\nexport const createStore = (() {\n const { set, subscribe } = writable('PRE_GAME');\n\n return {\n subscribe,\n set,\n preGame: () => gamestate === 'PRE_GAME',\n inGame: () => gamestate === 'IN_GAME',\n postGame: () => gamestate === 'POST_GAME',\n };\n})();\n```\n\n```text\nderived\n```\n\n```text\nPRE_GAME\n```\n\n```text\nIN_GAME\n```\n\n```text\nPOST_GAME\n```\n\n```text\ngamestate\n```\n\n```text\ngamestate.preGame()\n```\n\n```text\n$gameState\n```\n\n```text\ngamestate\n```\n\n```text\n{ gameSate: 'PRE_GAME', isPreGame: true, isInGame: false, isPostGame: false }\n```\n\n```text\nget()\n```\n\n```text\nfunction createStore() {\n const { set, subscribe } = writable('PRE_GAME');\n let state\n subscribe((v)=>state=v)\n return {\n subscribe,\n set,\n preGame: () => gamestate === 'PRE_GAME',\n inGame: () => state === 'IN_GAME',\n postGame: () => gamestate === 'POST_GAME',\n };\n }\n```\n\n```text\n<script>\n import {gamestate} from \"./store.js\"\n $: st=gamestate.inGame($gamestate)\n $: console.log(\"state\", st) \n</script>\n\n<h1 on:click={()=>$gamestate=\"IN_GAME\"}>Hello {$gamestate}!</h1>\n<p>state: {st}</p>\n```\n\n```text\nstate\n```\n\n```text\ninGame\n```\n\n```text\nst\n```\n\n```text\n$:\n```\n\n```text\n$gamestore\n```\n\n```text\n$gamestore\n```\n\n```text\n$derived_store\n```\n\n```js\nimport { derived, writable } from 'svelte/store'\n\nexport const gameState = (() => {\n const store = writable('PRE_GAME')\n const store2 = derived(store, $store => ({\n preGame: $store === 'PRE_GAME',\n inGame: $store === 'IN_GAME',\n postGame: $store === 'POST_GAME' \n }))\n \n return {\n set: store.set,\n subscribe: store2.subscribe\n }\n})()\n```\n\n```html\n<script>\n import { gameState } from \"./store.js\"\n</script>\n\n<button on:click=\"{() => $gameState='PRE_GAME'}\">go PRE_GAME</button>\n<button on:click=\"{() => $gameState='IN_GAME'}\">go IN_GAME</button>\n<button on:click=\"{() => $gameState='POST_GAME'}\">go POST_GAME</button>\n\n<br />\n\n{#if $gameState.preGame}\n <span>PRE_GAME</span>\n{/if}\n\n{#if $gameState.inGame}\n <span>IN_GAME</span>\n{/if}\n\n{#if $gameState.postGame}\n <span>POST_GAME</span>\n{/if}\n```\n\n```js\nimport { derived, writable } from 'svelte/store'\n\nexport const gameState = (() => {\n const store = writable('PRE_GAME')\n const { set, subscribe } = store\n\n return {\n set,\n subscribe,\n get preGame() { return derived(store, $store => $store === 'PRE_GAME') },\n get inGame() { return derived(store, $store => $store === 'IN_GAME') },\n get postGame() { return derived(store, $store=> $store === 'POST_GAME') },\n }\n})()\n```\n\n```html\n<script>\n import { gameState } from './store.js'\n const { preGame, inGame, postGame } = gameState\n</script>\n\n<span>Current State: {$gameState}</span>\n{#if preGame}<span>PRE_GAME</span>{/if}\n{#if inGame}<span>IN_GAME</span>{/if}\n{#if postGame}<span>POST_GAME</span>{/if}\n```\n\n```text\nset\n```\n\n```text\ngetters\n```\n\n```text\n$gameState.preGame\n```\n\n```text\ngameState.$preGame\n```\n\n========================================\n\nComments:\n- There is an easier way to have reactive functions inside the store without derived store: define your function `preGame: (state) => state === 'PRE_GAME'` and call it from your component `state2: {gamestate.preGame($gamestate)}` Now you have a reactive variable `$gamestate` in your component and value of the store inside the status-function\n- This is an excellent answer. I didn’t know you can use stores in store like this. Thank you.\n- I like how this looks. Is it possible to do this and also get the $gameState without an explicit get method? When I use derived separately, I can call $gameState and get one of the values. With this $gameState returns [object object] so I needed to add get which returns $store 🤔\n- Change store.js `subscribe:store.subscribe,subs: store2` and then you can use both stores in svelte-component `let s=gameState.subs` and `{#if $s.preGame}`\n- I added an alternative approach where you export props for each state instead, partially based on the answer from @grohjy you will need to destructure the once you need though (instead of returning three separate props, you can keep them bundled in a second substore of course)\n- The other answers work as well, but after trying them out for a little while this *feels* the most right in Svelte. Deriving from a store in a specific derived function seems to work best.","metadata":{"transformedAt":"2026-08-18T18:33:40.672Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":358,"estimatedTokens":2122}}191{"id":"stack-76824513","source":"stackoverflow","questionId":76824513,"title":"Svelte: How do I access route parameters in page.svelte?","tags":["svelte"],"text":"Title: Svelte: How do I access route parameters in page.svelte?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI am new to svelte. I have a route defined like this: `/posts/[slug]`. How do I access the `slug` in `page.svelte` file?\n\n```\n\nlet slug = ...\n\n```\n\nI have tried searching online but cannot find the solution.\n\n========================================\n\nCode:\n```text\n<script>\nlet slug = ...\n</script>\n```\n\n```text\n/posts/[slug]\n```\n\n```text\nslug\n```\n\n```text\npage.svelte\n```\n\n```js\nimport { page } from '$app/stores';\nlet slug = $page.params.slug;\n```\n\n========================================\n\nComments:\n- For the new versions (SvelteKit 2.12 or later), use state module instead `import { page } from '$app/state' let slug = page.params.slug`","metadata":{"transformedAt":"2026-08-18T18:33:40.672Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":45,"estimatedTokens":189}}192{"id":"stack-63098130","source":"stackoverflow","questionId":63098130,"title":"Adding Styling to svelte-routing Link tag in svelte js","tags":["svelte","svelte-3"],"text":"Title: Adding Styling to svelte-routing Link tag in svelte js\nTags: svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI wanted to add Styling to the `` tag in svelte routing but I couldn't.\nI have tried to add a class in which there is some styling but it didn't work.\n\n```\n\n```\n\nthe class contains:\n\n```\n.link {\n text-decoration: none;\n}\n```\n\nDoes anyone have a solution for this?\n\n========================================\n\nTop Answer:\nYou can use this option:\n\n```\nimport { link } from 'svelte-routing';\n...\n\n```\n\nthis gives you the same behavior and lets you add styles\n\nsource: https://github.com/EmilTholin/svelte-routing#link-1\n\n========================================\n\nCode:\n```text\n<Link to='/' class='link'></Link>\n```\n\n```text\n.link {\n text-decoration: none;\n}\n```\n\n```text\n<Link>\n```\n\n```text\n<style>\n .link > :global(a) {\n text-decoration: none;\n }\n \n :global(a) {\n ...\n }\n</style>\n```\n\n```text\n<Link></Link>\n```\n\n```text\n<a></a>\n```\n\n```text\nglobal\n```\n\n```text\nLink.svelte\n```\n\n```text\nimport { link } from 'svelte-routing';\n...\n<a href='/' class='link' use:link></a>\n```\n\n========================================\n\nComments:\n- Thanks! Although it's a bit late to say it.\n- When trying your suggestion, I can't seem to get it work. Setting any styling inside the `:global(a){}` doesn't get applied and vs code says that it is unused. What am I missing here?\n- @DannyBoy if you add the :global(a) to the parent's style it should work. For example: `.link-wrapper > :global(a) {text-decoration: none;}` ` `\n- Unfortunately it does not give the same behavior. It behaves like an `` tag by refreshing the page when changing the URL.\n- be sure that you hare using `link` and not `Link`\n- this solution is correct. Thanks man","metadata":{"transformedAt":"2026-08-18T18:33:40.672Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":97,"estimatedTokens":442}}193{"id":"stack-56714732","source":"stackoverflow","questionId":56714732,"title":"Can't preventDefault() on drop event on a div with Svelte","tags":["javascript","html","svelte"],"text":"Title: Can't preventDefault() on drop event on a div with Svelte\nTags: javascript, html, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implement a file dropper on a `` as a Svelte component. I've tried every combination of `preventDefault` but the browser still loads the dropped file instead of passing it to the component.\n\n```\n\n function handleDrop(event) {\n event.preventDefault();\n console.log(\"onDrop\");\n }\n\n function handleDragover(event) {\n console.log(\"dragOver\");\n }\n\n .dropzone {\n display: block;\n width: 100vw;\n height: 300px;\n background-color: #555;\n }\n\n```\n\nI've tried with and without `event.preventDefault();` in handler functions. Also tried with `on:dragenter` event and different combinations of modifiers, i.e. with `stopPropagation`. The browser still opens the dropped file. What am I doing wrong? Thanks! \n\n**(UPDATE) FIX:**\nOkay, the culprit was the `|once` modifier. Once removed from the `on:dragover` in `` everything works great, except that `dragover` event fires continuously while dragging across the div. `event.preventDefault();` inside handler functions is not needed as the `|preventDefault` modifier works correctly. Here is the code (omitting `` for brevity):\n\n```\n\n function handleDrop(event) {\n console.log(\"onDrop\");\n }\n function handleDragover(event) {\n console.log(\"onDragOver\");\n }\n\n```\n\nNot submitting this as an answer yet, because I would like to find out why I can't use `|once` modifier for `dragover` event, which would be useful for my app. Thanks!\n\n========================================\n\nTop Answer:\n```\n\n .dropzone {\n display: block;\n width: 100vw;\n height: 300px;\n background-color: #555;\n }\n\n```\n\n```\n handleDrop(event)}\n on:dragover={handleDragover}>\n\n```\n\n```\n\n export function handleDragover (ev) {\n ev.preventDefault();\n console.log(\"dragOver\");\n }\n\n export function handleDrop (ev) {\n ev.preventDefault();\n console.log(\"onDrop\");\n }\n\n```\n\nLook here: https://svelte.dev/repl/3721cbc9490a4c51b07068944a36a40d?version=3.4.2\n\nhttps://v2.svelte.dev/repl?version=2.9.10&gist=8a9b145a738530b20d0c3ba138512289\n\n========================================\n\nCode:\n```text\n<script>\n function handleDrop(event) {\n event.preventDefault();\n console.log(\"onDrop\");\n }\n\n function handleDragover(event) {\n console.log(\"dragOver\");\n }\n</script>\n\n<style>\n .dropzone {\n display: block;\n width: 100vw;\n height: 300px;\n background-color: #555;\n }\n</style>\n\n<div class=\"dropzone\" on:drop|preventDefault={handleDrop} \n on:dragover|once|preventDefault={handleDragover}></div>\n```\n\n```text\n<script>\n function handleDrop(event) {\n console.log(\"onDrop\");\n }\n function handleDragover(event) {\n console.log(\"onDragOver\");\n }\n</script>\n\n<div class=\"dropzone\" on:drop|preventDefault={handleDrop} \n on:dragover|preventDefault={handleDragover}></div>\n```\n\n```text\n<div>\n```\n\n```text\npreventDefault\n```\n\n```text\nevent.preventDefault();\n```\n\n```text\non:dragenter\n```\n\n```text\nstopPropagation\n```\n\n```text\n|once\n```\n\n```text\non:dragover\n```\n\n```text\n<div>\n```\n\n```text\ndragover\n```\n\n```text\nevent.preventDefault();\n```\n\n```text\n|preventDefault\n```\n\n```text\n<style>\n```\n\n```text\n|once\n```\n\n```text\ndragover\n```\n\n```text\n<div \n on:dragover|preventDefault\n on:drop|preventDefault={handler} \n>\n```\n\n```text\ndragover\n```\n\n```text\ndrop\n```\n\n```text\n<style>\n .dropzone {\n display: block;\n width: 100vw;\n height: 300px;\n background-color: #555;\n }\n</style>\n```\n\n```text\n<div class=\"dropzone\" on:drop={event => handleDrop(event)}\n on:dragover={handleDragover}>\n</div>\n```\n\n```text\n<script>\n export function handleDragover (ev) {\n ev.preventDefault();\n console.log(\"dragOver\");\n }\n\n export function handleDrop (ev) {\n ev.preventDefault();\n console.log(\"onDrop\");\n }\n</script>\n```\n\n========================================\n\nComments:\n- This still doesn't work on my end. Moreover, `export function` now creates warnings in the console: ` was created without expected prop 'handleDrop'`\n- According to this tutorial I should be able to just add `on:drop={handleDrop}` and in the function I would receive the event object anyway: `function handleDrop(event)`. And that works with the `dragover` event: while dragging across the `div` I can see the event object in the console if I do `console.log(event)`.","metadata":{"transformedAt":"2026-08-18T18:33:40.672Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":232,"estimatedTokens":1101}}194{"id":"stack-70506426","source":"stackoverflow","questionId":70506426,"title":"How to persist _layout state between pages in Sveltekit","tags":["svelte","sveltekit"],"text":"Title: How to persist _layout state between pages in Sveltekit\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a variable `checked` in my __layout.svelte and I want to have the value remain unchanged between page navigations. Instead when I navigate to a new page `checked` gets reset back to the default, false. Is there a way to simply persist layout or app state between page loads?\n\nThe context for the question is that I need to maintain the value of checked, which is a manual dark mode switch, across page navigations in the app.\n\n```\n\n let checked = false\n\n $: checked, console.log('checked is', checked)\n\nHome\nAbout\nContact\n\n \n \n a checkbox...\n \n\n```\n\n========================================\n\nCode:\n```text\n<!-- __layout.svelte -->\n<script>\n\n let checked = false\n\n $: checked, console.log('checked is', checked)\n\n</script>\n\n<a href=\"/\">Home</a>\n<a href=\"/about\">About</a>\n<a href=\"/contact\">Contact</a>\n\n<div style=\"margin-top:2em\">\n <label>\n <input type=\"checkbox\" bind:checked/>\n a checkbox...\n </label>\n</div>\n\n<slot></slot>\n```\n\n```text\nchecked\n```\n\n```text\nchecked\n```\n\n```text\nimport { writable } from \"svelte/store\";\n\nexport const checked = writable(false); // set the default value to false\n```\n\n```text\nimport {checked} from '$lib/store.js';\n```\n\n```text\n<input type=\"checkbox\" bind:checked={$checked}/>\n```\n\n```text\n<script>\n import {checked} from '$lib/store.js';\n</script>\n\n<h1>{$checked}</h1>\n```\n\n```text\nimport { writable } from \"svelte/store\";\nimport { browser } from \"$app/env\";\n\nexport const checked = writable();\n\nif (browser){\n checked.set(JSON.parse(localStorage.getItem(\"checked\")) || false);\n checked.subscribe(value => {\n localStorage.setItem(\"checked\", JSON.stringify(value));\n });\n}\n```\n\n```text\nstore.js\n```\n\n```text\nlib\n```\n\n```text\nstore.js\n```\n\n```text\n<script/>\n```\n\n```text\nindex.svelte\n```\n\n```text\n<h1/>\n```\n\n```text\nlocalStorage\n```\n\n```text\nif (browser)\n```\n\n```text\nlocalStorage\n```\n\n```text\nStrings\n```\n\n```text\nBooleans\n```\n\n```text\nstore.js\n```\n\n========================================\n\nComments:\n- A store alone probably will not be enough to persist data, in case of a full page load or reload. But serializing the store into/from `localStorage` or `sessionStorage` would do the trick.\n- Tested and works as needed. I've updated the question to specify that state only needs to be maintained across page navigation in the app. As indicated by @Thomas, a page refresh goes back to the initial value, and so state needs to be persisted by other means.\n- @IanEngelbrecht I updated my answer to save the state across sessions by using the localStorage.\n- So if this is just an object that holds data how does it work with static site generation?\n- @ZayX to what exactly are you referring to? Where are your doubts?\n- @miwin When I do static site generation I will have seperate pages. How does the object persists between different pages?\n- @ZayX that is the entire purpose of stores! To communicate between different components and pages. All of this happens on the client side. If you want to know how it works under the hood, please look into the Svelte source code.\n- @miwin thank you for your answer. I will assume that even when I do SSG svelte takes on routing and repopulating the page with framework internals. This should be the thing than enables js object to be preserved. I will definetly check source code when I have time.\n- Hmm, this is terrible. The default function for websites is to hold the scroll position and page state, imagine browsing a list of products for example. Why does SvelteKit override this?","metadata":{"transformedAt":"2026-08-18T18:33:40.672Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":157,"estimatedTokens":905}}195{"id":"stack-67334531","source":"stackoverflow","questionId":67334531,"title":"How to get html element of Svelte component using bind:this?","tags":["javascript","html","svelte","svelte-3"],"text":"Title: How to get html element of Svelte component using bind:this?\nTags: javascript, html, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nSuppose I have a reusable component called `button.svelte`,\n\n```\n\nexport let text = undefined\n\n{text}\n```\n\nNow I reuse this component in another component like so,\n\n```\n\nimport { onMount } from \"svelte\"\nimport Button from \"./Button.svelte\"\n\nlet button\n\nonMount(() => {\n console.log(button) // How do I print the html of the button element?\n})\n\n```\n\nBut `button` of `bind:this` doesn't seem to have the html of the button element. How do I get the html element of the button?\n\n========================================\n\nCode:\n```text\n<script>\nexport let text = undefined\n</script>\n\n<button>{text}</button>\n```\n\n```text\n<script>\nimport { onMount } from \"svelte\"\nimport Button from \"./Button.svelte\"\n\nlet button\n\nonMount(() => {\n console.log(button) // How do I print the html of the button element?\n})\n</script>\n\n<Button text=\"Button\" bind:this=\"{button}\"></Button>\n```\n\n```text\nbutton.svelte\n```\n\n```text\nbutton\n```\n\n```text\nbind:this\n```\n\n```text\n<script>\n export let node\n</script> \n\n<button bind:this={node}>\n <slot />\n</button>\n```\n\n```text\n<script>\n import Button from './Button.svelte'\n let button\n \n $:console.log(button)\n</script>\n\n<Button bind:node={button}>\n Hello\n</Button>\n```\n\n```text\nbind:this={prop}\n```\n\n```text\n$:\n```\n\n========================================\n\nComments:\n- Did you try innerHTML on button inside console.log? Also bind:this isn't supposed to be without double quotes?\n- May be this can help : https://stackoverflow.com/questions/59889859/how-can-i-retur‌​n-the-rendered-html-‌​of-a-svelte-componen‌​t\n- @JulienGabriel I tried doing `button.innerHTML` but shows `undefined`","metadata":{"transformedAt":"2026-08-18T18:33:40.672Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":106,"estimatedTokens":451}}196{"id":"stack-67407879","source":"stackoverflow","questionId":67407879,"title":"registering socket IO to vite for sveltekit","tags":["javascript","socket.io","svelte","vite","sveltekit"],"text":"Title: registering socket IO to vite for sveltekit\nTags: javascript, socket.io, svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have written a few apps using svelte and sapper and thought I would give sveltekit a go.\nAll in all it works, but I am now running into the issue of registering a worker on ther server.\n\nBasically I am trying to add socket.io to my app because I want to be able to send and receive data from the server. With sapper this wasn't really an issue because you had the `server.js` file where you could connect socket.io to the polka/express server. But I cannot find any equivalent in sveltekit and vite.\n\nI experimented a bit and I can create a new socket.io server in a route, but that will lead to a bunch of new problems, such as it being on a separate port and causing cors issues.\n\nSo I am wondering is this possible with sveltekit and how do you get access to the underlying server?\n\n========================================\n\nTop Answer:\nThe @sveltejs/adapter-node also builds express/polka compatible middleware which is exposed as `build/middelwares.js` which you can import into a custom `/server.cjs`:\n\n```\nconst {\n assetsMiddleware,\n prerenderedMiddleware,\n kitMiddleware,\n} = require(\"./build/middlewares.js\");\n\n... \n\napp.use(assetsMiddleware, prerenderedMiddleware, kitMiddleware);\n```\n\nThe node adaptor also has an entryPoint option, which allows bundling the custom server into the build, but I ran into issues using this approach.\n\nAdapters are not used during development (aka `npx svelte-kit dev`).\n\nBut using the `svelte.config.js` you're able to inject socket.io into the vite server:\n\n```\n...\n kit: {\n ...\n vite: {\n plugins: [\n {\n name: \"sveltekit-socket-io\",\n configureServer(server) {\n const io = new Server(server.httpServer);\n ...\n },\n },\n ],\n },\n },\n```\n\n**Note:** the dev server needs to be restarted to apply changes in the server code.\n\nYou could use entr to automate that.\n\n========================================\n\nCode:\n```text\nserver.js\n```\n\n```js\nconst {\n assetsMiddleware,\n prerenderedMiddleware,\n kitMiddleware,\n} = require(\"./build/middlewares.js\");\n\n... \n\napp.use(assetsMiddleware, prerenderedMiddleware, kitMiddleware);\n```\n\n```js\n...\n kit: {\n ...\n vite: {\n plugins: [\n {\n name: \"sveltekit-socket-io\",\n configureServer(server) {\n const io = new Server(server.httpServer);\n ...\n },\n },\n ],\n },\n },\n```\n\n```text\nbuild/middelwares.js\n```\n\n```text\n/server.cjs\n```\n\n```text\nnpx svelte-kit dev\n```\n\n```text\nsvelte.config.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.672Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":111,"estimatedTokens":646}}197{"id":"stack-60105276","source":"stackoverflow","questionId":60105276,"title":"Can I have multiple Svelte components on HTML page?","tags":["svelte"],"text":"Title: Can I have multiple Svelte components on HTML page?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nIs it possible to have a plain HTML page and have Svelte components injected at multiple places, like with React Portals? So I don't want to use Svelte as a Singe Page Application (SPA), but use Svelte components on existing HTML pages. And is it possible to let the separate Svelte components to communicate with each other using the event dispatcher, and to state using the Context API or Svelte stores?\n\nI am not in control of the rendered HTML, it comes from a CMS. So something like https://github.com/sveltejs/svelte/issues/1849 will not work... I can't \"compile\" the HTML page with the Svelte compiler.\n\n========================================\n\nCode:\n```js\nnew Part1({\n target: mount1\n});\nnew Part2({\n target: mount2\n});\n...\n```\n\n```text\n<svelte:window on:someeeventsomewhere={}></svelte:window>\n```\n\n```text\ntarget: ...\n```\n\n========================================\n\nComments:\n- Ok, that sounds promising! But when I don’t have control of the amount of “mount points”, is it possible to do the mounting at run-time, so select all DOM elements with a certain class and mount a specific component on all these DOM elements? And can I mount on a DOM element already containing ( server-side rendered) HTML and take over control?\n- You could use a querySelector and loop over the results to mount the Svelte component, for the existing DOM content, have a look at the 'hydratable' option in the docs.\n- Great insights! My last question to get the puzzle complete: is it possible to apply dynamic behavior to some existing markup, like is possible with Vue using **v-bind** and **v-on** as described in vuejs.org/v2/guide/syntax.html#v-bind-Shorthand\n- No, thats not possible. Svelte will not act an pre-existing markup unless you do it manually with queryselectors and innerhtml/-text.","metadata":{"transformedAt":"2026-08-18T18:33:40.672Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":37,"estimatedTokens":475}}198{"id":"stack-63372044","source":"stackoverflow","questionId":63372044,"title":"Svelte Each loop is not updated while object changed dynamically","tags":["javascript","svelte","sapper","svelte-3","svelte-component"],"text":"Title: Svelte Each loop is not updated while object changed dynamically\nTags: javascript, svelte, sapper, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nWhen i'm trying to change data dynamically of the each loop variable is not refreshing the DOM elements. How I can redraw the each loop values\n\n```\n\n // default messages object\n let messages =[{\n \"name\":\"John\",\n \"message\":\"Hi\",\n \"checked\": false\n },\n {\n \"name\":\"Anthony\",\n \"message\":\"welcome\",\n \"checked\": true\n },\n {\n \"name\":\"David\",\n \"message\":\"thank you\",\n \"checked\": false\n }]\n //click function to change the values dynamically \nfunction test(){\n messages.map(ob=>{\n ob.checked = true;\n })\n console.log(messages)\n}\n\n```\n\ntemplate code\n\n```\n\n {#each messages as m}\n {m.checked}\n \n {m.name}\n \n {/each}\n \n\n {test()}}> check all values\n\n```\n\nlink for snippet: https://svelte.dev/repl/887e7e2de4114ec1bb3625c264b9a62c?version=3.24.1\n\nAny help would be appreciated! Thank you :)\n\n========================================\n\nTop Answer:\n`map` returns a new array, in your case you got a new array from `undefined`, you need assign the result and correctly return the new object\n\n```\nfunction test(){\n messages = messages.map(obj => ({\n ...obj,\n checked: true\n }));\n}\n```\n\n========================================\n\nCode:\n```text\n<script>\n // default messages object\n let messages =[{\n \"name\":\"John\",\n \"message\":\"Hi\",\n \"checked\": false\n },\n {\n \"name\":\"Anthony\",\n \"message\":\"welcome\",\n \"checked\": true\n },\n {\n \"name\":\"David\",\n \"message\":\"thank you\",\n \"checked\": false\n }]\n //click function to change the values dynamically \nfunction test(){\n messages.map(ob=>{\n ob.checked = true;\n })\n console.log(messages)\n}\n</script>\n```\n\n```text\n<div>\n {#each messages as m}\n <div>{m.checked}\n <input type=\"checkbox\" bind:checked={m.checked}>\n {m.name}\n </div>\n {/each}\n <br>\n <button on:click={()=>{test()}}> check all values</button>\n</div>\n```\n\n```text\nfunction test(){\n messages = messages.map(obj => ({\n ...obj,\n checked: true\n }));\n}\n```\n\n```text\nmap\n```\n\n```text\nundefined\n```\n\n========================================\n\nComments:\n- messages = [...messages];\n- An actual example might help here. The documentation does not provide an example of this scenario","metadata":{"transformedAt":"2026-08-18T18:33:40.673Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":135,"estimatedTokens":586}}199{"id":"stack-59603406","source":"stackoverflow","questionId":59603406,"title":"Slot prop within _layout.svelte not passing prop","tags":["svelte","sapper"],"text":"Title: Slot prop within _layout.svelte not passing prop\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI'm working on a Sapper project and I'd like to load in some async data into the layout before loading in the slots. I've found that within a _layout.svelte file, I'm unable to pass props to the slot.\n\n```\n//_layout.svelte\n\n//index.svelte\n\n export let foo;\n alert(foo); // returns undefined\n\n```\n\nHas anyone run into this? I imagine I could work around it by just loading in all the data I need on every slot/subpage. The only way I'm able to set a slot prop is by accessing it manually.\n\n```\n$$props.$$scope.ctx.level1.props.foo = \"hello\"\n```\n\n========================================\n\nCode:\n```text\n//_layout.svelte\n<slot foo={\"hello\"}></slot>\n\n//index.svelte\n<script>\n export let foo;\n alert(foo); // returns undefined\n</script>\n```\n\n```text\n$$props.$$scope.ctx.level1.props.foo = \"hello\"\n```\n\n```text\n// in _layout.svelte\nimport {setContext} from 'svelte';\nsetContext('foo', foo);\n```\n\n```text\n// in index.svelte\nimport {getContext} from 'svelte';\nconst foo = getContext('foo');\n```\n\n========================================\n\nComments:\n- Accepted, thank you! It's less boilerplate than using a store and it seems works similarly to prop storage.","metadata":{"transformedAt":"2026-08-18T18:33:40.673Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":57,"estimatedTokens":316}}200{"id":"stack-65053432","source":"stackoverflow","questionId":65053432,"title":"Can you add optional _outer_ tags in svelte conditional statement?","tags":["svelte"],"text":"Title: Can you add optional _outer_ tags in svelte conditional statement?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nIs it possible to use a conditional statement to wrap inner content with an optional outer element?\n\nHere is an example of what I want to do in valid Svelte:\n\n```\n\n export let needs_div_wrapper;\n\n{#if needs_div_wrapper}\n \n My static content!\n \n{:else}\n My static content!\n{/if}\n```\n\nAnd here is an example in non-valid Svelte that demonstrates what I want to do:\n\n```\n...\n\n{#if needs_div_wrapper}\n \n{/if}\n My static content!\n{#if needs_div_wrapper}\n \n{/if}\n```\n\nEDIT: Just for clarity, I'm trying to accomplish this *without* a new component for the inner content.\n\n========================================\n\nTop Answer:\nLate to the party but still relevant I guess. I've come up with this solution, works at least for some use cases:\n\n```\n\n export let needs_div_wrapper;\n\n My static content!\n\n.contents { display: contents; }\n\n```\n\n**Update**\n\nIn case the conditional wrapper is an `` element, `display:contents` won't be enough. You could use `` for that scenario.\n\n```\n\n export let href;\n\n My static content!\n\n```\n\nExplanation: if `href` prop is not passed to the component, its value is `undefined`.\n\n- `this={href ? 'a' : 'div'}`: when `href` has a value, an `` element is generated, when `undefined` it is falsy so it generates a ``.\n\n- `{href}` is short for `href={href}`: if `href` is `undefined`, this attribute is omitted by svelte.\n\n- `class:contents={href}`: if `href` is `undefined`, it is falsy, which is good enough for a conditional class value.\n\n========================================\n\nCode:\n```text\n<script>\n export let needs_div_wrapper;\n</script>\n\n{#if needs_div_wrapper}\n <div>\n <a>My static content!</a>\n </div>\n{:else}\n <a>My static content!</a>\n{/if}\n```\n\n```text\n...\n\n{#if needs_div_wrapper}\n <div>\n{/if}\n <a>My static content!</a>\n{#if needs_div_wrapper}\n </div>\n{/if}\n```\n\n```html\n<script>\n export let wrap = false\n</script>\n{#if wrap}\n <div {...$$restProps}>\n <slot />\n </div>\n{:else}\n <slot />\n{/if}\n```\n\n```html\n<script>\n import DivWrapper from './DivWrapper.svelte'\n\n export let needs_div_wrapper;\n</script>\n\n<DivWrapper wrap={needs_div_wrapper}>\n <a>My static content!</a>\n</DivWrapper>\n```\n\n```text\nDivWrapper.svelte\n```\n\n```text\nApp.svelte\n```\n\n```html\n<script>\n export let needs_div_wrapper;\n</script>\n\n<div class:contents={needs_div_wrapper}>\n <a>My static content!</a>\n</div>\n\n<style>\n.contents { display: contents; }\n</style>\n```\n\n```html\n<script>\n export let href;\n</script>\n\n<svelte:element\n this={href ? 'a' : 'div'}\n {href}\n class:contents={href}\n>\n My static content!\n</svelte:element>\n```\n\n```text\n<a>\n```\n\n```text\ndisplay:contents\n```\n\n```text\n<svelte:element>\n```\n\n```text\nhref\n```\n\n```text\nundefined\n```\n\n```text\nthis={href ? 'a' : 'div'}\n```\n\n```text\nhref\n```\n\n```text\n<a>\n```\n\n```text\nundefined\n```\n\n```text\n<div>\n```\n\n```text\n{href}\n```\n\n```text\nhref={href}\n```\n\n```text\nhref\n```\n\n```text\nundefined\n```\n\n```text\nclass:contents={href}\n```\n\n```text\nhref\n```\n\n```text\nundefined\n```\n\n```text\n<script lang=\"ts\">\n export let wrappers: string[] = [];\n</script>\n{#if wrappers.length}\n <svelte:element this={wrappers[0]} {...$$restProps}>\n <svelte:self wrappers={wrappers.slice(1)}>\n <slot/>\n </svelte:self>\n </svelte:element>\n{:else}\n <slot/>\n{/if}\n```\n\n```text\n<script lang=\"ts\">\n import Wrap from \"./Wrap.svelte\";\n let wrappers = ['p', 'strong']; // Right place for nesting logic\n</script>\n<Wrap {wrappers}>\n Your content\n</Wrap>\n```\n\n========================================\n\nComments:\n- I would like something like this too. I created an issue on the Svelte GitHub: github.com/sveltejs/svelte/issues/7528\n- I originally asked this question generally, and the lack of a general answer played a role in my understanding of the limits of svelte. I didn't know about display: contents. That's going to be useful. As far as conditional classes go, I like this syntax: ``` export let needs_div_wrapper; My static content! .contents { display: contents; } ```\n- That made sense, at the time of writing I didn't know about the `class:classname={boolean}` syntax yet. I updated my answer.","metadata":{"transformedAt":"2026-08-18T18:33:40.673Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":262,"estimatedTokens":1055}}201{"id":"stack-64545260","source":"stackoverflow","questionId":64545260,"title":"Svelte: using \"bind:this\" inside \"each\" block","tags":["svelte"],"text":"Title: Svelte: using \"bind:this\" inside \"each\" block\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI want to render an array of objects, using an `each` block. I need to be able to remove elements from the array using callbacks from inside the `each` block. Also, for more complex UI-interactions, I need the reference to each component of the `each`-block to be available in the main app.\n\nHere is my approach:\n\n```\n\n let items = [{text: \"one\"}, {text: \"two\"}];\n \n function deleteItem(i) {\n items.splice(i, 1);\n items = items;\n }\n\n{#each items as item, i}\n deleteItem(i)} >\n {item.text}\n \n\n{/each}\n```\n\nUnderstandibly, this leads to errors such as `item[i] is undefined`, because when the splicing of `items` is processed, the `bind:this` cannot properly be cleaned up anymore.\n\nI tried to solve this by moving the component-references to a separate array. But no matter what I try, I cannot get the reference-array and the object-array to sync: Whenever `deleteItem()` is processed, I end up with `null`-values inside the `refs`-array. Here is one of my approaches (the `each`-section that prints the `refs`-array should help to show the `null`-values):\n\n```\n\n import {tick } from \"svelte\";\n let items = [{text: \"one\", id: 1}, {text: \"two\", id:2}];\n let refs = [];\n \n async function deleteItem(i) {\n items.splice(i, 1);\n await tick();\n refs.splice(i, 1);\n items = items;\n console.log(refs);\n }\n\n{#each items as item, i (item.id)}\n deleteItem(i)} bind:this={refs[i]}>\n {item.text}\n \n\n{/each}\n\n{#each refs as ref}\n{ref}\n\n{/each}\n```\n\nI tried with and without `tick()`, tried inserting the `tick()` in different places, with and without `async` and with and without using `(item.id)` in the each block. How can I keep the references and the data in sync?\n\n========================================\n\nCode:\n```html\n<script>\n let items = [{text: \"one\"}, {text: \"two\"}];\n \n function deleteItem(i) {\n items.splice(i, 1);\n items = items;\n }\n</script>\n\n{#each items as item, i}\n<button bind:this={items[i].ref} on:click={() => deleteItem(i)} >\n {item.text}\n</button> \n<p />\n{/each}\n```\n\n```html\n<script>\n import {tick } from \"svelte\";\n let items = [{text: \"one\", id: 1}, {text: \"two\", id:2}];\n let refs = [];\n \n async function deleteItem(i) {\n items.splice(i, 1);\n await tick();\n refs.splice(i, 1);\n items = items;\n console.log(refs);\n }\n</script>\n\n{#each items as item, i (item.id)}\n<button on:click={async () => deleteItem(i)} bind:this={refs[i]}>\n {item.text}\n</button> \n<p />\n{/each}\n\n{#each refs as ref}\n{ref}\n<p />\n{/each}\n```\n\n```text\neach\n```\n\n```text\neach\n```\n\n```text\neach\n```\n\n```text\nitem[i] is undefined\n```\n\n```text\nitems\n```\n\n```text\nbind:this\n```\n\n```text\ndeleteItem()\n```\n\n```text\nnull\n```\n\n```text\nrefs\n```\n\n```text\neach\n```\n\n```text\nrefs\n```\n\n```text\nnull\n```\n\n```text\ntick()\n```\n\n```text\ntick()\n```\n\n```text\nasync\n```\n\n```text\n(item.id)\n```\n\n```html\n<script>\n let items = [...]\n let _refs = []\n $: refs = _refs.filter(Boolean)\n</script>\n\n<button bind:this={_refs[i]}></button>\n```\n\n```html\n<button bind:this={item.ref}>\n```\n\n```js\nitems = items.filter((item, idx) => idx != i)\n```\n\n```text\nrefs\n```\n\n```text\nnull\n```\n\n========================================\n\nComments:\n- Thank you - your second approach works well!","metadata":{"transformedAt":"2026-08-18T18:33:40.673Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":202,"estimatedTokens":830}}202{"id":"stack-61188380","source":"stackoverflow","questionId":61188380,"title":"Using string as a component name in","tags":["svelte"],"text":"Title: Using string as a component name in\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nLet's say we have a custom component in Svelte created using the dynamic special tag. And let's say we have a **string** with the name of the component constructor.\n\n```\n\n import testComponent from './Something.svelte';\n\n let componentConstructorName = 'testComponent';\n\n```\n\nIs it possible to parse the component constructor name and render the corresponding component directly in the `this` property?\n\nI am aware I could create an object that assigns the constructor references to it's string names, but I am trying to do this in more automated way without doing any manual assignments.\n\nThe following will work, but I do feel some pain using `eval()`.\n\n```\n\n```\n\n========================================\n\nTop Answer:\nHere is my solution, which is quite Vuey, I think.\n\n```\n\n import CompOne from './CompOne.svelte';\n import CompTwo from './CompTwo.svelte';\n import CompThree from './CompThree.svelte';\n\n const components = { CompOne, CompTwo, CompThree }\n let compConstrName = \"CompOne\";\n\n```\n\n========================================\n\nCode:\n```js\n<script>\n import testComponent from './Something.svelte';\n\n let componentConstructorName = 'testComponent';\n</script>\n\n<svelte:component this=\"{componentConstructorName}\" />\n```\n\n```js\n<svelte:component this=\"{ eval(componentConstructorName) }\" />\n```\n\n```text\nthis\n```\n\n```text\neval()\n```\n\n```js\nlet componentContructorName = 'testComponent';\n$: componentConstructorClass = \n componentConstructorName === 'testComponent'\n ? testComponent\n : someDefaultComponent\n```\n\n```js\nlet componentContructorName = 'testComponent';\n$: componentConstructorClass = (() => switch(componentConstructorName) {\n case 'testComponent': return TestComponent;\n case 'testComponent2': return TestComponent2;\n default: someDefaultComponent;\n})();\n```\n\n```text\neval\n```\n\n```text\n<script>\n import CompOne from './CompOne.svelte';\n import CompTwo from './CompTwo.svelte';\n import CompThree from './CompThree.svelte';\n\n\n const components = { CompOne, CompTwo, CompThree }\n let compConstrName = \"CompOne\";\n</script>\n\n<svelte:component this={components[compConstrName]} />\n```\n\n========================================\n\nComments:\n- Being tracked here: github.com/sveltejs/svelte/issues/2324\n- Yup, the switch is what I did initially. I'm going to put an request on GitHub for the community to discuss then. I think it would be a useful thing to do.\n- Oh boy, it's such a shame, that Aurelia is pretty much dead. Once you worked with Aurelia, stuff like this ^ feels a bit cumbersome... 🙈","metadata":{"transformedAt":"2026-08-18T18:33:40.673Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":107,"estimatedTokens":659}}203{"id":"stack-66801706","source":"stackoverflow","questionId":66801706,"title":"Use Sveltekit and Tailwind CSS","tags":["svelte","tailwind-css","svelte-3","sveltekit"],"text":"Title: Use Sveltekit and Tailwind CSS\nTags: svelte, tailwind-css, svelte-3, sveltekit\nSource: Stack Overflow\n\nQuestion:\nSveltekit is finally in public beta. Does anyone know how to use it with Tailwind CSS? There aren't any official docs for this integration.\n\n========================================\n\nTop Answer:\nLuckily, setting up Tailwind CSS in Sveltekit is easy.\n\n### 1. Install Sveltekit\n\nIf you don't have a Sveltekit project already, now's the time to create one.\n\n```\nnpm init svelte@next\nnpm install\n```\n\n### 2. Install Tailwind CSS\n\nAssuming you already have Svelte\n\n```\nnpm install -D tailwindcss@latest postcss@latest autoprefixer@latest\n```\n\nIf you want to use just in type compilation for Tailwind, install that, too.\n\n```\nnpm install -D @tailwindcss/jit\n```\n\n### 3. Run Tailwind setup\n\n```\nnpx tailwindcss init -p\n```\n\nNext, change the created `tailwind.config.js` to a commonjs module by renaming it to `tailwind.config.cjs`. You just need to change the extension to `cjs`.\n\nThen, inside the config, setup which pages/components to purge from.\n\n```\n// tailwind.config.cjs\nmodule.exports = {\n purge: ['src/app.html', 'src/**/*.svelte'],\n...\n}\n```\n\n### 4. Create styles.css\n\nCreate a `styles.css` file in the src folder.\n\n```\n// ./src/style.css\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\nNow, create a layout component to import the styles from.\n\n```\n// ./src/routes/$layout.svelte\n\n import '../style.css';\n\n```\n\n### 5. Connect Sveltekit with Tailwind\n\nThis is the final step.\n\nIn your `svelte.config.cjs` file, add postcss as a preprocessor.\n\n```\n// svelte.config.cjs\nmodule.exports = {\n // add this\n preprocess: sveltePreprocess({\n postcss: true,\n defaults: {\n style: 'postcss',\n },\n }),\n}\n```\n\nAnd create a `postcss.config.cjs` file in the root of the project.\n\n```\n// postcss.config.cjs\nmodule.exports = {\n plugins: {\n 'tailwindcss': {},\n autoprefixer: {},\n },\n};\n```\n\n*If you're using `@tailwindcss/jit`, replace `tailwindcss` above with `@tailwindcss/jit`.*\n\nThat's it! You're now ready to use Sveltekit and Tailwind CSS.\n\n*P.S. Credit goes to Matt Lehrer for writing a great blog post on the subject.*\n\n========================================\n\nCode:\n```text\nnpm init svelte@next\n```\n\n```text\nnpx svelte-add tailwindcss # --jit\n```\n\n```text\nnpm init svelte@next\nnpm install\n```\n\n```text\nnpm install -D tailwindcss@latest postcss@latest autoprefixer@latest\n```\n\n```text\nnpm install -D @tailwindcss/jit\n```\n\n```text\nnpx tailwindcss init -p\n```\n\n```text\n// tailwind.config.cjs\nmodule.exports = {\n purge: ['src/app.html', 'src/**/*.svelte'],\n...\n}\n```\n\n```css\n// ./src/style.css\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n```text\n// ./src/routes/$layout.svelte\n<script>\n import '../style.css';\n</script>\n```\n\n```js\n// svelte.config.cjs\nmodule.exports = {\n // add this\n preprocess: sveltePreprocess({\n postcss: true,\n defaults: {\n style: 'postcss',\n },\n }),\n}\n```\n\n```js\n// postcss.config.cjs\nmodule.exports = {\n plugins: {\n 'tailwindcss': {},\n autoprefixer: {},\n },\n};\n```\n\n```text\ntailwind.config.js\n```\n\n```text\ntailwind.config.cjs\n```\n\n```text\ncjs\n```\n\n```text\nstyles.css\n```\n\n```text\nsvelte.config.cjs\n```\n\n```text\npostcss.config.cjs\n```\n\n```text\n@tailwindcss/jit\n```\n\n```text\ntailwindcss\n```\n\n```text\n@tailwindcss/jit\n```\n\n========================================\n\nComments:\n- almost too easy! Seriously though, very nice! was excited to see a similar adder for Bulma.io\n- Just a note there's currently a bug with it: github.com/svelte-add/tailwindcss/issues/…","metadata":{"transformedAt":"2026-08-18T18:33:40.673Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":224,"estimatedTokens":901}}204{"id":"stack-61854794","source":"stackoverflow","questionId":61854794,"title":"Sapper/Svelte: how to fetch a local json file to retrieve data","tags":["json","fetch","local","svelte","sapper"],"text":"Title: Sapper/Svelte: how to fetch a local json file to retrieve data\nTags: json, fetch, local, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nIn my sapper app, I have some data stored in a json file at src/data/videoslist.json, an array of objects in json format.\n\nI need to retrive the data in my index page to pass it to the component. Here's my code at the top of src/routes/index.svelte\n\n```\n\n export async function preload() {\n const response = await this.fetch('../data/videoslist.json');\n const responseJson = await response.json();\n return {\n videos: responseJson\n }\n }\n\n```\n\nI get an error 500\n\n```\ninvalid json response body at http://127.0.0.1:3000/data/videoslist.json reason: Unexpected token The file is pure json, nothing else. The unexpected token Do you know what I get wrong ? I tried so many paths variations wit ../ ./ or moving the file to the route folder, but nothing works.\n\nPS: I'm still a newbie with js and framework stuff, I may have missed something very basic for someone who knows better :) (like you can't retrieve a local file with fetch).\n\n========================================\n\nTop Answer:\nI've noticed that with the following:\n\n```\n\n export async function preload({ params: { id } }) {\n return await (await this.fetch(`/route/${id}/details.json`)).json();\n });\n\n```\n\n...the SSR code will attempt to load https://127.0.0.1/route/id/details.json - which fails on my hosting. If I specify a fully-qualified absolute URL (externally accessible), e.g.\n\n```\nthis.fetch(`https://hostname.tld/route/${id}/details.json`)\n```\n\n..it works fine. I have a `details.json.js` server route set up, which is working as expected when the URL is accessed directly via `https://hostname.tld/route/id/details.json`\n\nSapper evidently runs the same code on the client after the server 500, so the page still works, but it's somewhat confusing.\n\nI had a similar issue with relative paths in preload scripts due to the hosting provider blocking with lack of referrer (resulting in a 403), which can be mitigated with:\n\n```\nthis.fetch(`/route/${id}/details.json`, { referrerPolicy: \"origin\" })\n```\n\n...however, this doesn't seem to help in this instance.\n\nI can obviously just change the URL to be absolute, but I'd rather not tie this to the host, screw up local dev, and evidently force the SSR code to leave the local network. I guess I'm unclear how server-side fetch works to localhost, so may not be a sapper-specific issue.\n\nN.B. I can utilise \"host\" from the preload page argument to construct an absolute URL thus (must be http not https): \n\n```\n \n export async function preload({ host, params: { id } }) { \n return await (await this.fetch(`http://{host}/route/${id}/details.json`)).json(); \n });\n\n```\n\n...and it works on the hosting - but fear it isn't intuitive, and not as the documentation suggests.\n\n```\n\n```\n\n========================================\n\nCode:\n```text\n<script context=\"module\">\n export async function preload() {\n const response = await this.fetch('../data/videoslist.json');\n const responseJson = await response.json();\n return {\n videos: responseJson\n }\n }\n</script>\n```\n\n```text\ninvalid json response body at http://127.0.0.1:3000/data/videoslist.json reason: Unexpected token < in JSON at position 0\n```\n\n```text\nstatic\n```\n\n```text\nstatic/data/videoslist.json\n```\n\n```text\nvideoslist.json.js\n```\n\n```text\n<script context=\"module\">\n export async function preload() {\n const response = await this.fetch('videoslist.json');\n const responseJson = await response.json();\n return {\n videos: responseJson\n }\n }\n</script>\n```\n\n```text\n<script context=\"module\">\n export async function preload({ params: { id } }) {\n return await (await this.fetch(`/route/${id}/details.json`)).json();\n });\n</script>\n```\n\n```text\nthis.fetch(`https://hostname.tld/route/${id}/details.json`)\n```\n\n```text\nthis.fetch(`/route/${id}/details.json`, { referrerPolicy: \"origin\" })\n```\n\n```text\n<script context=\"module\"> \n export async function preload({ host, params: { id } }) { \n return await (await this.fetch(`http://{host}/route/${id}/details.json`)).json(); \n });\n</script>\n```\n\n```text\ndetails.json.js\n```\n\n```text\nhttps://hostname.tld/route/id/details.json\n```\n\n========================================\n\nComments:\n- Why do you use fetch if it is a local json file? Wouldn't it be simpler to make a javascript file, export the json and import it the \"normal\" way?\n- Yes, I thought of that, but the content of the json file is generated by fs.writeFileSync, and it overwrites the whole content everytime fresh data is collected\n- Ok and it is impossible to hardcode something like this in front of it: `module.exports = { jsonFile: // the json file` with the fs function?\n- It uses fetch because it is only a local file on the server, once the code is bundled and send to the client it is no longer 'local'. If you use this approach you will have to re-bundle your app everytime you make a change to the json file.\n- Yes, I confirm what Stephane says. I initially tried to read the json file with fs in the block, but it creates issues like preventing import from other libraries. I was confirmed by a sapper contributor that fs should not be used on the client side, only on the node side.\n- the content of the json file is generated by fs.writeFileSync, it gets entirely overwritten every time new content is written, and I didn't find a way to keep lines of javascript to return the json.\n- you would create a file `videoslist.json.js` and in that file you write a function that returns the content of `videoslist.json`\n- So simple and brilliant ! I'll give it a try and let you know. Thanks\n- Hi stephane, I tried your suggestion but i'm not getting it right and I can't figure out how to code properly this solution. Server routes are still very unclear to me as I'm a beginner. I should learn about general node concepts first before trying to code. Thanks for the suggestion, I'll get back to it when I understand better about routing.\n- @StephaneVanraes `fs` doesn't work when using relative path like, for example: `./_videolist.json`, cause Sapper seems not to compile that files and then it won't find it among compiled stuff (it seeks inside `__sapper__` folder). The only way to make it work is to use an absolute path, but it's not a very portable solution for deploying etc. Just wondering what should be the best practice to manage data (server side) without using a DB.\n- You should use node's `path` library and `__dirname` to get the current path, that is a lot more portable\n- Thanks Rich, I'll give it a try and let you know\n- This way the data are publicly accessible and not filtered by the server.\n- Given that the question was asking how to get the data in `videoslist.json` into the client, that obviously isn't a concern.\n- @RichHarris would be very interesting a safer solution, if any.","metadata":{"transformedAt":"2026-08-18T18:33:40.673Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":170,"estimatedTokens":1740}}205{"id":"stack-72141287","source":"stackoverflow","questionId":72141287,"title":"How to display a package.json version in the footer of the site?","tags":["svelte","sveltekit"],"text":"Title: How to display a package.json version in the footer of the site?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI would like to display a version that is declared in the package.json file in the footer of my site\n\nHow can I do this?\n\nI found this FAQ explanation in their documentation, but unfortunately I don't know to access it from my component\n\n```\n// svelte.config.js\n\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\n \nconst file = fileURLToPath(new URL('package.json', import.meta.url));\nconst json = readFileSync(file, 'utf8');\nconst pkg = JSON.parse(json);\n```\n\n========================================\n\nTop Answer:\nA little late to the party, but here's how I was able to achieve an answer to OP's question as of (14 Apr 23).\n\nAs per the sveltekit docs.\n\n```\n// add the following to > svelte.config.js\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\n\nconst file = fileURLToPath(new URL('package.json', import.meta.url));\nconst json = readFileSync(file, 'utf8');\nconst pkg = JSON.parse(json);\n```\n\nAs well as;\n\n```\n// add the following to kit: {}\nversion: {\n name: pkg.version\n}\n```\n\nThen in your desired component;\n\n```\n\n import { version } from '$app/environment';\n\nThe package.json version is: {version}\n```\n\nIf you're planning to go the Vite route, you should read, urb_'s answer to a similar question asked here on S.O. How do I add a version number to a SvelteKit/Vite app?.\n\nbut in summary;\n\n**Be aware**, config changed after @sveltejs/kit@1.0.0-next.359: After a\nbreaking change on @sveltejs/kit@1.0.0-next.359, Vite config must be\nincluded in its own file:\n\n========================================\n\nCode:\n```js\n// svelte.config.js\n\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\n \nconst file = fileURLToPath(new URL('package.json', import.meta.url));\nconst json = readFileSync(file, 'utf8');\nconst pkg = JSON.parse(json);\n```\n\n```js\nconst config = {\n kit: {\n vite: {\n define: {\n VERSION: pkg\n }\n }\n }\n};\n```\n\n```html\n<script>\n const version = VERSION;\n</script>\n\n<span>{version}</span>\n```\n\n```js\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vite';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\n\nconst file = fileURLToPath(new URL('package.json', import.meta.url));\nconst json = readFileSync(file, 'utf8');\nconst pkg = JSON.parse(json);\n\nexport default defineConfig({\n plugins: [sveltekit()],\n define: {\n PKG: pkg\n }\n});\n```\n\n```html\n<p>{PKG.version}</p>\n```\n\n```text\nvite.define\n```\n\n```text\nvite.config.js\n```\n\n```js\n// add the following to > svelte.config.js\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\n\nconst file = fileURLToPath(new URL('package.json', import.meta.url));\nconst json = readFileSync(file, 'utf8');\nconst pkg = JSON.parse(json);\n```\n\n```js\n// add the following to kit: {}\nversion: {\n name: pkg.version\n}\n```\n\n```html\n<script>\n import { version } from '$app/environment';\n</script>\n\n<span>The package.json version is: {version}</span>\n```\n\n```text\nconst file = fileURLToPath(new URL(\"package.json\", import.meta.url));\nconst json = readFileSync(file, \"utf8\");\nconst pkg = JSON.parse(json);\n...\nconst config = {\n...\n define: {\n __APP_NAME__: JSON.stringify(pkg.name),\n __APP_VERSION__: JSON.stringify(pkg.version),\n },\n }\n}\n```\n\n```text\n{__APP_VERSION__}\n```\n\n========================================\n\nComments:\n- how do you import `VERSION` and avoid `VERSION is not defined` error messages? (using SvelteKit)\n- Just a nit, but I think it should be `VERSION: JSON.stringify(pkg.version)`, thanks.\n- @NickJonas With Typescript, you can add `declare const VERSION: string` to your `src/app.d.ts` to fix errors and warnings. Vite Docs: Define.\n- Answer is outdated: \"Unexpected option config.kit.vite\"\n- @NatoBoram Updated for the latest version\n- Note that the keys of `define` are replaced in the code directly with their value. If you assign it a string value (instead of a JSON object as in the answer), then you'll have to add quotes in your code as well, e.g. `define: { SOME_VALUE: \"test\" }` could be used in your code as `const value = \"SOME_VALUE\"` (but not as `const value = SOME_VALUE` - unless `test` is a valid variable in the local scope).\n- Be careful with replacing `kit.version.name` as it is used by SvelteKit for HMR/change detection during development. Also, the full warning linked seems to suggest to prefer using `vite.config.js` over `svelte.config.js`.","metadata":{"transformedAt":"2026-08-18T18:33:40.673Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":183,"estimatedTokens":1136}}206{"id":"stack-73136479","source":"stackoverflow","questionId":73136479,"title":"Vite PostCSS module error when building app in Svelte","tags":["svelte","vite","postcss","autoprefixer"],"text":"Title: Vite PostCSS module error when building app in Svelte\nTags: svelte, vite, postcss, autoprefixer\nSource: Stack Overflow\n\nQuestion:\nI came across this strange error in Svelte; every time I ran `npm run dev`, this vite error would appear:\n\n```\n[vite] Internal server error: Failed to load PostCSS config (searchPath: /Users/Documents/Personal projects): [Failed to load PostCSS config] Failed to load PostCSS config (searchPath: /Users/Documents/Personal projects): [Failed to load PostCSS config] Failed to load PostCSS config (searchPath: /Users/Documents/Personal projects): [Error] Cannot find module 'autoprefixer'\n```\n\nI'm new to vite so it took me an hour of research, to figure out how to export the module, I was able to fix it by creating a `postcss.config.cjs` file and inside the file add:\n\n```\nmodule.exports = {\n autoprefixer: {}\n}\n```\n\nI hope this helps anyone that comes across the same/similar error.\n\n========================================\n\nTop Answer:\nI solved this issue by deleting the node_modules directory, and ran `npm i` again.\n\n========================================\n\nCode:\n```text\n[vite] Internal server error: Failed to load PostCSS config (searchPath: /Users/Documents/Personal projects): [Failed to load PostCSS config] Failed to load PostCSS config (searchPath: /Users/Documents/Personal projects): [Failed to load PostCSS config] Failed to load PostCSS config (searchPath: /Users/Documents/Personal projects): [Error] Cannot find module 'autoprefixer'\n```\n\n```text\nmodule.exports = {\n autoprefixer: {}\n}\n```\n\n```text\nnpm run dev\n```\n\n```text\npostcss.config.cjs\n```\n\n```text\nmodule.exports = {\n autoprefixer: {}\n}\n```\n\n```text\npostcss.config.cjs\n```\n\n```text\nnpm i\n```\n\n```text\n\"type\": \"module\",\n```\n\n```text\nnpm install -D tailwindcss@latest postcss@latest autoprefixer@latest\n\nnpx tailwindcss init -p\n\nnpm i\n```\n\n```text\nnpm run dev\n```\n\n```js\nmodule.exports = {\n autoprefixer: {}\n }\n```\n\n```js\nimport tailwindConfig from './tailwind.config'\nimport autoprefixer from 'autoprefixer'\nimport tailwind from 'tailwindcss'\n\nexport default {\n plugins: [tailwind(tailwindConfig), autoprefixer],\n}\n```\n\n```js\n...\nimport postcss from './postcss.config'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n css: {\n postcss,\n },\n})\n```\n\n```json\n{\n ...\n \"include\": [\n \"vite.config.ts\",\n \"postcss.config.ts\",\n \"tailwind.config.ts\"\n ]\n}\n```\n\n```text\npostcss\n```\n\n```text\ncss\n```\n\n```text\ninclude\n```\n\n========================================\n\nComments:\n- CommonJS files when using vite need to be explicitly named as `.cjs`. See issue on GitHub\n- Best answer for entire TS Vite project !","metadata":{"transformedAt":"2026-08-18T18:33:40.673Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":134,"estimatedTokens":670}}207{"id":"stack-64493172","source":"stackoverflow","questionId":64493172,"title":"Singleton in Svelte","tags":["svelte"],"text":"Title: Singleton in Svelte\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI am trying to make a Svelte app, where I have a class (not svelte component) that create an audioSource, and manage it.\n\nI would like to get this class instance across multiple component.\n\nRight now, the only way I found is to do this :\n\n```\n\n import { AudioAnalyser } from \"@app/class/audio/AudioAnalyser\";\n import type { MediaAnalyser } from \"@app/types/analyser\";\n\n let analyser: MediaAnalyser = new AudioAnalyser();\n\n```\n\nInside a component, so I am sure there is only one instance, and that instance via property binding with other Component.\n\nBut I am trying to find a way where I could instantiate this class once and access it trought all the app like with an angular Service.\n\nthank you\n\n========================================\n\nTop Answer:\nIn my application, I use a Singleton inside a typescript file. This singleton can then store unique data that will be shared across my application from any other .svelte component.\n\nYou can create a typescript Singleton like so :\n\n```\nexport class EditorConfig {\n private static instance : EditorConfig;\n private constructor(){}\n public static getInstance(): EditorConfig {\n if(!EditorConfig.instance){\n EditorConfig.instance = new EditorConfig();\n }\n return EditorConfig.instance;\n }\n\n public myvariable = \"\";\n\n public helloworld(){\n EditorConfig.getInstance().myvariable = \"hello world\";\n console.log(EditorConfig.getInstance().myvariable)\n }\n```\n\nYou can than import this typescript file inside a svelte component like this :\n\n```\n\n import {EditorConfig} from './EditorConfig.ts'\n\n EditorConfig.getInstance().helloworld()\n\n```\n\nBut you can also do this with **svelte store**. You can find some examples in the svelte officiel documentation.\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\" context=\"module\">\n import { AudioAnalyser } from \"@app/class/audio/AudioAnalyser\";\n import type { MediaAnalyser } from \"@app/types/analyser\";\n\n let analyser: MediaAnalyser = new AudioAnalyser();\n</script>\n```\n\n```js\n// analyser.ts\nimport { AudioAnalyser } from \"@app/class/audio/AudioAnalyser\";\nimport type { MediaAnalyser } from \"@app/types/analyser\";\n\nconst analyser: MediaAnalyser = new AudioAnalyser();\n\nexport default analyser\n```\n\n```html\n<script>\n import analyser from './analyser.ts'\n</script>\n```\n\n```js\nexport class EditorConfig {\n private static instance : EditorConfig;\n private constructor(){}\n public static getInstance(): EditorConfig {\n if(!EditorConfig.instance){\n EditorConfig.instance = new EditorConfig();\n }\n return EditorConfig.instance;\n }\n\n public myvariable = \"\";\n\n public helloworld(){\n EditorConfig.getInstance().myvariable = \"hello world\";\n console.log(EditorConfig.getInstance().myvariable)\n }\n```\n\n```js\n<script>\n import {EditorConfig} from './EditorConfig.ts'\n\n EditorConfig.getInstance().helloworld()\n</script>\n```\n\n========================================\n\nComments:\n- You have to use your App.svelte context for initializing. The quaestion is about scoping. If your scope is the whole app, do not instantiate in a sub-component.\n- Correct me if I'm work, but it does not look like the solutions so far would work with SSR (Server Side Rendering).","metadata":{"transformedAt":"2026-08-18T18:33:40.673Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":124,"estimatedTokens":825}}208{"id":"stack-65656481","source":"stackoverflow","questionId":65656481,"title":"How to dynamically render components in Svelte?","tags":["svelte"],"text":"Title: How to dynamically render components in Svelte?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to loop through an array to render the component with the value of `type`.\n\n```\n\nimport One from './One.svelte'; \nimport Two from './Two.svelte';\nimport Three from './Three.svelte';\n\nconst contents = [\n {type: 'One'},\n {type: 'Two'},\n {type: 'Three'},\n {type: 'One'}\n]\n\n{#each contents as content}\n \n{/each}\n```\n\nDesired output:\n\n```\n\n```\n\nWhat is the best way to do this?\n\n========================================\n\nTop Answer:\n### For Svelte 5:\n\n```\n\n import One from './One.svelte';\n import Two from './Two.svelte';\n\n const contents = [One, Two];\n\n{#each contents as content}\n {@const SvelteComponent = content}\n \n{/each}\n```\n\nThe component has to start with an upper case letter, that's why I'm using `{@const SvelteComponent = content}` in this example\n\n========================================\n\nCode:\n```text\n<script>\n\nimport One from './One.svelte'; \nimport Two from './Two.svelte';\nimport Three from './Three.svelte';\n\nconst contents = [\n {type: 'One'},\n {type: 'Two'},\n {type: 'Three'},\n {type: 'One'}\n]\n\n</script>\n\n{#each contents as content}\n <{content.type} />\n{/each}\n```\n\n```text\n<One />\n<Two />\n<Three />\n<One />\n```\n\n```text\ntype\n```\n\n```text\n<script>\n import One from './One.svelte'; \n import Two from './Two.svelte';\n\nconst contents = [\n One,\n Two\n]\n</script>\n\n{#each contents as content}\n <svelte:component this={content}/>\n{/each}\n```\n\n```text\n<svelte:component>\n```\n\n```text\n<svelte:component>\n```\n\n```text\n<script>\n import One from './One.svelte';\n import Two from './Two.svelte';\n\n const contents = [One, Two];\n</script>\n\n{#each contents as content}\n {@const SvelteComponent = content}\n <SvelteComponent></SvelteComponent>\n{/each}\n```\n\n```text\n{@const SvelteComponent = content}\n```\n\n========================================\n\nComments:\n- What about html elements such as and ?\n- @VityaSchel you can still use the `` tag in Svelte 5: svelte.dev/docs/svelte/svelte-element\n- Note: svelte 5 doesn't like self closing tags like that. Use ``","metadata":{"transformedAt":"2026-08-18T18:33:40.673Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":136,"estimatedTokens":526}}209{"id":"stack-64527549","source":"stackoverflow","questionId":64527549,"title":"Svelte form on:submit type TypeScript","tags":["typescript","svelte"],"text":"Title: Svelte form on:submit type TypeScript\nTags: typescript, svelte\nSource: Stack Overflow\n\nQuestion:\nI am trying to build a simple form in Svelte TypeScript.\n\nMy on:submit looks like this: ``, and my onSubmit function is defined as:\n\n```\nconst onSubmit = (event: HTMLFormElement) => {\n event.preventDefault();\n dispatch(\"addPerson\", person);\n person = {\n name: \"\",\n isOwed: 0,\n };\n };\n```\n\nWith this code I get the TypeScript problem:\n\nType '(event: HTMLFormElement) => void' is not assignable to type 'EventHandler'.\nTypes of parameters 'event' and 'event' are incompatible.\n\nI get that the event passed to onSubmit has the type `EventHandler`, and that my function is only expecting HTMLFormElement, but I can't manage to expect the whole EventHandler object. How can I achieve this?\n\n========================================\n\nTop Answer:\nTry this instead.\n\n```\n \n const handleSubmit: svelte.JSX.EventHandler = () => {\n\n }\n\n```\n\n========================================\n\nCode:\n```text\nconst onSubmit = (event: HTMLFormElement) => {\n event.preventDefault();\n dispatch(\"addPerson\", person);\n person = {\n name: \"\",\n isOwed: 0,\n };\n };\n```\n\n```text\n<form on:submit={onSubmit}>\n```\n\n```text\nEventHandler<Event, HTMLFormElement>\n```\n\n```text\nfunction handleSubmit(e: SubmitEvent) {\n const formData = new FormData(e.target as HTMLFormElement)\n}\n```\n\n```html\n<form on:submit|preventDefault={handleSubmit}>\n```\n\n```text\nSubmitEvent\n```\n\n```text\nevent\n```\n\n```text\nEvent\n```\n\n```text\nHTMLFormElement\n```\n\n```text\nevent: HTMLFormElement\n```\n\n```text\nevent: Event\n```\n\n```text\nevent: EventHandler<Event, HTMLFormElement>\n```\n\n```text\n<script lang=\"ts\"> \n const handleSubmit: svelte.JSX.EventHandler<Event, HTMLFormElement> = () => {\n\n }\n</script>\n\n<form on:submit|preventDefault={handleSubmit}>\n\n</form>\n```\n\n```html\n<script lang=\"ts\">\n import type { EventHandler } from \"svelte/elements\";\n\n const handleSubmit: EventHandler<SubmitEvent, HTMLFormElement> =\n function (event) {\n const data = new FormData(event.currentTarget);\n // event.currentTarget will have type HTMLFormElement here\n };\n</script>\n\n<form on:submit|preventDefault={handleSubmit}>\n <!-- ... -->\n</form>\n```\n\n```js\ntype EventHandler<E extends Event = Event, T extends EventTarget = Element> = (\n event: E & { currentTarget: EventTarget & T }\n) => any;\n```\n\n```text\nEventHandler<E, T>\n```\n\n```text\nevent\n```\n\n```text\nE\n```\n\n```text\nevent.currentTarget\n```\n\n```text\nT\n```\n\n```text\ncurrentTarget\n```\n\n```text\ntarget\n```\n\n```text\nEventHandler\n```\n\n```text\nevent.target\n```\n\n```text\nSubmitEvent\n```\n\n```text\ncurrentTarget\n```\n\n```text\ntarget\n```\n\n```text\ntarget\n```\n\n```text\ncurrentTarget\n```\n\n========================================\n\nComments:\n- Where does `EventHandler` come from ?\n- Can't try it right now but it probably comes from the svelte's types definition file.\n- `event` is not an `EventHandler` either – it’s a `SubmitEvent` in this case. You can annotate the handler function with `EventHandler`, however.","metadata":{"transformedAt":"2026-08-18T18:33:40.673Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":196,"estimatedTokens":758}}210{"id":"stack-71952922","source":"stackoverflow","questionId":71952922,"title":"How to add bootstrap 5 and other global packages to a SvelteKit project?","tags":["javascript","typescript","twitter-bootstrap","svelte","sveltekit"],"text":"Title: How to add bootstrap 5 and other global packages to a SvelteKit project?\nTags: javascript, typescript, twitter-bootstrap, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI installed *bootstrap* using *NPM*\n\nIn a normal `svelte` project I usualy add *bootstrap* and other packages, which are used project wide, in the `App.ts` file. However, in a *SvelteKit* project there is no main entry point.\n\nSo what is the recommended way of adding *bootstrap 5* or other *packages* to *SvelteKit* globally?\n\nI don't want to use rollup plugins, but rather just want to import it as an *module* in `JavaScript`\n\n========================================\n\nTop Answer:\n**updated answer for SvelteKit > 1.0**\n\nThe previous answer, while correct at the time of asking, has been outdated since a major refactor to SvelteKit prior to that release (but *after* posting the answer)\n\nThe top level layout layout is now a file called `+layout.svelte` instead.\n\n**previous answer**\n\nYou can make a top level `__layout` and import everything there.\n\n========================================\n\nCode:\n```text\nsvelte\n```\n\n```text\nApp.ts\n```\n\n```text\nJavaScript\n```\n\n```text\nsrc/app.html\n```\n\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <link rel=\"icon\" href=\"%sveltekit.assets%/favicon.png\" />\n <meta name=\"viewport\" content=\"width=device-width\" />\n %sveltekit.head%\n\n <link href=\"%sveltekit.assets%/res/bootstrap-5.0.2/bootstrap.min.css\" rel=\"stylesheet\">\n <style>\n body {\n /* override Bootstrap */\n background-color: unset;\n }\n </style>\n </head>\n <body>\n <div style=\"display: contents\">%sveltekit.body%</div>\n \n <script src=\"%sveltekit.assets%/res/bootstrap-5.0.2/bootstrap.bundle.min.js\"></script>\n </body>\n</html>\n```\n\n```text\n<link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC\" crossorigin=\"anonymous\">\n<script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM\" crossorigin=\"anonymous\"></script>\n```\n\n```text\n<html>\n```\n\n```text\n<head>\n```\n\n```text\n<body>\n```\n\n```text\nunset\n```\n\n```text\n<body>\n```\n\n```text\nbackground-color\n```\n\n```text\nsrc/static\n```\n\n```text\n%sveltekit.assets%/\n```\n\n```text\nbootstrap.min.css\n```\n\n```text\nbootstrap.bundle.min.js\n```\n\n```text\nsrc/static/bootstrap-5.0.2/\n```\n\n```text\nsrc/app.html\n```\n\n```text\n+layout.svelte\n```\n\n```text\n__layout\n```\n\n```text\nnpx svelte-add@latest bootstrap\n```\n\n```text\n<script>\n import 'bootstrap/dist/css/bootstrap.min.css';\n import 'bootstrap/dist/js/bootstrap.min.js';\n</script>\n```\n\n```text\nnpm install bootstrap\n```\n\n```text\n+layout.svelte\n```\n\n========================================\n\nComments:\n- Seems like that is the way, also found out there is `svelte-add`, which seems to be the future but doesnt have alot of packages currently.\n- how to choose bootstrap 4 or bootstrap 5?\n- Looking at the source of the *bootstrap* package you can't, github.com/svelte-add/bootstrap/blob/main/__run.js#L5 It just adds `bootstrap` without the option to add a version, so it just installs the latest version of *bootstrap*. Would be nice indeed if they added the ability to specify which version.\n- Btw, I would just go for the good old `npm install bootstrap@version` way. Since sveltekit has the top level `__layout` now.\n- @NamGVU I actualy forgot something, you can change the version of bootstrap by just simply changing the version in your *package.json*.\n- I just faced this issue, since, for some reason, collapses and modals didn't work using sveltestrap or svelte-add, and I didn't want to add a cdn, thanks for your solution :)\n- In Sveltekit 1.0 the \"static\" directory is in the root, not inside \"src\". The code above is correct.\n- I set this as accepted anwser, because the question was asked when svelte was still in beta. This is now indeed how it should be done, thanks.\n- This is now the best answer for SvelteKit. If you use svelte-add to install Bootstrap, the Bootstrap SCSS will already be imported in `+layout.svelte`. Just add the JS import for components. Note that `dist/js/bootstrap.bundle.min.js`is also available if you also need Popper for dropdowns, popovers, or tooltips. Or import individual JS components from `js/dist/*.js`.\n- Does not seem to work with latest SvelteKit: \"document is not defined\"","metadata":{"transformedAt":"2026-08-18T18:33:40.674Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":163,"estimatedTokens":1152}}211{"id":"stack-56991322","source":"stackoverflow","questionId":56991322,"title":"How to update context in svelte?","tags":["svelte"],"text":"Title: How to update context in svelte?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\ngetContext and setContext functions can only be called during component initialization. Is there some way to update the context value during runtime, on a click event for instance.\nImagine we store a theme or a localization in a context value and want to create a button to change that. Is it possible somehow?\nI've tried set the context using a variable and updating that variable, but it didn't work. Like this:\n\n```\n//App.svelte\n\n import {setContext} from 'svelte';\n import Name from './components/Name.svelte';\n let name = 'John';\n setContext('name',name);\n function changeName(){\n /// how to update context here ?\n name = 'Mike'; // Doesn't work!!!\n // setContext('name',name);// Doesn't work - Errors\n }\n\nChange Name\n```\n\n```\n//Name.svelte\n\n import {getContext} from 'svelte';\n let name = getContext('name');\n\n### My name is: {name}\n\n```\n\n========================================\n\nCode:\n```text\n//App.svelte\n<script>\n import {setContext} from 'svelte';\n import Name from './components/Name.svelte';\n let name = 'John';\n setContext('name',name);\n function changeName(){\n /// how to update context here ?\n name = 'Mike'; // Doesn't work!!!\n // setContext('name',name);// Doesn't work - Errors\n }\n</script>\n<Name></Name>\n<button on:click={changeName}>Change Name</button>\n```\n\n```text\n//Name.svelte\n<script>\n import {getContext} from 'svelte';\n let name = getContext('name');\n</script>\n\n<h1> My name is: {name}</h1>\n```\n\n```html\n<!-- App.svelte -->\n<script>\n import {setContext} from 'svelte';\n import {writable} from 'svelte/store';\n import Name from './components/Name.svelte';\n\n let name = writable('John');\n setContext('name',name);\n\n function changeName(){\n $name = 'Mike';\n }\n</script>\n<Name></Name>\n<button on:click={changeName}>Change Name</button>\n```\n\n```html\n<!-- Name.svelte -->\n<script>\n import {getContext} from 'svelte';\n let name = getContext('name');\n</script>\n\n<h1> My name is: {$name}</h1>\n```\n\n========================================\n\nComments:\n- As I understand, the stores are available everywhere, and context only to the child components, is this a way to limit the availability of a store? What are some other uses of this approach?\n- @gajo357: That is a misunderstanding, stores have nothing to do with being \"available everywhere\". *Anything* directly exported from a module can be imported anywhere. (This is mainly a note to others.)\n- In this example I don't get why you wouldn't just pass name to Name component as a prop rather then setting is as context? What about if you wanted to define user within +layout.svelte so its shared across all components, how would you then change user context within (settings) +page.svelte such that it is reactive to changes to the context?","metadata":{"transformedAt":"2026-08-18T18:33:40.674Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":99,"estimatedTokens":720}}212{"id":"stack-60233135","source":"stackoverflow","questionId":60233135,"title":"Svelte v3 programmatically create a component with props and event listeners","tags":["svelte","svelte-3"],"text":"Title: Svelte v3 programmatically create a component with props and event listeners\nTags: svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nIs it possible to create a component and programmatically attach event listeners to it?\n\nI know that this is easily possible for props using `` by spreading with `{ ...props }`. I wonder if something similar can be achieved to attach event listeners.\n\nE.g., in the following example I would like to programmatically attach `on:message` to `A` and `on:count` to `B`:\n\n```\n\n import A from './A.svelte';\n import B from './B.svelte';\n\n let message = 'Hi there 👋';\n let count = 0;\n\n const components = [{\n component: A,\n props: { message },\n listeners: { message: (m) => { console.log(`They say \"${m}\"`); } }\n }, {\n component: B,\n props: { count },\n listeners: { click: () => { count++; } }\n }];\n\n{#each components as component}\n \n{/each}\n\n They say \"{message}\"!\n\n They clicked {count} times!\n\n import { createEventDispatcher } from 'svelte';\n const dispatch = createEventDispatcher();\n export let message = '';\n function changeHandler(e) { dispatch('message', message); }\n\n import { createEventDispatcher } from 'svelte';\n const dispatch = createEventDispatcher();\n export let count = 0;\n function clickHandler() { dispatch('count', count); }\n\nClick me\n```\n\nHere's a live demo: https://svelte.dev/repl/af1bd30ab75b43f19b72a306340b7282?version=3.18.2\n\nI.e., I am hoping there's a way to expand the `components` array to\n\n```\n { message = e.detail; }}/>\n { count = e.detail; }}/>\n```\n\n========================================\n\nTop Answer:\nYou can't dynamically attach listeners, no - don't forget Svelte is a compiled language, it does all the heavy lifting at compile time, so things need to be known in advance.\n\nWhat I've done for dynamic listeners is to fire a single known event, and then have the event detail contain differential logic, such as event names, etc. As in the following:\n\n```\n// SomeComponent.svelte\n\n import { createEventDispatcher } from 'svelte'\n\n const dispatch = createEventDispatcher()\n\n dispatch('component-event', { name: 'alert', value: 'oh noes' })\n dispatch('component-event', { name: 'log', value: 'some message' })\n\n```\n\n```\n// App.svelte\n handleEvent(e)} />\n\n function handleEvent ({ detail }) {\n const { name, value } = detail\n if (name === 'alert') { alert(value) }\n if (name === 'log') { console.log(value) }\n }\n\n```\n\n========================================\n\nCode:\n```text\n<!-- App.svelte -->\n<script>\n import A from './A.svelte';\n import B from './B.svelte';\n\n let message = 'Hi there 👋';\n let count = 0;\n\n const components = [{\n component: A,\n props: { message },\n listeners: { message: (m) => { console.log(`They say \"${m}\"`); } }\n }, {\n component: B,\n props: { count },\n listeners: { click: () => { count++; } }\n }];\n</script>\n\n{#each components as component}\n <div><svelte:component this={component.component} { ...component.props }/></div>\n{/each}\n\n<div>\n <p>They say \"{message}\"!</p>\n <p>They clicked {count} times!</p>\n</div>\n\n<!-- A.svelte -->\n<script>\n import { createEventDispatcher } from 'svelte';\n const dispatch = createEventDispatcher();\n export let message = '';\n function changeHandler(e) { dispatch('message', message); }\n</script>\n\n<input on:change={changeHandler} on:value={message} value={message} />\n\n<!-- B.svelte -->\n<script>\n import { createEventDispatcher } from 'svelte';\n const dispatch = createEventDispatcher();\n export let count = 0;\n function clickHandler() { dispatch('count', count); }\n</script>\n\n<button on:click={clickHandler}>Click me</button>\n```\n\n```text\n<A message={message} on:message={e => { message = e.detail; }}/>\n<B count={count} on:count={e => { count = e.detail; }}/>\n```\n\n```text\n<svelte:component/>\n```\n\n```text\n{ ...props }\n```\n\n```text\non:message\n```\n\n```text\nA\n```\n\n```text\non:count\n```\n\n```text\nB\n```\n\n```text\ncomponents\n```\n\n```html\n<svelte:component this={component.component} { ...component.props } bind:this={instance}/>\n\n<script>\n export let component;\n\n let instance;\n \n $: if (instance && component.listeners) {\n for (let [key, listener] of Object.entries(component.listeners)) {\n instance.$on(key, listener);\n }\n }\n</script>\n```\n\n```html\n{#each components as component}\n <ComponentEvent {component}/>\n{/each}\n```\n\n```text\n$on\n```\n\n```text\n<svelte:component\n this={component.component}\n { ...component.props }\n on:message={ component.function}\n on:count={ component.function}\n/>\n```\n\n```text\n// SomeComponent.svelte\n<script>\n import { createEventDispatcher } from 'svelte'\n\n const dispatch = createEventDispatcher()\n\n dispatch('component-event', { name: 'alert', value: 'oh noes' })\n dispatch('component-event', { name: 'log', value: 'some message' })\n</script>\n```\n\n```text\n// App.svelte\n<svelte:component this={someComponent} on:component-event={e => handleEvent(e)} />\n\n<script>\n function handleEvent ({ detail }) {\n const { name, value } = detail\n if (name === 'alert') { alert(value) }\n if (name === 'log') { console.log(value) }\n }\n</script>\n```\n\n========================================\n\nComments:\n- This approach requires one to know in advance what the callbacks are and cover all of them. This is fine in my toy demo but I am actually looking for a solution that doesn't require the event names to be known upfront.\n- I don't think the listeners can be attached without the on: directive using just Svelte, props work without a directive so spreading them without one makes sense.\n- Interesting approach! Thanks for sharing. Aside, I am not entirely sure why it should technically not be possible to dynamically attach event listeners when it's possible to dynamically attach props. Maybe this is just a limitation of the current API.\n- Also svelte.dev/tutorial/svelte-component\n- great answer. how can i pass data to event listener?","metadata":{"transformedAt":"2026-08-18T18:33:40.674Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":244,"estimatedTokens":1486}}213{"id":"stack-72177023","source":"stackoverflow","questionId":72177023,"title":"How to Return File from SvelteKit Endpoint","tags":["rest","svelte","fs","sveltekit"],"text":"Title: How to Return File from SvelteKit Endpoint\nTags: rest, svelte, fs, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am trying to serve a PDF file that my SvelteKit app generates and allow a user to download it from an endpoint.\n\nMy project structure looks like this:\n\n```\n---------------------\n/src/routes/downloads\n---------------------\n[file].ts\nABC.pdf\nXYZ.pdf\n```\n\nMy `[file].ts` endpoint looks like this:\n\n```\nimport fs from 'fs'\n\n// ----- GET -----\nexport async function get({ params }){\n //console.log(params.file) -> ABC\n\n var pdf = fs.readFileSync('./src/routes/downloads/'+params.file+'.pdf')\n\n return{\n status:200,\n headers: {\n \"Content-type\" : \"application/pdf\",\n \"Content-Disposition\": \"attachment; filename=\"+params.file+\".pdf\"\n },\n body: pdf\n }\n}\n```\n\nSo then when I hit `http://localhost:3000/downloads/ABC`, the PDF file named `ABC.pdf` downloads.\n\nBut my `readFileSync` path isn't something that's going to work on production. As far as I know, there is no `/src/routes` folder.\n\nHow do I serve my file from a `http://localhost:3000` url? Everything I've tried yields a `404` and it can't find the file. I'm also open to a different way of handling this scenario. This is just my best guess of how to do this in SvelteKit.\n\n========================================\n\nTop Answer:\nFor anyone looking at this code\n\n```\nexport async function get({ params }){\n const file = `./${params.file}.pdf`;\n const pdfs = import.meta.glob(('./*.pdf', { as: 'raw' });\n const pdf = pdfs[file];\n\n return {\n status:200,\n headers: {\n \"Content-type\" : \"application/pdf\",\n \"Content-Disposition\": \"attachment; filename=\"+params.file+\".pdf\"\n },\n body: pdf\n }\n}\n```\n\nAnd wondering why it doesn't work...\n\nThis is not how it's done in SvelteKit anymore.\nCurrently you need to return a Response object, like this:\n\n```\nreturn new Response(body, { status: 200, headers: {} })\n```\n\nHopefully this is gonna save somebody some time, I just spent few minutes debugging :)\n\n========================================\n\nCode:\n```js\n---------------------\n/src/routes/downloads\n---------------------\n[file].ts\nABC.pdf\nXYZ.pdf\n```\n\n```js\nimport fs from 'fs'\n\n// ----- GET -----\nexport async function get({ params }){\n //console.log(params.file) -> ABC\n\n var pdf = fs.readFileSync('./src/routes/downloads/'+params.file+'.pdf')\n\n return{\n status:200,\n headers: {\n \"Content-type\" : \"application/pdf\",\n \"Content-Disposition\": \"attachment; filename=\"+params.file+\".pdf\"\n },\n body: pdf\n }\n}\n```\n\n```text\n[file].ts\n```\n\n```text\nhttp://localhost:3000/downloads/ABC\n```\n\n```text\nABC.pdf\n```\n\n```text\nreadFileSync\n```\n\n```text\n/src/routes\n```\n\n```text\nhttp://localhost:3000\n```\n\n```text\n404\n```\n\n```text\nadapter-node\n```\n\n```text\n/src\n```\n\n```text\n/static\n```\n\n```text\nfs.readFile('./my-app-data/foo.txt')\n```\n\n```text\nnode build\n```\n\n```text\nstatic\n```\n\n```text\nstatic\n```\n\n```text\nstatics\n```\n\n```js\nexport async function get({ params }){\n const file = `./${params.file}.pdf`;\n const pdfs = import.meta.glob(('./*.pdf', { as: 'raw' });\n const pdf = pdfs[file];\n\n return {\n status:200,\n headers: {\n \"Content-type\" : \"application/pdf\",\n \"Content-Disposition\": \"attachment; filename=\"+params.file+\".pdf\"\n },\n body: pdf\n }\n}\n```\n\n```text\nimport.meta.glob\n```\n\n```text\nimport.meta.glob\n```\n\n```text\nas: 'raw'\n```\n\n```js\nexport async function get({ params }){\n const file = `./${params.file}.pdf`;\n const pdfs = import.meta.glob(('./*.pdf', { as: 'raw' });\n const pdf = pdfs[file];\n\n return {\n status:200,\n headers: {\n \"Content-type\" : \"application/pdf\",\n \"Content-Disposition\": \"attachment; filename=\"+params.file+\".pdf\"\n },\n body: pdf\n }\n}\n```\n\n```js\nreturn new Response(body, { status: 200, headers: {} })\n```\n\n========================================\n\nComments:\n- I would simply put the files in the `statics` folder instead and link to it with `blabla.pdf` directly. This way you do not have to have an endpoint to handle this.\n- Hmm... that's an interesting idea. I had hoped to require that a user know the filename in order to be allowed to fetch it from my site. It seems like the `static` folder would be wide open for anyone to browse. 🤔\n- that would not be so much difference with the endpoint though, but you could of course add extra security like authentication with the endpoint\n- As far as I know, I can't reference `./static/` from my endpoints because on the server in production, there is no \"static\" folder.\n- So would my path in my endpoint be `./static/downloads/` instead of `./src/routes`? And somehow after I build my app, it will know to route `./static/downloads` to the root of my server (mywebsite.abc/downloads)?\n- Yeah, these files are generated on-the-fly as a web service. I post JSON via a `POST` request then convert them to a PDF, so I need a dynamic way of saving and reading files in the file system.\n- if they are generated, there is no need to read the filesystem\n- It also works for sqlite3 files with better-sqlite3. Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:40.674Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":232,"estimatedTokens":1263}}214{"id":"stack-72531742","source":"stackoverflow","questionId":72531742,"title":"How to use svelte:component with TypeScript?","tags":["typescript","svelte"],"text":"Title: How to use svelte:component with TypeScript?\nTags: typescript, svelte\nSource: Stack Overflow\n\nQuestion:\nI would like to use a dynamic component to select a view depending on the value of an enum:\n\n```\n\n```\n\nBut I don't get a compile error if I don't pass all the necessary parameters:\n\n```\n\n```\n\nHow to correctly specify the typing of dynamic components?\n\nUPD: map example with React\n\n```\nconst props: Props = {...}\nconst components: Record> = {\n [EnumType.variant_1]: Component1,\n [EnumType.variant_2]: Component2,\n}\n```\n\n========================================\n\nCode:\n```html\n<svelte:component\n this={components[enumValue]}\n {...props}\n/>\n```\n\n```html\n<svelte:component\n this={components[enumValue]}\n/>\n```\n\n```text\nconst props: Props = {...}\nconst components: Record<EnumType, React.FC<Props>> = {\n [EnumType.variant_1]: Component1,\n [EnumType.variant_2]: Component2,\n}\n```\n\n```html\n<!-- renderer.svelte -->\n<script lang=\"ts\" generics=\"C extends ComponentType\">\n import type { ComponentType, ComponentProps } from 'svelte';\n\n export let component: C;\n export let props: ComponentProps<InstanceType<C>>;\n</script>\n\n<svelte:component this={component} {...props} />\n```\n\n```html\n<!-- adder.svelte -->\n<script lang=\"ts\">\n export let a: number;\n export let b: number;\n</script>\n\n{a} + {b} = {a + b}\n```\n\n```html\n<script lang=\"ts\">\n import Renderer from './renderer.svelte';\n import Adder from './adder.svelte';\n</script>\n\n<Renderer component={Adder} />\n<!-- Error on \"Renderer\" because props are missing -->\n\n<Renderer component={Adder} props={{ a: 12 }} />\n<!-- Error on \"props\": Property 'b' is missing in type '{ a: number; }'\n but required in type '{ a: number; b: number; }' -->\n```\n\n```text\nsvelte\n```\n\n```text\nsvelte-preprocess\n```\n\n```text\nprops\n```\n\n========================================\n\nComments:\n- Thanks, your example works! To solve my problem, it remains to get the components type with the desired type of parameters. For example, in React it can be solved with React.FC type like in UPD. I can't find any example how to get Svelte component type.\n- Also, I don't understand how to use keywords \"bind\", \"on\", \"use\" in this case\n- You probably will not be able to use every feature when doing something like this. You will not be able to use `bind` in any case, if you spread properties. In general using `svelte:component` should be a rare occurrence, so you should pick your trade-offs. What is UPD? Also, you already have the \"component type\", it is what you import from a Svelte file.\n- If you want to get the type from within a component, that is currently not supported (GitHub issue).\n- `SvelteComponentTyped` is now deprecated and I cannot get this proposed solution to work - any ideas? (using Svelte 4.2.1)\n- @Einar: I updated the answer to reflex current syntax/types.","metadata":{"transformedAt":"2026-08-18T18:33:40.674Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":110,"estimatedTokens":713}}215{"id":"stack-64297484","source":"stackoverflow","questionId":64297484,"title":"How can I import node module into svelte component","tags":["npm","import","module","typeerror","svelte"],"text":"Title: How can I import node module into svelte component\nTags: npm, import, module, typeerror, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm new to svelte and I am trying to use an installed node module in my dependancies called momentum-slider. In the script tags of my svelte component I have:\n\n```\nimport MomentumSlider from \"../../node_modules/momentum-slider\";\nlet slider = new MomentumSlider({\n el: \".ms-container\",\n});\n```\n\nIn my component's html markup I have the suggested markup as shown in the tutorial at https://scotch.io/tutorials/building-a-fancy-countdown-timer-with-momentumsliderjs\n\nHowever, I am getting a typeError in the browser console:\n\nhttps://i.sstatic.net/shE4x.gif\n\nI am new to development in general and I am not sure if this is a problem with momentum-slider or an error on my part. Any insights would be much appreciated.\n\n========================================\n\nTop Answer:\nIf you have installed the package properly: `npm install momentum-slider`\nthe package is listed in your `package.json`.\n\nWhen this fits, you just have to import:\n`import MomentumSlider from \"momentum-slider\";`\n\n========================================\n\nCode:\n```text\nimport MomentumSlider from \"../../node_modules/momentum-slider\";\nlet slider = new MomentumSlider({\n el: \".ms-container\",\n});\n```\n\n```js\nimport MomentumSlider from \"momentum-slider\";\n```\n\n```js\nimport { onMount } from \"svelte\";\nimport MomentumSlider from \"momentum-slider\";\n\nlet slider;\n\nonMount(() => {\n slider = new MomentumSlider({ \n el: \".ms-container\"\n });\n});\n```\n\n```text\nMomentumSlider\n```\n\n```text\nnpm install momentum-slider\n```\n\n```text\npackage.json\n```\n\n```text\nimport MomentumSlider from \"momentum-slider\";\n```\n\n```text\nrequire\n```\n\n```text\nrequire\n```\n\n```text\nvar Validator = require('jsonschema').Validator;\n```\n\n```text\nimport { Validator } from \"jsonschema\";\n```\n\n========================================\n\nComments:\n- Many Thanks nologin for your suggestions. I have ammended the import statement as you suggested. momentum-slider is not listed in the package.json file but it is listed in the package-lock.json file. I'm not sure what the difference is between these two files but after following the advice of @johannchopin to use the **onMount** lifecycle hook I have been successful.\n- Fine that it is solved. The import is fixed as I recommended ;) The \"onMount\" above takes care, that the DOM is already created.\n- Many thanks @johannchopin! The corrections you suggested did the trick. I need to get my head around the lifecycle functions in svelte. I am thinking that **onMount** is like an eventlistener that listens to when the component has been inserted into the dom and **only then** runs the code inside. This would explain why the instance of MomentumSlider was failing to query the **.container** element as it did not yet exist in the html document. Is this line of thinking correct?\n- @stickleBrick Yep you give a correct explanation of your previous problem +1\n- So if it solves your problem please `validate` my answer :)\n- Apologies, I gave it a positive vote but was unaware of how to validate, I've done that now and it should have worked.","metadata":{"transformedAt":"2026-08-18T18:33:40.674Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":99,"estimatedTokens":790}}216{"id":"stack-63259289","source":"stackoverflow","questionId":63259289,"title":"Svelte: add noscroll class name to body from component","tags":["javascript","html","css","svelte"],"text":"Title: Svelte: add noscroll class name to body from component\nTags: javascript, html, css, svelte\nSource: Stack Overflow\n\nQuestion:\nI have a `src/components/UI/Sidebar.svelte` component with a variable toggle.\n\n```\nexport let toggle = true;\n```\n\nI would like to add a class name of `noscroll` to the `` when toggle is true to lock the body scroll. I have added this on the `src/template.html`\n\n```\n\n .noscroll { position: fixed; overflow-y:scroll };\n\n```\n\nWhat would it be the best way to implement a y-axis scroll lock like this when the sidebar is open?\n\n========================================\n\nCode:\n```js\nexport let toggle = true;\n```\n\n```html\n<style>\n .noscroll { position: fixed; overflow-y:scroll };\n</style>\n```\n\n```text\nsrc/components/UI/Sidebar.svelte\n```\n\n```text\nnoscroll\n```\n\n```text\n<body>\n```\n\n```text\nsrc/template.html\n```\n\n```js\nexport let toggle;\n$: document.body.classList[toggle ? 'add' : 'remove']('noscroll');\n```\n\n```js\nexport let toggle;\n\n$: if (process.browser) document.body.classList.toggle('noscroll', toggle);\n```\n\n```js\nexport let toggle;\nimport { browser } from '$app/env'\n\n$: if (browser) document.body.classList.toggle('noscroll', toggle);\n```\n\n```text\nbrowser\n```\n\n========================================\n\nComments:\n- @StephaneVanreas thanks fo that info and this is what I thought I needed to do. But when I add this in the components script I get an error `ReferenceError: document is not defined`. Does it matter that I am also using Sapper?\n- It does matter, yes — that statement will fail in the server-side rendering phase. Also, you can do `classList.toggle(name, condition)` which is more compact — so you could change the whole statement to `$: if (process.browser) document.body.classList.toggle('noscroll', toggle)`\n- Woah! Thanks @RichHarris this did the trick!!! Thanks for the insight and I really enjoy working with Svelte.","metadata":{"transformedAt":"2026-08-18T18:33:40.674Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":78,"estimatedTokens":470}}217{"id":"stack-67944684","source":"stackoverflow","questionId":67944684,"title":"How to serve plain json files with sveltekit?","tags":["javascript","svelte","sveltekit"],"text":"Title: How to serve plain json files with sveltekit?\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI tried doing something like this in my endpoint\nroutes/users.json.ts :\n\n```\nimport * as api from '$lib/api'\n\nexport async function get({ query, locals }) {\n\n const response = await this.fetch('static/data/customers.json')\n\n return {\n status: 200,\n body: {\n data: response\n }\n }\n}\n```\n\nmy static folder is located in the routes folder.\n\nI got this error:\n\n```\n...\nTypeError [ERR_INVALID_URL]: Invalid URL: /static/data/customers.json\n at onParseError (internal/url.js:259:9)\n at new URL (internal/url.js:335:5)\n at new Request (file:///home/nkostic/code/example/node_modules/@sveltejs/kit/dist/install-fetch.js:1239:16)\n...\n```\n\nWhat am I missing ?\n\nThe important thing is that it has to be static json files.\n\n========================================\n\nTop Answer:\nSvelteKit's `static` directory outputs to the root of your published folder, so you don't need to include `static` in your path. Try fetching `/data/customers.json` instead.\n\n========================================\n\nCode:\n```text\nimport * as api from '$lib/api'\n\nexport async function get({ query, locals }) {\n\n const response = await this.fetch('static/data/customers.json')\n\n return {\n status: 200,\n body: {\n data: response\n }\n }\n}\n```\n\n```text\n...\nTypeError [ERR_INVALID_URL]: Invalid URL: /static/data/customers.json\n at onParseError (internal/url.js:259:9)\n at new URL (internal/url.js:335:5)\n at new Request (file:///home/nkostic/code/example/node_modules/@sveltejs/kit/dist/install-fetch.js:1239:16)\n...\n```\n\n```text\nimport * as api from '$lib/api'\nimport yourJSON as api from 'path-to-file/customers.json'\n\nexport async function get({ query, locals }) {\n \n return {\n status: 200,\n body: {\n yourJSON\n }\n }\n\n}\n```\n\n```text\nstatic\n```\n\n```text\nstatic\n```\n\n```text\n/data/customers.json\n```\n\n```html\n<script context=\"module\">\n export async function load({ fetch }) {\n const response = await fetch(`../posts.json`); // stored in static folder\n const posts = await response.json();\n return {\n props: {\n posts: posts\n }\n }\n }\n</script> \n\n<script>\n export let posts;\n<script>\n```\n\n```text\n<script context=\"module\">\n```\n\n========================================\n\nComments:\n- The url appears to be invalid? Remember a fetch is not an import so you can’t just point it to a local file.\n- Tried different variants with fetch and it did not worked. I would prefer this take since it would not made my components larger but rather just serve the static file. For the simple uses cases such as mock api or some other implementations import works just fine.\n- I would prefer the fetch solution so my components do not get bigger like with import. But for simple cases such is mine this is exactly what I need. I aslo realised, thanks to Theo from sveltkit discord chat, that vitejs.dev is where I would look for more details about this functionality.\n- Cool, thanks, what version of sveltekit was used for this ?\n- svelte 3.44.0 and sveltekit 1.0.0-next.301","metadata":{"transformedAt":"2026-08-18T18:33:40.674Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":132,"estimatedTokens":779}}218{"id":"stack-71804119","source":"stackoverflow","questionId":71804119,"title":"Initializing a custom Svelte store asynchronously","tags":["svelte","svelte-store"],"text":"Title: Initializing a custom Svelte store asynchronously\nTags: svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\n**Background**\n\nI am attempting to develop a cross-platform desktop app using Svelte and Tauri\n\nWhen the app starts i need to load a settings.json-file from the filesystem into a custom Svelte store.\n\nIt needs to be a custom store because I must validate the data using a custom set-function before writing to it\n\nThe store will hold an object.\n\nI am using regular Svelte and not Svelte-kit as SSR is not necessary.\n\n**Problems**\n\n- Tauri does not have any synchronous methods for reading files in their fs-api\n\n- Svelte does not seem to have any intuitive way I can find for doing this\n\n**Tests**\n\n- Following Svelte's promiseStore example, this works for regular stores but not custom stores as the custom set method cannot be reached\n\n- Using a recursive timout-function waiting for the file to be read\n\n- Using a while-loop waiting for the file to be read\n\n- Attempted to find a way to load the data into a global variable before Svelte initializes\n\n**Example**\n\nIt would be a lot of code if I were to post all the failed attempts, so I will provide a example of what I am attempting to achieve.\n\nEverything in the code works when createStore is not async, except reading the settings-file.\n\n```\nimport { writable, get as getStore } from 'svelte/store'; // Svelte store\nimport _set from 'lodash.set'; // Creating objects with any key/path\nimport _merge from 'lodash.merge'; // Merging objects\nimport { fs } from '@tauri-apps/api'; // Accessing local filesystem\n\nasync function createStore() {\n // Read settings from the file system\n let settings = {}\n try { settings = JSON.parse(await fs.readTextFile('./settings.json')); }\n catch {}\n\n // Create the store\n const store = writable(settings);\n\n // Custom set function\n function set (key, value) {\n if(!key) return;\n\n // Use lodash to create an object\n const change = _set({}, key, value);\n\n // Retreive the current store and merge it with the object above\n const currentStore = getStore(store)\n const updated = _merge({}, currentStore, change)\n\n // Update the store\n store.update(() => updated)\n \n // Save the updated settings back to the filesystem\n fs.writeFile({\n contents: JSON.stringify(updated, null, 2),\n path: './settings.json'}\n )\n }\n\n // Bundle the custom store\n const customStore = {\n subscribe: store.subscribe,\n set\n }\n\n return customStore;\n}\n\nexport default createStore();\n```\n\n========================================\n\nTop Answer:\n**Update**: I'd recommend the wrapper component approach in Corrl revised answer,\n\nbut with an #await block instead of an #if.\n\nAs loading the settings are part of the app startup, you can delay the mounting your Svelte App until after the settings are loaded.\n\nThis allows components to use the store without worrying about the loading state:\n\n```\n// main.js\ninitSettings().then(()=> {\n new App({ target: document.body })\n})\n\n// settings.js\nimport { writable, get } from 'svelte/store';\nimport { fs } from '@tauri-apps/api'; \n\nlet store;\nconst settings = { \n subscribe() {\n if (!store) {\n throw new Error('Not initialized')\n }\n return store.subscribe()\n },\n async changeSetting(key, value) {\n if (!store) {\n throw new Error('Not initialized')\n }\n // ... save to fs\n }\n}\n\nexport default settings;\n\nexport async function initSettings() {\n const data = JSON.parse(await fs.readTextFile('./settings.json'))\n if (store) {\n store.set(data)\n } else {\n store = writable(data);\n }\n}\n```\n\nDownside it that it delays the startup of the app and if you don't implement a .catch in main.js the app would stay blank when the promise is rejected.\n\n========================================\n\nCode:\n```js\nimport { writable, get as getStore } from 'svelte/store'; // Svelte store\nimport _set from 'lodash.set'; // Creating objects with any key/path\nimport _merge from 'lodash.merge'; // Merging objects\nimport { fs } from '@tauri-apps/api'; // Accessing local filesystem\n\n\nasync function createStore() {\n // Read settings from the file system\n let settings = {}\n try { settings = JSON.parse(await fs.readTextFile('./settings.json')); }\n catch {}\n\n // Create the store\n const store = writable(settings);\n\n // Custom set function\n function set (key, value) {\n if(!key) return;\n\n // Use lodash to create an object\n const change = _set({}, key, value);\n\n // Retreive the current store and merge it with the object above\n const currentStore = getStore(store)\n const updated = _merge({}, currentStore, change)\n\n // Update the store\n store.update(() => updated)\n \n // Save the updated settings back to the filesystem\n fs.writeFile({\n contents: JSON.stringify(updated, null, 2),\n path: './settings.json'}\n )\n }\n\n // Bundle the custom store\n const customStore = {\n subscribe: store.subscribe,\n set\n }\n\n return customStore;\n}\n\nexport default createStore();\n```\n\n```text\n<script>\n import settings from './settings'\n import {onMount} from 'svelte'\n \n let appInitialized\n\n onMount(async () => {\n try {\n await settings.init() \n appInitialized = true\n }catch(error) {\n console.error(error)\n }\n })\n\n</script>\n\n{#if appInitialized}\n 'showing App'\n{:else}\n 'initializing App'\n{/if}\n```\n\n```text\n<script>\n import settings from './settings'\n</script>\n\n{#await settings.init()}\n 'initializing store'\n{:then}\n 'show App'\n{:catch error}\n 'Couldn't initialize - '{error.message}\n{/await}\n```\n\n```text\n<script>\n import settings from './settings'\n import store2 from './store2'\n import store3 from './store3'\n\n const initStores = [\n settings.init(),\n store2.init(),\n store3.init()\n ]\n</script>\n\n{#await Promise.all(initStores)}\n 'initializing stores'\n{:then}\n 'showing App'\n{:catch error}\n 'Couldn't initialize - '{error.message}\n{/await}\n```\n\n```js\nimport { writable, get } from 'svelte/store';\nimport { fs } from '@tauri-apps/api'; \n\nfunction createStore() {\n\n let initialValue = {}\n // destructure the store on creation to have 'direct access' to methods\n const {subscribe, update, set} = writable(initialValue);\n\n return {\n subscribe,\n\n async init() {\n const savedSettings = JSON.parse(await fs.readTextFile('./settings.json'))\n set(savedSettings);\n },\n\n changeSetting(key, value) {\n if(!key) return;\n\n const storeValue = get(this)\n\n storeValue[key] = value\n\n update(_ => storeValue)\n \n fs.writeFile({\n contents: JSON.stringify(storeValue, null, 2),\n path: './settings.json'\n })\n }\n }\n}\n\nexport default createStore();\n```\n\n```text\nApp\n```\n\n```text\nfs.writeFile()\n```\n\n```text\n{#await}\n```\n\n```js\n// main.js\ninitSettings().then(()=> {\n new App({ target: document.body })\n})\n\n// settings.js\nimport { writable, get } from 'svelte/store';\nimport { fs } from '@tauri-apps/api'; \n\nlet store;\nconst settings = { \n subscribe() {\n if (!store) {\n throw new Error('Not initialized')\n }\n return store.subscribe()\n },\n async changeSetting(key, value) {\n if (!store) {\n throw new Error('Not initialized')\n }\n // ... save to fs\n }\n}\n\nexport default settings;\n\nexport async function initSettings() {\n const data = JSON.parse(await fs.readTextFile('./settings.json'))\n if (store) {\n store.set(data)\n } else {\n store = writable(data);\n }\n}\n```\n\n```js\nexport const websocketClient = lateInitLoadable(async () => {\n const client: MySpecialWebsocket = await setupWSOnlyAfterPageHasLoaded();\n return client;\n});\n\n\nexport const highLevelClient = asyncDerived(\n [websocketClient.load],\n async ([$websocketClient]) => {\n const client = new HighLevelClient($websocketClient);\n await client.asyncSetup();\n return client;\n }\n);\n```\n\n```html\n<script>\n import {onMount} from 'svelte'\n\n onMount(async () => {\n await websocketClient.init();\n await highLevelClient.load\n const val = await $highLevelClient.websocketRequest();\n })\n</script>\n\n{#await highLevelClient.load then $highLevelClient}\n 'showing App'\n{/await}\n```\n\n```js\nimport { browser } from '$app/environment';\n\nif (browser) {\n websocketClient.init();\n}\n```\n\n```js\nimport { writable, type Readable } from 'svelte/store';\n\nexport type Loadable<T> = Readable<T> & { load: Promise<T>; init?: () => Promise<T> };\n\nexport function asyncDerived<S extends readonly unknown[], T>(\n deps: S,\n cb: (values: { [K in keyof S]: Awaited<S[K]> }) => Promise<T>\n): Loadable<T> {\n const { subscribe, set } = writable<T>();\n const load = new Promise<T>((resolve) => {\n Promise.all(deps).then((resolvedDeps) => {\n cb(resolvedDeps).then((value) => {\n resolve(value);\n set(value);\n });\n });\n });\n\n return {\n subscribe,\n load\n };\n}\n\nexport function lateInitLoadable<T>(lateInitFn: () => Promise<T>): Loadable<T> {\n const { subscribe, set } = writable<T>();\n // eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars\n let loadResolver: (value: T) => void = (_: T) => {};\n const load = new Promise<T>((resolve) => {\n loadResolver = resolve;\n });\n\n return {\n subscribe,\n async init() {\n const value = await lateInitFn();\n set(value as T);\n loadResolver(value as T);\n return value as T;\n },\n load\n };\n}\n```\n\n```text\nonMount()\n```\n\n```text\ninit()\n```\n\n```text\nonMount\n```\n\n```text\nif (browser)\n```\n\n```text\nasyncDerived\n```\n\n```text\nlateInitLoadable\n```\n\n```js\nimport { type Readable, writable } from 'svelte/store';\n\nexport interface ReadOnlyAsyncStore<T> extends Readable<T> {\n init: (promise: Promise<T>) => Promise<T>;\n}\n\n/// <summary>\n/// Creates a readable store that can be initialized after its created, asynchronously\n/// </summary>\n/// <usage>\n/// export const myStore = createStore<YourInterface>(); // Can do this in a shared ts file\n/// store.init(fetch('https://api.com/data')); //Can do this from your onmount etc\n/// </usage>\n/// <typeparam name=\"T\">The type of the store</typeparam>\nexport function createReadableAsyncStore<T>(): ReadOnlyAsyncStore<T> {\n const { subscribe, update } = writable<T>();\n\n return {\n subscribe,\n init: async (promise) => {\n const data = await promise;\n update(() => data);\n return data;\n }\n };\n}\n```\n\n========================================\n\nComments:\n- This works beautifully! Thank you :) Also great inclusion of {#await Promise.all(initStores)} I will need this later.\n- @Corrl but there is no App component in sveltekit 1.0. Where to find it?\n- @FishLegs I think in SvelteKit +layout.js would be the place for initializing the store. kit.svelte.dev/docs/routing#layout-layout-js Since it runs before rendering the component no need for `#await` blocks\n- @Corrl yes that should work as same\n- Thanks for mentioning the #await block! I never really used it before and just realized how useful it actually is... :)","metadata":{"transformedAt":"2026-08-18T18:33:40.674Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":487,"estimatedTokens":2832}}219{"id":"stack-59013329","source":"stackoverflow","questionId":59013329,"title":"Best place/lifecycle method to set page titles in a single-page Svelte app","tags":["javascript","single-page-application","svelte"],"text":"Title: Best place/lifecycle method to set page titles in a single-page Svelte app\nTags: javascript, single-page-application, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm getting started with Svelte and building a single-page application (using page.js as the router). I thought I'd have a separate component to produce the `` block, and when each component mounts it would write the page title to a store, which would then be read by the head component. It partially works - the page title is updated when I click through to different pages. However, if I go back in my browser's history, the title doesn't change back with the page. It does change if I then reload the page. So perhaps `onMount()` isn't the right lifecycle method. What approach can I take that will work with history state navigation?\n\nHere's my app boiled down to a minimal example.\n\n```\n// index.js\n\nimport page from 'page'\n\nimport App from './views/App.svelte'\n\nconst app = new App({\n target: document.body,\n props: {\n route: null,\n },\n})\n\nfunction one() {\n app.$set({ route: 'one' })\n}\n\nfunction two() {\n app.$set({ route: 'two' })\n}\n\npage('/one', one)\npage('/two', two)\npage()\n\n// App.svelte\n\n import One from './One.svelte'\n import Two from './Two.svelte'\n import Head from '../parts/Head.svelte'\n import Home from './Home.svelte'\n\n export let route\n\n{#if route === 'one'}\n \n{:else if route === 'two'}\n \n{:else}\n \n{/if}\n\n// Head.svelte\n\n import { pageName } from '../stores.js'\n\n let displayPageName\n\n pageName.subscribe(value => {\n displayPageName = value\n })\n\n {#if displayPageName}\n Test App — {displayPageName}\n {:else}\n Test App\n {/if}\n\n// stores.js\n\nimport { writable } from 'svelte/store'\n\nexport const pageName = writable(null)\n\n// Home.svelte\n\nOne Two\n\n// One.svelte\n\n import { onMount } from 'svelte'\n import { pageName } from '../stores.js'\n\n onMount(async () => {\n pageName.update(() => 'Component One')\n })\n\nTwo\n\n// Two.svelte\n\n import { onMount } from 'svelte'\n import { pageName } from '../stores.js'\n\n onMount(async () => {\n pageName.update(() => 'Component Two')\n })\n\nOne\n```\n\n========================================\n\nCode:\n```text\n// index.js\n\nimport page from 'page'\n\nimport App from './views/App.svelte'\n\nconst app = new App({\n target: document.body,\n props: {\n route: null,\n },\n})\n\nfunction one() {\n app.$set({ route: 'one' })\n}\n\nfunction two() {\n app.$set({ route: 'two' })\n}\n\npage('/one', one)\npage('/two', two)\npage()\n\n// App.svelte\n\n<script>\n import One from './One.svelte'\n import Two from './Two.svelte'\n import Head from '../parts/Head.svelte'\n import Home from './Home.svelte'\n\n export let route\n</script>\n\n<Head />\n\n{#if route === 'one'}\n <One />\n{:else if route === 'two'}\n <Two />\n{:else}\n <Home />\n{/if}\n\n// Head.svelte\n\n<script>\n import { pageName } from '../stores.js'\n\n let displayPageName\n\n pageName.subscribe(value => {\n displayPageName = value\n })\n</script>\n\n<svelte:head>\n {#if displayPageName}\n <title>Test App — {displayPageName}</title>\n {:else}\n <title>Test App</title>\n {/if}\n</svelte:head>\n\n// stores.js\n\nimport { writable } from 'svelte/store'\n\nexport const pageName = writable(null)\n\n// Home.svelte\n\n<a href=\"/one\">One</a> <a href=\"/two\">Two</a>\n\n// One.svelte\n\n<script>\n import { onMount } from 'svelte'\n import { pageName } from '../stores.js'\n\n onMount(async () => {\n pageName.update(() => 'Component One')\n })\n</script>\n\n<a href=\"/two\">Two</a>\n\n// Two.svelte\n\n<script>\n import { onMount } from 'svelte'\n import { pageName } from '../stores.js'\n\n onMount(async () => {\n pageName.update(() => 'Component Two')\n })\n</script>\n\n<a href=\"/one\">One</a>\n```\n\n```text\n<svelte:head>\n```\n\n```text\nonMount()\n```\n\n```js\n$: title = $pageName ? `Test App \\u2014 ${$pageName}` : 'Test App'\n```\n\n```js\n$: {\n document.title = title\n}\n```\n\n```html\n<script>\n import { pageName } from '../stores.js'\n\n $: title = $pageName ? `Test App \\u2014 ${$pageName}` : 'Test App'\n\n $: {\n document.title = title\n }\n</script>\n\n<svelte:head>\n <title>{title}</title>\n</svelte:head>\n```\n\n```js\npage('/', () => app.$set({ route: null }))\n```\n\n```text\n<title>\n```\n\n```text\n{#if}\n```\n\n```text\n$pageName\n```\n\n```text\n<title>\n```\n\n```text\ndocument.title\n```\n\n```text\nHead.svelte\n```\n\n```text\n/\n```\n\n========================================\n\nComments:\n- Hi there, thanks a lot for this very informative answer! It looks like you have a typo - it should be `{title}`. Also, in `Home.svelte` I had to explicitly set `$pageName = null`, otherwise at `/` the page title would render as \"null\". Otherwise, perfect, thanks again.","metadata":{"transformedAt":"2026-08-18T18:33:40.674Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":278,"estimatedTokens":1166}}220{"id":"stack-58691278","source":"stackoverflow","questionId":58691278,"title":"Sapper event for route change","tags":["javascript","svelte","sapper"],"text":"Title: Sapper event for route change\nTags: javascript, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI need to redirect users to login page if they are not authenticated. I need something like `route.beforeEach` in Vue.js, ideally:\n\n```\nsapper.beforeRouteChange((to, from, next) => {\n\n const isAuth = \"[some session or token check]\";\n\n if (!isAuth) {\n next('/login')\n }\n\n next()\n})\n```\n\nI found Sapper - protected routes (route guard) this question but I think it's not enough for my needs. What if token or auth changes in runtime? OR is it covered by reactivity?\n\n**Edit 1:** I think that this issue on Sapper GitHub solves my problem.\n\n========================================\n\nTop Answer:\nYou can also use `authenticationMiddleware.js` inside `server.js` file\n\nHere is `authenticationMiddleware.js` file\n\n```\nimport { get, post } from \"./../lib/api\";\nasync function authenticationMiddleware(req, res, next) {\n let user = null\n const cookies = require('cookie-universal')(req, res);\n if (cookies.get('token')) {\n try {\n user = await get(\"users/me\", null, cookies.get('token'));\n } catch (e) {\n console.log('err at users', e.toString());\n }\n req.user = user\n req.token = cookies.get('token')\n } else {\n req.user = {}\n req.token = null\n cookies.set('token', null)\n }\n next();\n}\nexport { authenticationMiddleware }\n```\n\ne.g. https://github.com/itswadesh/sapper-ecommerce/blob/master/src/server.js\n\n========================================\n\nCode:\n```js\nsapper.beforeRouteChange((to, from, next) => {\n\n const isAuth = \"[some session or token check]\";\n\n if (!isAuth) {\n next('/login')\n }\n\n next()\n})\n```\n\n```text\nroute.beforeEach\n```\n\n```js\nimport AuthMiddleware from \"../methods/authMiddleware.js\";\n import { goto, stores } from '@sapper/app';\n const { page } = stores();\n\n if (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n page.subscribe(({ path, params, query }) => {\n const from = window.location.pathname;\n const redirect = (href) => { goto(href); }\n\n AuthMiddleware.beforeChange(from, path, redirect, params, query);\n })\n }\n```\n\n```js\nexport default class AuthMiddleware {\n\n static beforeChange(from, to, redirect, params, query) {\n\n if (!AuthMiddleware._isUserAuthenticated()) {\n redirect(\"/login\");\n }\n }\n\n // ~\n\n static _isUserAuthenticated() {\n return true; // TODO: Implement\n }\n}\n```\n\n```text\n/src/routes/_layout.svelte\n```\n\n```text\nauthMiddleware.js\n```\n\n```text\nimport { get, post } from \"./../lib/api\";\nasync function authenticationMiddleware(req, res, next) {\n let user = null\n const cookies = require('cookie-universal')(req, res);\n if (cookies.get('token')) {\n try {\n user = await get(\"users/me\", null, cookies.get('token'));\n } catch (e) {\n console.log('err at users', e.toString());\n }\n req.user = user\n req.token = cookies.get('token')\n } else {\n req.user = {}\n req.token = null\n cookies.set('token', null)\n }\n next();\n}\nexport { authenticationMiddleware }\n```\n\n```text\nauthenticationMiddleware.js\n```\n\n```text\nserver.js\n```\n\n```text\nauthenticationMiddleware.js\n```\n\n========================================\n\nComments:\n- How I can redirect specific pages here? like profile page if lot login redirect to login page.\n- I like this solution but how is `AuthMiddleware.beforeChange()` executed before the route change? In my experimentation any callback passed into subscribe is called after the store changes. Further, I've found `from` and `to` are equal because the route change has already happened by the time the function is executed. I'm only asking because I'm curious what you did beyond whats included in the answer.\n- Yeah sorry. It is possible that `beforeChange` is not really called *before* the route change (It was just some good sounding name that I liked). I just needed SOME solution for my problem and at that time this was enough for my needs. If you find something better, feel free to edit my answer (or send me an DM and I will edit it myself).\n- Would this work on exported static version ot the app?\n- I think the issue you're going to run into here is that sapper is a little bit *too* efficient. Once you get the main chunks over to the client calls for rendered components happen infrequently. From what I can tell, `beyonk-adventures/sapper-rbac` has the most complete solution to date but they still need that client-side part.","metadata":{"transformedAt":"2026-08-18T18:33:40.674Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":160,"estimatedTokens":1113}}221{"id":"stack-49389697","source":"stackoverflow","questionId":49389697,"title":"How to use JavaScript libraries with Sapper/Svelte?","tags":["svelte"],"text":"Title: How to use JavaScript libraries with Sapper/Svelte?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nUsing Sappers export feature to build a static site, I would love to be able to use JavaScript libraries like Conversational Form and GSAP. Trying to add them to `client.js` or my components, I can't access the `window` object.\n\nHow do I best approach this?\n\n========================================\n\nCode:\n```text\nclient.js\n```\n\n```text\nwindow\n```\n\n```js\n<script>\n import { TweenMax, Power2, TimelineLite } from 'gsap';\n\n export default {\n oncreate() {\n // use GSAP in here, or in custom methods\n }\n };\n</script>\n```\n\n```text\nimport\n```\n\n========================================\n\nComments:\n- It seems you have a problem with your code. However, we can't help unless we have code or information that can reproduce the problem. Otherwise, we are just blindly guessing.\n- This was exactly the hint I needed. Thanks a lot Rich.","metadata":{"transformedAt":"2026-08-18T18:33:40.674Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":41,"estimatedTokens":236}}222{"id":"stack-57224986","source":"stackoverflow","questionId":57224986,"title":"Svelte build initial render to index.html file","tags":["javascript","html","svelte","sapper"],"text":"Title: Svelte build initial render to index.html file\nTags: javascript, html, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI've decided try out Svelte for my next website, and this will be a static website hosted using GitLab pages.\n\nI got the basic compilation working which generates `dist/bundle.js` and `dist/bundle.css`.\n\nThe issue is that I cannot upload this `dist` folder as there is no `index.html` file.\n\nHow do I get Svelte/rollup to generate an `index.html` file which contains the **initial** render?\n\nThe other option is to create my own `index.html` file and import `bundle.js`. This is not an option for me because the initial render is now generated at runtime via javascript instead of at compile-time, potentially having a negative SEO impact and preventing users without javascript from at least seeing something.\n\nI was also looking at Sapper which does server-side rendering, which, from what I know, does an initial rendering server-side. However, this seems to require you to have a server instead of rendering to a file, and seems overly complicated for a static single-page website.\n\n========================================\n\nTop Answer:\nI have recently started experimenting with Svelte and started by downloading the hello world example.\n\nI then just started altering it for my needs.\n\nIt already has an `index.html` file set up in the public folder (it is set up to compile to the public folder instead of dist). Svelte / Rollup will not generate an `index.html` file, it is purely for compiling and bundling your JS / Svelte components.\n\nThe `index.html` file supplied is just basic:\n\n```\n\n \n \n\n Svelte app\n\n \n \n \n\n \n\n```\n\nThe `main.js` looks like this:\n\n```\nimport App from './App.svelte';\n\nvar app = new App({\n target: document.body\n});\n\nexport default app;\n```\n\nHere is a link [source], [build] to my first svelte app if you're interested.\n\nAs far as SEO is concerned, I hear all over the place for years that google can crawl JS now, but I am not convinced. A JS driven SPA will never have the SEO juice that a standard html page will.\n\nThat being said, I am currently working on an SPA with svelte that I want good SEO for. The interactive part is only a small part of the page, so I am adding the rest (text, images and stuff) directly to the `index.html` so search engines should have no problem crawling it. I just change the `main.js` to inject the app into a div (with the ID of app) rather than the body.\n\nSo the `main.js` looks like this:\n\n```\nimport App from './App.svelte';\n\nvar app = new App({\n target: document.getElementById('app'),\n});\n\nexport default app;\n```\n\nI have not yet done anything with Sapper so I can't comment on that.\n\nI hope my answer helps in some way.\n\n========================================\n\nCode:\n```text\ndist/bundle.js\n```\n\n```text\ndist/bundle.css\n```\n\n```text\ndist\n```\n\n```text\nindex.html\n```\n\n```text\nindex.html\n```\n\n```text\nindex.html\n```\n\n```text\nbundle.js\n```\n\n```text\nsapper export\n```\n\n```text\n<!doctype html>\n<html>\n<head>\n <meta charset='utf8'>\n <meta name='viewport' content='width=device-width'>\n\n <title>Svelte app</title>\n\n <link rel='icon' type='image/png' href='favicon.png'>\n <link rel='stylesheet' href='global.css'>\n <link rel='stylesheet' href='bundle.css'>\n</head>\n\n<body>\n <script src='bundle.js'></script>\n</body>\n</html>\n```\n\n```text\nimport App from './App.svelte';\n\nvar app = new App({\n target: document.body\n});\n\nexport default app;\n```\n\n```text\nimport App from './App.svelte';\n\nvar app = new App({\n target: document.getElementById('app'),\n});\n\nexport default app;\n```\n\n```text\nindex.html\n```\n\n```text\nindex.html\n```\n\n```text\nindex.html\n```\n\n```text\nmain.js\n```\n\n```text\nindex.html\n```\n\n```text\nmain.js\n```\n\n```text\nmain.js\n```\n\n========================================\n\nComments:\n- I actually did start with that hello world example and that's when I decided to ask this question. If I put the static content in `index.html`, it defeats my purpose of using svelte because my website is mainly static and the only dynamic parts will be maybe a hamburger menu. So I intend to use Svelte as more of a html compiler than a js compiler due to my lack of dynamic parts, similar to next.js and react static and a few others (which have the issue of either not allowing any client-side javascript inside components or require the entire react runtime which I'mtrying toavoid byusing Svelte)\n- Then it seems to me that you don't need svelte at all (or any JS framework). A menu can be made with minimal CSS and maybe a small amount of JS. Maybe a static site generator would more suit your needs. I persoannly use metalsmith for my blog.\n- Svelte allows me to separate into components with scoped styles and javascript and I find it difficult to develop without this. I could use other template engines but I can't find any that have scoped css and js. I also prefer to stick with Svelte so that I can use it across projects regardless of whether I'd like to generate a static website or not. Svelte already generates a static website unless you use something like sapper, but requires javascript to generate the initial render instead of generating a html file with the initial render. I would have expected this to be a simple task.\n- Looks like sapper has been superseded by SvelteKit (by the same people): kit.svelte.dev","metadata":{"transformedAt":"2026-08-18T18:33:40.675Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":187,"estimatedTokens":1335}}223{"id":"stack-72375181","source":"stackoverflow","questionId":72375181,"title":"Remount page after navigating to same route - sveltekit","tags":["svelte","sveltekit"],"text":"Title: Remount page after navigating to same route - sveltekit\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nWhen im using svelte-kits routing system, I can create dynamics pages using `[page].svelte` for example, that will be rendered when I'm calling `localhost:3000/foo`. However when I'm navigating from `localhost:3000/foo` to `localhost:3000/bar`, the `onMount()` function is not called (I guess for performance reasons).\n\nI can work around this issue by wrapping all relevant stuff in a `{#key ... }` expression, but is there any way to \"remount\" the page?\n\nThenks for helping me out :)\n\n========================================\n\nCode:\n```text\n[page].svelte\n```\n\n```text\nlocalhost:3000/foo\n```\n\n```text\nlocalhost:3000/foo\n```\n\n```text\nlocalhost:3000/bar\n```\n\n```text\nonMount()\n```\n\n```text\n{#key ... }\n```\n\n```text\nonMount\n```\n\n```text\n{#key}\n```\n\n========================================\n\nComments:\n- Any particular reason why you would want to remount? If you have actions that you want to trigger when `page` changes, you can put all these actions inside a function and call that function when `page` updates with a reactive statement that is dependent on `page`, for example: `$: doRefresh(page)`.\n- Maybe since I'm coming from other libraries, I'm still used to this convention, but your suggestion is also an elegant way. As @Bob Fanger mentioned, rarely I had some issues with third party libraries (p5js) where a `canvas` element was not fully removed, leading to performance issues. There it seemed easier to just fully 'remount' the page.\n- That's a fair assessment, and for these situations `{#key}` would indeed be the right choice.","metadata":{"transformedAt":"2026-08-18T18:33:40.675Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":52,"estimatedTokens":416}}224{"id":"stack-75832641","source":"stackoverflow","questionId":75832641,"title":"How to compile Svelte 3 components into IIFE's that can be used in vanilla js","tags":["javascript","svelte","web-component","svelte-3","iife"],"text":"Title: How to compile Svelte 3 components into IIFE's that can be used in vanilla js\nTags: javascript, svelte, web-component, svelte-3, iife\nSource: Stack Overflow\n\nQuestion:\nI am making a web component in Vanilla JS that use a hidden `select` in the background and a `div` and `ul>li` in front. It became a bit complex with fetching data from an api, ect, so I transitioned to Svelte to simplify it and make it more readable.\n\nNow I've tried for 2 days to export the component as an IIFE. I just can't seem to figure out how. I might be mistaken, but I thought that was one of the main features of Svelte - to make reusable components that can be used anywhere. Making it was the easy part, but now I want to load it and use it directly in the browser (with ``). I thought that should be easy?\n\nI use Svelte 3 (3.57.0) with Vite 4 (4.2.1), and I have tried both `npm create svelte` to create a library project with SvelteKit and `npm init vite` with `svelte` as framework.\n\nI've read quite a lot of the documentation for Vite and Svelte, but it feels overwhelming and I can't seem to find a configuration that works.\n\n*Does anyone know how to compile components to IIFEs in Svelte?*\n\n========================================\n\nCode:\n```text\nselect\n```\n\n```text\ndiv\n```\n\n```text\nul>li\n```\n\n```text\n<script src=\"\"></script>\n```\n\n```text\nnpm create svelte\n```\n\n```text\nnpm init vite\n```\n\n```text\nsvelte\n```\n\n```js\n// vite.js.config.js\nimport { svelte } from '@sveltejs/vite-plugin-svelte';\nimport { defineConfig } from 'vite';\nimport { resolve } from 'path';\n\nexport default defineConfig({\n build: {\n lib: {\n entry: resolve(__dirname, 'dist/index.js'),\n name: 'Components',\n fileName: 'components',\n },\n outDir: 'dist-js',\n },\n plugins: [\n svelte(),\n ],\n});\n```\n\n```bash\nvite -c vite.js.config.js build\n```\n\n```text\ndist\n```\n\n```text\ndist-js\n```\n\n```text\n-c\n```\n\n```text\npackage.json\n```\n\n```text\nimport\n```\n\n```text\nbuild.lib.name\n```\n\n```text\nComponent\n```\n\n```text\nindex.js\n```\n\n```text\nnew Components.Component({ ... })\n```\n\n========================================\n\nComments:\n- Why would you try to do that? Why not compile it as a regular module instead of polluting global scope?\n- I'm not super up to date on 'regular modules'. I'm primarily looking for a way to drop in / use a svelte component in a regular HTML document. To make the question more specific I went with IIFE's as that is what I know. Do you know about any resources for compiling them into such a module?\n- Thank you, thank you, thank you! That was very enlightening and helpful - works like a charm!\n- Thanks for this — I just went through the proces with my own project in Svelte 4, here's the repo in case anyone wants another example to reference: github.com/kitschpatrol/tweakpane-css","metadata":{"transformedAt":"2026-08-18T18:33:40.675Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":114,"estimatedTokens":709}}225{"id":"stack-74936501","source":"stackoverflow","questionId":74936501,"title":"SvelteKit: How to access Firebase authentication state from the server","tags":["firebase","svelte","sveltekit"],"text":"Title: SvelteKit: How to access Firebase authentication state from the server\nTags: firebase, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm managing authentication state in a readable store which is grouped with a promise that resolves when the auth state is known (either signed in or out). The store is set internally via `onAuthStateChange`.\n\nI'm trying to access this auth state from the server (`+layout.server.ts` and `+page.server.ts`) so that I can redirect the user to a sign-in page if they aren't authenticated, or load data from the database if (and only if) they are. No matter what I try, whenever I access this store from the server, its value is always null. I think this is because Firebase is only supposed to run on the client, although I'm not sure. Is there any way I can access this store from the server, or change my implementation so that Firebase runs in the server and passes auth state to the client? This blog post explains pretty much exactly what I want to do, but the solution here seems more complicated than it needs to be.\n\nI've tried moving Firebase initialization code to the server (in both `hooks.server.ts` and `+layout.server.ts`), but there's no way for me to pass the auth object to the client because it can't be serialized (I get an error explaining this when I try to return it from a load function in `+page.server.ts`). I've also tried to handle authentication only using client-side code, but the server is responsible for loading data from the database, so in this case there's no way for me to verify a valid authentication state from the server.\n\n========================================\n\nCode:\n```text\nonAuthStateChange\n```\n\n```text\n+layout.server.ts\n```\n\n```text\n+page.server.ts\n```\n\n```text\nhooks.server.ts\n```\n\n```text\n+layout.server.ts\n```\n\n```text\n+page.server.ts\n```\n\n========================================\n\nComments:\n- Blog post you referenced explains all in details and code there is not overcomplicated. What answer do you expect?\n- Verifying auth state before a database call strikes me as a very standard problem that should have a well-defined solution. Adding a Firebase service account and saving auth state to cookies feels like an over-engineered solution relative to the problem at hand, but if this is the correct way to do it then so be it.\n- firebase expects you to use firestore or the firebase real time database, which work better with firebase auth. if you need to access auth state on your server to call a non-firebase service, this mechanically make it more complex, it's not that surprising.\n- I am using firebase realtime database.\n- Thank you for your response, and for sharing your solution in the first place!\n- Thanks for the informative blog! OOC, have you tried using `hooks.ts`? I haven't tried it myself but that's what I hear lends itself well to JWT-based auth and such.","metadata":{"transformedAt":"2026-08-18T18:33:40.675Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":47,"estimatedTokens":719}}226{"id":"stack-70097888","source":"stackoverflow","questionId":70097888,"title":"How to get a reference to a Svelte component from within the component","tags":["javascript","svelte","svelte-3"],"text":"Title: How to get a reference to a Svelte component from within the component\nTags: javascript, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nThere's an easy way to get a reference to an instance of a sub component from the parent scope, as shown in the tutorial.\n\nWhat I want is to get a reference to the component from within the component itself. So, if we were looking at the official Svelte demo linked above, I would be meaning that I want a reference to the InputField instance from within the InputField instance, rather than from App.svelte.\n\n(The reason I want this: I need instances to fire hooks to external JS libraries that will interract with the instance programmatically.)\n\n### Copy of code from tutorial (for convenience and longevity)\n\nApp.svelte:\n\n```\n\n import InputField from './InputField.svelte';\n let field;\n\n field.focus()}>Focus field\n```\n\nInputFiled.svelte:\n\n```\n\n let input;\n export function focus() {\n input.focus();\n }\n\n // Somewhere here, I want a var, like you might imagine the following to do:\n let myself = this;\n\n```\n\n========================================\n\nCode:\n```html\n<script>\n import InputField from './InputField.svelte';\n let field;\n</script>\n<InputField bind:this={field}/>\n<button on:click={() => field.focus()}>Focus field</button>\n```\n\n```html\n<script>\n let input;\n export function focus() {\n input.focus();\n }\n\n // Somewhere here, I want a var, like you might imagine the following to do:\n let myself = this;\n</script>\n<input bind:this={input} />\n```\n\n```text\n<script>\n import InputField from './InputField.svelte';\n let field;\n</script>\n\n<InputField bind:this={field} {field}/>\n\n<button on:click={() => field.focus()}>Focus field</button>\n```\n\n```text\n<script>\n let input;\n export let field;\n export function focus() {\n input.focus();\n }\n let myself;\n $:if(field) myself = field;\n</script>\n<input bind:this={input} />\n```\n\n========================================\n\nComments:\n- I did think that might be an option (seems odd to have to do this though!). What did you mean by \"you can use it with context\"?\n- @artfulrobot create a context with the field and usecontext in input, just a way to tidy things up and not oddly pass it to the component and be able to use it anywhere.\n- Ah, yeah, ok, thanks very much.","metadata":{"transformedAt":"2026-08-18T18:33:40.675Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":92,"estimatedTokens":585}}227{"id":"stack-57802087","source":"stackoverflow","questionId":57802087,"title":"How to create and style svelte 3 custom elements with nested components?","tags":["web-component","shadow-dom","custom-element","svelte","svelte-component"],"text":"Title: How to create and style svelte 3 custom elements with nested components?\nTags: web-component, shadow-dom, custom-element, svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create custom-element (web component) in svelte 3. I can't find any way to style nested components from css. Svelte removes styles before injecting them to `` inside of ShadowDOM.\n\nThe problem is that I want to have nested components in my root element.\nFor example:\n\nRootComponent (svelte custom-element)\n\n- (imports) FooComponent\n\n- (imports) BarComponent\n\nAs stated here: svelte-custom-element\n\nAll the components imported to custom-element must have compiler option set to ``.\n\nWith this option set nested components works as expected and are injected into root's element ShadowDOM. The problem is that `styles` defined in nested components are not being injected. \nThe workaround for this problem would be to inject them into root's element `` as global styles within ShadowDom. \n(Un)fortunately svelte automatically removes all unused styles during compilation when custom elements not yet exist. \n\nMy goal is to create web component with svelte and then use it outside of svelte as native web-component.\n\nHere is REPL\n\nCustom elements do not really work on REPL as Conduitry wrote:\n\n The compiler options in the REPL don't actually affect the code that >is run, just the code that is displayed. So enabling customElement >doesn't mean you are building and running a web component\n\nSo it's more like a code example than working one.\n\n- I would like to know if there is another way to create svelte custom-element with nested component and proper styling.\n\n- Is there a way to disable removing of unused css?\n\nhttps://i.sstatic.net/FEeEC.jpg\n\nfrom `` starts Nested component imported from Nested.svelte.\n\n`` element should have `.nested` class injected but it is removed by svelte compiler.\n\n========================================\n\nTop Answer:\nThis is because when `customElement` option is on, each style in a component is injected into the `shadowRoot` of the custom element.\n\n```\nclass YourComponent extends SvelteElement {\n constructor(options) {\n super();\n\n this.shadowRoot.innerHTML = `.foo{color:red;}`;\n// continues\n```\n\nThus, in order to make `style` appear, **you must use svelte component as custom element**, not as svelte component.\n\nYour `App.svelte` should be like below.\n\n```\n\n import Foo from './Foo.svelte'\n import Bar from './Bar.svelte'\n\n```\n\nHowever, this neither solve the problems related with custom element. \n\n:global selector is not transformed into actual global selector.\n\nEvery nested component will produce `shadowRoot`, whereas mostly you will want only top-level one.\n\nCheck out some issues below from svelte repository related to custom elements.\n\n- nested component in custom element does not inherit style #2605\n\n- :global(...) not working in custom elements #2969\n\nIt seems like svelte does not fully support style cascading in custom element yet, should be handled in future.\n\nChecked in svelte v3.12.1.\n\n========================================\n\nCode:\n```text\n<style>\n```\n\n```text\n<svelte:options tag=\"component-name\" />\n```\n\n```text\nstyles\n```\n\n```text\n<style>\n```\n\n```text\n<div class=\"nested\">\n```\n\n```text\n<style>\n```\n\n```text\n.nested\n```\n\n```js\nclass YourComponent extends SvelteElement {\n constructor(options) {\n super();\n\n this.shadowRoot.innerHTML = `<style>.foo{color:red;}</style>`;\n// continues\n```\n\n```js\n<script>\n import Foo from './Foo.svelte'\n import Bar from './Bar.svelte'\n</script>\n<svelte:options tag=\"web-component\" />\n\n<foo-component/>\n<bar-component/>\n```\n\n```text\ncustomElement\n```\n\n```text\nshadowRoot\n```\n\n```text\nstyle\n```\n\n```text\nApp.svelte\n```\n\n```text\nshadowRoot\n```\n\n```js\nlet cssKeep: string = \"\";\n```\n\n```html\n<span style=\"display: none;\" class={cssKeep}><span class={cssKeep} /> </span>\n```\n\n```html\n<script lang=\"ts\">\n export let content: string;\n</script>\n\n<p class=\"red\"> {content} </p>\n```\n\n```html\n<svelte:options tag=\"my-element\" />\n\n<script lang=\"ts\">\n import Message from \"./components/Message.svelte\";\n let cssKeep: string = \"\";\n</script>\n\n<Message content=\"hello\" />\n\n<span style=\"display: none;\" class={cssKeep}><span class={cssKeep} /> </span>\n\n<style>\n .red {\n color: red;\n }\n</style>\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\n\nexport default defineConfig({\n build: {\n lib: {\n entry: './src/main.ts',\n name: 'MyElement'\n },\n },\n plugins: [\n svelte(\n {\n compilerOptions: {\n css: true,\n },\n exclude: \"./src/App.svelte\",\n emitCss: true,\n }\n ),\n svelte(\n {\n compilerOptions: {\n customElement: true,\n css: true,\n },\n exclude: \"./src/components/**\",\n emitCss: true,\n }\n ),\n ],\n})\n\n\n// guide: https://www.thisdot.co/blog/web-components-with-svelte\n```\n\n```text\nApp.svelte\n```\n\n```text\nApp.svelte\n```\n\n```text\n./components/Message.svelte\n```\n\n```text\nMessage.svelte\n```\n\n```text\n<style>\n```\n\n```text\nMessage.svelte\n```\n\n```text\n<style>\n```\n\n```text\nApp.svelte\n```\n\n```text\nApp.svelte\n```\n\n```text\nApp.svelte\n```\n\n```text\nsrc/components/Message.svelte\n```\n\n```text\nsrc/App.svelte\n```\n\n```text\nvite.config.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.675Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":280,"estimatedTokens":1333}}228{"id":"stack-66877654","source":"stackoverflow","questionId":66877654,"title":"How to disable transition animation on parent component mount and destroy in Svelte?","tags":["svelte","svelte-3","sapper","svelte-component"],"text":"Title: How to disable transition animation on parent component mount and destroy in Svelte?\nTags: svelte, svelte-3, sapper, svelte-component\nSource: Stack Overflow\n\nQuestion:\nRight now, I have a menu which on click of a hamburger button can be expanded or collapsed. The default state of the menu is `true` meaning its expanded, but when I go to a different route where the menu is `not there`, it plays the collapsed animation. Here is a sample code:\n\n```\n\n import { slide } from 'svelte/transition';\n let isExpanded = true; \n\nisExpanded=!isExpanded}>Expand/Collapse\n\n{#if isExpanded}\n \n Content\n \n{/if}\n\nThere is no menu in this page\n```\n\nThis is the current behavior of the code:\n\nOn page load/reload, the menu expand transition plays (weirdly, this only happens sometimes) and on clicking the link, the menu collapse transition plays for a split second while the redirect is happening.\n\nI'm not sure if this is a bug or something wrong in my implementation. Either case, would be grateful if a workaround is provided for this.\n\nThanks in advance!\n\n========================================\n\nTop Answer:\nIn svelte transitions are triggered only when the component is either mounted (added to the dom) or destroyed (removed from the dom), so the only way to disable transition on mount/destroy cycles is to not use it.\n\n========================================\n\nCode:\n```text\n<script>\n import { slide } from 'svelte/transition';\n let isExpanded = true; \n</script>\n\n<button on:click={()=>isExpanded=!isExpanded}>Expand/Collapse</button>\n\n{#if isExpanded}\n <nav transition:slide>\n Content\n </nav>\n{/if}\n\n<a href=\"/some-page\">There is no menu in this page</a>\n```\n\n```text\ntrue\n```\n\n```text\nnot there\n```\n\n```text\n{#if isExpanded}\n <nav transition:slide|local>\n Content\n </nav>\n{/if}\n```\n\n```text\nlocal\n```\n\n```text\n|local\n```\n\n```text\n|global\n```\n\n========================================\n\nComments:\n- it might be helpful to clarify the question title is upon **parent** mount/destroy","metadata":{"transformedAt":"2026-08-18T18:33:40.675Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":88,"estimatedTokens":498}}229{"id":"stack-73427629","source":"stackoverflow","questionId":73427629,"title":"SvelteKit - api response data (PageData) not updated after initial render","tags":["typescript","svelte","sveltekit"],"text":"Title: SvelteKit - api response data (PageData) not updated after initial render\nTags: typescript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nam new to svelte and svelteKit in general and am trying to load data from api and I followed the sveltekit todo sample code. It's working well for initial rendering and `a` tag onClick but in div `on:click` am updating url parameters api getting called and returns data but `PageData` object not updating.\n\nHere I have attached my `onClick`\n\n```\nimport { goto } from '$app/navigation'; \nconst adhigaramClick = (adhigaram: string) => {\n selectedAdhigaram = adhigaram\n $page.url.searchParams.set('adhigaram',adhigaram); \n goto(`?${$page.url.searchParams.toString()}`);\n }\n```\n\nHere I have attached the api call (`+page.server.ts`)\n\n```\nexport const load: PageServerLoad = async ({url, params}) => {\n let selectedPaal = \"test;\n\n const paramPaal =url.searchParams.get(\"paal\")\n const adhigaram =url.searchParams.get(\"adhigaram\")\n\n if (paramPaal) {\n selectedPaal = paramPaal;\n }\n \n const response = await api('GET', `page/${selectedPaal}${adhigaram?`/${adhigaram}` : ''}`);\n \n if (response.status === 404) {\n return {\n data: {} as Page\n };\n }\n\n if (response.status === 200) { \n return {\n ... (await response.json()) as Data\n };\n }\n throw error(response.status);\n};\n```\n\n`+page.svelte.ts` file to get the response data(`PageData`)\n\n```\nimport type { PageData } from './$types';\n\n export let data: PageData;\n $: console.log(data);\n```\n\n`a` tag click is working fine page re rendering\n\n```\n\n {paal.titleTamil}\n\n```\n\n========================================\n\nTop Answer:\nAdding to @FlippingBinary's answer, my issue was not that the load function was not rerunning, but that the UI was not updating.\n\nThe `{#key ...}` block fixed the rerendering for me.\n\nhttps://svelte.dev/docs#template-syntax-key\n\nJ\n\n========================================\n\nCode:\n```text\nimport { goto } from '$app/navigation'; \nconst adhigaramClick = (adhigaram: string) => {\n selectedAdhigaram = adhigaram\n $page.url.searchParams.set('adhigaram',adhigaram); \n goto(`?${$page.url.searchParams.toString()}`);\n }\n```\n\n```text\nexport const load: PageServerLoad = async ({url, params}) => {\n let selectedPaal = \"test;\n\n const paramPaal =url.searchParams.get(\"paal\")\n const adhigaram =url.searchParams.get(\"adhigaram\")\n\n if (paramPaal) {\n selectedPaal = paramPaal;\n }\n \n const response = await api('GET', `page/${selectedPaal}${adhigaram?`/${adhigaram}` : ''}`);\n \n if (response.status === 404) {\n return {\n data: {} as Page\n };\n }\n\n if (response.status === 200) { \n return {\n ... (await response.json()) as Data\n };\n }\n throw error(response.status);\n};\n```\n\n```text\nimport type { PageData } from './$types';\n\n export let data: PageData;\n $: console.log(data);\n```\n\n```text\n<a href={`?paal=${paal.keyword}`} >\n {paal.titleTamil}\n</a>\n```\n\n```text\na\n```\n\n```text\non:click\n```\n\n```text\nPageData\n```\n\n```text\nonClick\n```\n\n```text\n+page.server.ts\n```\n\n```text\n+page.svelte.ts\n```\n\n```text\nPageData\n```\n\n```text\na\n```\n\n```text\nload\n```\n\n```text\nload\n```\n\n```text\n+layout.js\n```\n\n```text\nurl\n```\n\n```text\nparams\n```\n\n```text\nload\n```\n\n```text\nparams\n```\n\n```text\nurl\n```\n\n```text\nurl.pathname\n```\n\n```text\nurl.search\n```\n\n```text\nawait parent()\n```\n\n```text\nload\n```\n\n```text\nfetch\n```\n\n```text\ndepends\n```\n\n```text\ninvalidate(url)\n```\n\n```text\ninvalidate()\n```\n\n```text\nload\n```\n\n```text\ndata\n```\n\n```text\nafterNavigate\n```\n\n```text\n{#key ...}\n```\n\n```text\n{#key ...}\n```\n\n```text\n<script>\n...\n$: data, data = data\n...\n</script>\n```\n\n```text\ninvalidateAll()\n```\n\n========================================\n\nComments:\n- There is no place in your code where you call \"adhigaramClick\". Do you have a minimal +page.ts and +page.server.ts file that reproduces the behavior?\n- I have a list of div am calling that \"adhigaramClick\" function while user clicks on the div","metadata":{"transformedAt":"2026-08-18T18:33:40.675Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":35,"totalLines":262,"estimatedTokens":1003}}230{"id":"stack-64847693","source":"stackoverflow","questionId":64847693,"title":"Uncaught Error: 'target' is a required option - Svelte","tags":["npm","svelte","rollupjs"],"text":"Title: Uncaught Error: 'target' is a required option - Svelte\nTags: npm, svelte, rollupjs\nSource: Stack Overflow\n\nQuestion:\nI'm building an NPM package for Svelte. With this package I export a couple of simple components:\n\n```\nimport SLink from './SLink.svelte';\nimport SView from './SView.svelte';\n\nexport { SLink, SView };\n```\n\nThis is before bundling them to a minified version using rollup.\n\nRollup config:\n\n```\nmodule.exports = {\n input: 'src/router/index.ts',\n output: {\n file: pkg.main,\n format: 'umd',\n name: 'Router',\n sourcemap: true,\n },\n plugins: [\n svelte({\n format: 'umd',\n preprocess: sveltePreprocess(),\n }),\n resolve(),\n typescript(),\n terser(),\n ],\n};\n```\n\n`package.json` (minus unnecessary info):\n\n```\n{\n \"name\": \"svelte-dk-router\",\n \"version\": \"0.1.29\",\n \"main\": \"dist/router.umd.min.js\",\n \"scripts\": {\n \"lib\": \"rollup -c lib.config.js\",\n },\n \"peerDependencies\": {\n \"svelte\": \"^3.0.0\"\n },\n \"files\": [\n \"dist/router.umd.min.js\"\n ],\n}\n```\n\nWhen I publish the package and test it, I get this error:\n\n```\nUncaught Error: 'target' is a required option\n at new SvelteComponentDev (index.mjs:1642)\n at new Home (App.svelte:5)\n at Z (router.umd.min.js:1)\n at N (router.umd.min.js:1)\n at new t.SView (router.umd.min.js:1)\n at create_fragment (App.svelte:5)\n at init (index.mjs:1476)\n at new App (App.svelte:5)\n at main.js:7\n at main.js:9\n```\n\nWhich seems to be something to do with mounting the component as `target` is used to mount:\n\n```\nconst app = new App({ target: document.body })\n```\n\nThe odd thing is, `SLink` on it's own works fine, mounts as it should etc., it's just `SView` that doesn't work.\n\n`SLink`:\n\n```\n\n import { writableRoute, changeRoute } from '../logic';\n\n export let name: string = undefined,\n path: string = undefined,\n query: Record = undefined,\n params: Record = undefined;\n\n let routerActive: boolean;\n\n writableRoute.subscribe(newRoute => {\n if (newRoute.path === '*') return;\n const matches = (path && path.match(newRoute.regex)) || newRoute.name === name;\n routerActive = matches ? true : false;\n });\n\n changeRoute({ name, path, query, params })}\n class={routerActive ? 'router-active' : ''}>\n \n\n```\n\n`SView`:\n\n```\n\n import { writableRoute } from '../logic';\n\n let component: any;\n\n writableRoute.subscribe(newRoute => (component = newRoute ? newRoute.component : null));\n\n```\n\nI've tried the components uncompiled, as per these docs, but then the imports don't work.\n\nAnyone have any idea how I can work around this issue?\n\n========================================\n\nTop Answer:\nI recently ran into this problem. I was setting up a new page and forgot the `defer` keyword on the `script`. I had:\n\n```\n\n```\n\nand it needed to be\n\n```\n\n```\n\nNotice the missing `defer`.\n\n========================================\n\nCode:\n```js\nimport SLink from './SLink.svelte';\nimport SView from './SView.svelte';\n\nexport { SLink, SView };\n```\n\n```js\nmodule.exports = {\n input: 'src/router/index.ts',\n output: {\n file: pkg.main,\n format: 'umd',\n name: 'Router',\n sourcemap: true,\n },\n plugins: [\n svelte({\n format: 'umd',\n preprocess: sveltePreprocess(),\n }),\n resolve(),\n typescript(),\n terser(),\n ],\n};\n```\n\n```json\n{\n \"name\": \"svelte-dk-router\",\n \"version\": \"0.1.29\",\n \"main\": \"dist/router.umd.min.js\",\n \"scripts\": {\n \"lib\": \"rollup -c lib.config.js\",\n },\n \"peerDependencies\": {\n \"svelte\": \"^3.0.0\"\n },\n \"files\": [\n \"dist/router.umd.min.js\"\n ],\n}\n```\n\n```js\nUncaught Error: 'target' is a required option\n at new SvelteComponentDev (index.mjs:1642)\n at new Home (App.svelte:5)\n at Z (router.umd.min.js:1)\n at N (router.umd.min.js:1)\n at new t.SView (router.umd.min.js:1)\n at create_fragment (App.svelte:5)\n at init (index.mjs:1476)\n at new App (App.svelte:5)\n at main.js:7\n at main.js:9\n```\n\n```js\nconst app = new App({ target: document.body })\n```\n\n```js\n<script lang=\"ts\">\n import { writableRoute, changeRoute } from '../logic';\n\n export let name: string = undefined,\n path: string = undefined,\n query: Record<string, string> = undefined,\n params: Record<string, string> = undefined;\n\n let routerActive: boolean;\n\n writableRoute.subscribe(newRoute => {\n if (newRoute.path === '*') return;\n const matches = (path && path.match(newRoute.regex)) || newRoute.name === name;\n routerActive = matches ? true : false;\n });\n</script>\n\n<div\n on:click={() => changeRoute({ name, path, query, params })}\n class={routerActive ? 'router-active' : ''}>\n <slot />\n</div>\n```\n\n```js\n<script lang=\"ts\">\n import { writableRoute } from '../logic';\n\n let component: any;\n\n writableRoute.subscribe(newRoute => (component = newRoute ? newRoute.component : null));\n</script>\n\n<svelte:component this={component} />\n```\n\n```text\npackage.json\n```\n\n```text\ntarget\n```\n\n```text\nSLink\n```\n\n```text\nSView\n```\n\n```text\nSLink\n```\n\n```text\nSView\n```\n\n```json\n{\n \"name\": \"svelte-dk-router\",\n \"version\": \"0.1.29\",\n \"main\": \"dist/router.umd.min.js\",\n\n \"svelte\": \"src/index.js\",\n\n \"scripts\": {\n \"lib\": \"rollup -c lib.config.js\",\n },\n \"peerDependencies\": {\n \"svelte\": \"^3.0.0\"\n },\n \"files\": [\n \"dist/router.umd.min.js\"\n ],\n}\n```\n\n```js\nimport SLink from './SLink.svelte';\nimport SView from './SView.svelte';\n\nexport { SLink, SView };\n```\n\n```text\nnode_modules/svelte\n```\n\n```text\nmain\n```\n\n```text\npackage.json\n```\n\n```text\nsvelte\n```\n\n```text\n.js\n```\n\n```text\npackage.json\n```\n\n```text\nsrc/index.js\n```\n\n```text\nrollup-plugin-svelte\n```\n\n```text\nsvelte\n```\n\n```text\npackage.json\n```\n\n```text\ntemplate.html\n```\n\n```text\nsrc\n```\n\n```text\n#sapper\n```\n\n```text\n%sapper.html%\n```\n\n```text\ndocument.body\n```\n\n```text\nclient.js\n```\n\n```text\nsrc\n```\n\n```text\n<script src=\"/app/public/build/bundle.js\"></script>\n```\n\n```text\n<script defer src=\"/app/public/build/bundle.js\"></script>\n```\n\n```text\ndefer\n```\n\n```text\nscript\n```\n\n```text\ndefer\n```\n\n========================================\n\nComments:\n- This does seem to be on the right track, but then the imports don't work as `../logic` is compiled to `umd`\n- You should import from the uncompiled source file, so it goes in the right bundle with the rest. `import { ... } from './logic.js'` or something like this, with a `src/logic.js` file.\n- I decided to compile all Typescript files into a `dist` folder with a script that also copies the components, point `main` and `svelte` to a single `index.js` which exports everything and this worked. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:40.675Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":37,"totalLines":388,"estimatedTokens":1650}}231{"id":"stack-70398935","source":"stackoverflow","questionId":70398935,"title":"How to deploy a svelte kit app after build using nginx as web server","tags":["node.js","nginx","deployment","svelte","sveltekit"],"text":"Title: How to deploy a svelte kit app after build using nginx as web server\nTags: node.js, nginx, deployment, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a svelte kit project. I want to deploy the app in an Nginx web server after an `npm run build`. At the moment I have a node container and I use to start using `npm run preview`. It's working fine, but I want to deploy in a production environment using `build`.\n\nHow could I do that?\n\nref: https://kit.svelte.dev/docs#command-line-interface-svelte-kit-build\n\n========================================\n\nTop Answer:\nIf you have a static website (ie no endpoints) you should use `@sveltejs/adapter-static`. It will put the files you should serve in `/build` directory. You can then serve the generated pages using NGINX. A sample NGINX config would be:\n\n```\nserver {\n listen 80;\n server_name test.jasonrigden.com;\n root /path/to/build/directory;\n index index.html;\n}\n```\n\nIf your site is not static you should use `@sveltejs/adapter-node` and run that in your container. You could put NGINX in front of it to use its features (SSL, load balancing, firewall, etc). After building your site (using `npm run build`) you can run `node ./build/index.js`.\n\nAlternatively, you could use Netlify, Vercel, or Cloudflare Pages to host you site.\n\nTo see how to change your adapter see the docs.\n\nGood luck!\n\n========================================\n\nCode:\n```text\nnpm run build\n```\n\n```text\nnpm run preview\n```\n\n```text\nbuild\n```\n\n```text\nupstream sveltekit {\n server 127.0.0.1:3000;\n keepalive 8;\n}\n\n\nserver {\n # listen ... \n # servername ...\n\n # root ... (folder with an index.html in case of sveltekit being crashed)\n\n location / {\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-NginX-Proxy true;\n proxy_set_header X-Forwarded-Proto $scheme;\n\n proxy_pass http://sveltekit;\n proxy_redirect off;\n\n error_page 502 = @static;\n }\n\n location @static {\n try_files $uri /index.html =502;\n }\n}\n```\n\n```text\nnode ./build/index.js\n```\n\n```text\nHOST=127.0.0.1\n```\n\n```text\nnode build/index.js\n```\n\n```text\nserver {\n listen 80;\n server_name test.jasonrigden.com;\n root /path/to/build/directory;\n index index.html;\n}\n```\n\n```text\n@sveltejs/adapter-static\n```\n\n```text\n/build\n```\n\n```text\n@sveltejs/adapter-node\n```\n\n```text\nnpm run build\n```\n\n```text\nnode ./build/index.js\n```\n\n```text\nupstream hijacked-media {\n server 127.0.0.1:3000;\n keepalive 64;\n}\n\nserver {\n server_name hijacked.media www.hijacked.media;\n #root /var/www/hijacked.media/sveltekittest/sveltekitprod/PROD-GCP;\n # index index.html index.htm;\n access_log /var/log/nginx/hijacked.media.access.log;\n error_log /var/log/nginx/hijacked.media.error.log;\n\n location / {\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header Host $host;\n\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection 'upgrade';\n\n proxy_pass http://hijacked-media;\n proxy_redirect off;\n proxy_read_timeout 240s;\n #proxy_cache_bypass $http_upgrade;\n }\n\n\n listen 443 ssl; # managed by Certbot\n ssl_certificate /etc/letsencrypt/live/hijacked.media/fullchain.pem; # managed by Certbot\n ssl_certificate_key /etc/letsencrypt/live/hijacked.media/privkey.pem; # managed by Certbot\n include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot\n ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot\n\n\n}\nserver {\n if ($host = www.hijacked.media) {\n return 301 https://$host$request_uri;\n } # managed by Certbot\n\n\n if ($host = hijacked.media) {\n return 301 https://$host$request_uri;\n } # managed by Certbot\n\n\n server_name hijacked.media www.hijacked.media;\n listen 80;\n return 404; # managed by Certbot\n\n\n}\n```\n\n```text\n$ npm run build\n```\n\n```text\ngcloud compute scp --recurse build/ user@gcpinstance:~/Desktop\n```\n\n```text\ngcloud compute scp package*.* user@gcpinstance:~/Desktop\n```\n\n```text\nnpm install\n```\n\n```text\nmkdir SvelteKitProd/\n```\n\n```text\nmv package*.* build/ node-modules/ SvelteKitProd/\n```\n\n```text\nsudo chown -R root:root SvelteKitProd/\n```\n\n```text\nmv SvelteKitProd/ /var/www/domainname/\n```\n\n```text\ncd /var/www/domainname/\n```\n\n```text\nsudo vi /etc/nginx/sites-available/domainname\n```\n\n```text\npm2 start SvelteKitProd/build/index.js\n```\n\n```text\nupstream sveltekit-server {\n server 127.0.0.1:3000;\n keepalive 8;\n}\n\nserver {\n listen 80;\n server_name mydomain.com;\n\n root /home/deploy/frontend/build/client;\n\n location / {\n try_files $uri $uri/ @sveltekit;\n }\n\n location @sveltekit {\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-NginX-Proxy true;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_set_header X-Sendfile-Type X-Accel-Redirect;\n\n proxy_pass http://sveltekit-server;\n proxy_redirect off;\n\n # error_page 502 = @static;\n }\n\n location ^~ /_app/immutable/ {\n # gzip_static on;\n expires max;\n add_header Cache-Control public;\n access_log off;\n try_files $uri $uri/;\n }\n}\n```\n\n========================================\n\nComments:\n- My website isn't static, it's actually an enterprise app. I use a reverse haproxy up front, with ssl and other settings. I tried this settings in the containers, `node ./build/index.js`. It's working fine! Thank you.\n- Thank you. I will learn more about pm2. I use a reverse haproxy up front, with ssl and other settings. I tried this settings in the containers, `node ./build/index.js`. In fact, I think now nginx is not needed to run. Thanks.\n- I am facing issues with the nginx configuration. It works for location /. But if I want to point the sveltekit app to a different location (e.g. /survey), it doesn't work. Why could that be?\n- @sridharraman try setting `config.kit.paths.base` your `svelte.config.js` to `/survey`.\n- @coyotte508, let me try it. I see an issue in my dev app itself now. If I go to localhost:3000, it asks me if I meant /survey. Going to localhost:3000/survey renders it fine, but some of my fetch commands fail as I need to hard-code the 'survey/' path everywhere. I wonder if there is a cleaner approach?\n- You can make a fetch wrapper to add a base path? `function bfetch(path, options) { return fetch(base+path, options)}` Maybe there is a better way, would need to look into the docs. You can `import {base} from \"$app/paths\"`.\n- @coyotte508, changing the base worked somewhat. The app is accessible at the /survey location. But none of the components/assets within _app get loaded. What could be the reason?\n- The @Duke answer support serving the static files as static files, cache on the images and pass only the real nodejs work to nodejs.\n- on /_app/immutable/ location I think there is no need to have the @sveltekit upstream","metadata":{"transformedAt":"2026-08-18T18:33:40.675Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":272,"estimatedTokens":1778}}232{"id":"stack-64928001","source":"stackoverflow","questionId":64928001,"title":"Svelte: Associate label and input in a reusabe way","tags":["html","dom","svelte","svelte-3"],"text":"Title: Svelte: Associate label and input in a reusabe way\nTags: html, dom, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI'm building a Svelte input component which should be usable multible times on the same page.\n\n```\n\n {label}\n \n \n \n \n\n```\n\nTrying to associate label and input I have the following problem:\n\n- I can't use implicit association by changing the outer `` to ``, since the input is not a direct child.\n\n- I can't use the labels `for` attribute, since reusing the element would create mutible identical ids.\n\nIs there a way to create component instance unique ids (pre- or postfixed) in Svelte or is there another solution to this problem.\n\nOr is the best solution to manually set a random string as id?\n\n```\n\n const id = random_string();\n /* ... */\n\n {label}\n \n \n \n \n\n```\n\n========================================\n\nTop Answer:\nWhy not just define a unique name for the input since your need one? You could then just have a component like:\n\n**Input.svelte**\n\n```\n\n export let name\n export let label\n let value\n \n const getInputId = () => {\n return `input_${name}`\n }\n\n {label}\n \n \n \n\n```\n\nAnd use it like:\n\n**App.svelte**\n\n```\n\n import Input from './Input.svelte'\n\n```\n\nCheckout the REPL.\n\n========================================\n\nCode:\n```text\n<div>\n <label>{label}</label>\n <div>\n <input bind:value>\n <!-- some more elements -->\n </div>\n</div>\n```\n\n```text\n<script>\n const id = random_string();\n /* ... */\n</script>\n\n<div>\n <label for={id}>{label}</label>\n <div>\n <input {id} bind:value>\n <!-- some more elements -->\n </div>\n</div>\n```\n\n```text\n<div>\n```\n\n```text\n<label>\n```\n\n```text\nfor\n```\n\n```text\n<script context=\"module\">\n let counter = 0\n</script>\n<script>\n export let label\n let value\n let eltId = 'input_'+ counter++\n</script>\n\n<div>\n <label for={eltId}>{label}</label>\n <div>\n <input id={eltId} bind:value>\n </div>\n</div>\n```\n\n```text\n<script>\n import Input from './Input.svelte'\n</script>\n\n<Input label='Select Country' />\n<Input label='Select Country' />\n<Input label='Select Country' />\n```\n\n```html\n<script>\n export let name\n export let label\n let value\n \n const getInputId = () => {\n return `input_${name}`\n }\n</script>\n\n<div>\n <label for={getInputId()}>{label}</label>\n <div>\n <input id={getInputId()} bind:value>\n </div>\n</div>\n```\n\n```html\n<script>\n import Input from './Input.svelte'\n</script>\n\n<Input name='country' label='Select Country' />\n```\n\n========================================\n\nComments:\n- This is not possible, if the top form itself has to be reusable. And why should the compnent **need** a name?\n- This is a footgun, you're gonna accidentally collide two names and then clicking some label will toggle a checkbox on the other side of the page","metadata":{"transformedAt":"2026-08-18T18:33:40.675Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":176,"estimatedTokens":711}}233{"id":"stack-74589653","source":"stackoverflow","questionId":74589653,"title":"How can I reset the jsdom instance when using vitest in order to test a History-based router?","tags":["javascript","svelte","jsdom","testing-library","vitest"],"text":"Title: How can I reset the jsdom instance when using vitest in order to test a History-based router?\nTags: javascript, svelte, jsdom, testing-library, vitest\nSource: Stack Overflow\n\nQuestion:\nI'd like to do some integration testing of my `svelte` + `page.js`-based router using `vitest`, but I'm running into an issue where the `jsdom` instance only updates correctly once per test file.\n\nIn the following setup, either test will pass when run with `.only` or if I split each test into its own file. But when they run in sequence, the second one will always fail. Inspecting the DOM with `screen.debug()` reveals that it's empty, and calls to `act` or `tick` don't seem to do anything.\n\nI suspect it has something to do with how `jsdom` is interacting with the History API, but I'm not sure where to go from here.\n\n**Root.svelte**\n\n```\n\n import page from 'page'\n\n import SignIn from './SignIn/SignIn.svelte'\n import Upload from './Upload/Upload.svelte'\n import { authenticationToken } from './Root.stores.js'\n\n let currentPage\n\n page('/', () => {\n page.redirect('/sign-in')\n })\n\n page('/sign-in', () => {\n currentPage = SignIn\n })\n\n page('/upload', () => {\n if ($authenticationToken === null) {\n return page.redirect('/sign-in')\n }\n\n currentPage = Upload\n })\n\n page.start()\n\n```\n\n**Root.svelte.test.js**\n\n```\nimport page from 'page'\nimport Root from './Root.svelte'\nimport { authenticationToken } from './Root.stores.js'\n\nit('redirects to sign in when not authenticated', async () => {\n vi.spyOn(page, 'redirect')\n authenticationToken.set(null)\n\n const { act } = setupComponent(Root)\n await act(() => page('/upload'))\n\n expect(page.redirect).toHaveBeenCalledWith('/sign-in')\n})\n\nit('displays the upload screen when authenticated', async () => {\n authenticationToken.set('token')\n\n const { act } = setupComponent(Root)\n await act(() => page('/upload'))\n\n expect(document.getElementById('upload')).toBeInTheDocument()\n})\n```\n\n**Other Research**\n\nThe issue is similar to this one in the `jest` project. In that issue, the recommendation was to call `jsdom.reconfigure()` in a `beforeEach` block, but I don't know how to get a hold of the `jsdom` instance in `vitest` in order to try that.\n\nAny ideas or alternative approaches welcome, thanks!\n\n========================================\n\nTop Answer:\nSince version 1.3.0, Vitest exposes a `jsdom` global variable, so it should be possible to call\n\n```\njsdom.reconfigure(/* ... */)\n```\n\nSee also https://vitest.dev/config/#environment (scroll to the bottom of the section)\n\n========================================\n\nCode:\n```text\n<script>\n import page from 'page'\n\n import SignIn from './SignIn/SignIn.svelte'\n import Upload from './Upload/Upload.svelte'\n import { authenticationToken } from './Root.stores.js'\n\n let currentPage\n\n page('/', () => {\n page.redirect('/sign-in')\n })\n\n page('/sign-in', () => {\n currentPage = SignIn\n })\n\n page('/upload', () => {\n if ($authenticationToken === null) {\n return page.redirect('/sign-in')\n }\n\n currentPage = Upload\n })\n\n page.start()\n</script>\n\n<svelte:component this={ currentPage } />\n```\n\n```text\nimport page from 'page'\nimport Root from './Root.svelte'\nimport { authenticationToken } from './Root.stores.js'\n\nit('redirects to sign in when not authenticated', async () => {\n vi.spyOn(page, 'redirect')\n authenticationToken.set(null)\n\n const { act } = setupComponent(Root)\n await act(() => page('/upload'))\n\n expect(page.redirect).toHaveBeenCalledWith('/sign-in')\n})\n\nit('displays the upload screen when authenticated', async () => {\n authenticationToken.set('token')\n\n const { act } = setupComponent(Root)\n await act(() => page('/upload'))\n\n expect(document.getElementById('upload')).toBeInTheDocument()\n})\n```\n\n```text\nsvelte\n```\n\n```text\npage.js\n```\n\n```text\nvitest\n```\n\n```text\njsdom\n```\n\n```text\n.only\n```\n\n```text\nscreen.debug()\n```\n\n```text\nact\n```\n\n```text\ntick\n```\n\n```text\njsdom\n```\n\n```text\njest\n```\n\n```text\njsdom.reconfigure()\n```\n\n```text\nbeforeEach\n```\n\n```text\njsdom\n```\n\n```text\nvitest\n```\n\n```js\nimport { JSDOM } from 'jsdom';\nimport { beforeEach } from 'vitest';\n\nbeforeEach(() => {\n const dom = new JSDOM('<html><head></head><body></body></html>', {\n url: 'https://some.url.tld' // Necessary for window.localStorage to work\n });\n\n // @ts-ignore\n global.window = dom.window;\n global.document = dom.window.document;\n global.navigator = dom.window.navigator;\n global.location = dom.window.location;\n global.XMLHttpRequest = dom.window.XMLHttpRequest;\n})\n```\n\n```text\njsdom.reconfigure()\n```\n\n```text\njsdom.reconfigure(/* ... */)\n```\n\n```text\njsdom\n```\n\n========================================\n\nComments:\n- I know this was a little while ago but I would love to know if you ever made any progress? I have a similar / related question over here: stackoverflow.com/q/75795059/2883500 ... I think if I could find a way to reset JSDOM window in between tests without having to move to separate files I'd be good to go.\n- @pooley1994 I couldn't find a solution so I am now using E2E tests for routing. 🤷🏻","metadata":{"transformedAt":"2026-08-18T18:33:40.675Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":238,"estimatedTokens":1265}}234{"id":"stack-59160164","source":"stackoverflow","questionId":59160164,"title":"Using Svelte, how do I populate a tag in with a Javascript string variable?","tags":["svelte","sapper","css-in-js"],"text":"Title: Using Svelte, how do I populate a tag in with a Javascript string variable?\nTags: svelte, sapper, css-in-js\nSource: Stack Overflow\n\nQuestion:\nUsing Svelte, what I want to accomplish is being able to style my `html` using the `css` property of a `post` object I have. \n\nI thought, no problem, just add a style tag to my `svelte:head` with `{post.css}`. It will drop my `post.css` data right into the style tag, and viola’, problem solved. But, no, problem not solved. When I view the element in my browser, I see \n\n`{post.css}` \n\ninstead of \n\n```\n\n p{\n color: purple;\n font-weight: 900;\n }\n \n```\n\nI have created a work around, where I set the `innerText` of the `` tag after `onMount`, but I don’t like it, and would prefer to do it a cleaner way.\n\nWhat I want…\n\n```\n\n export let post = {\n html: `This is purple\n\n`,\n css : `\n p{\n color: purple;\n font-weight: 900;\n }\n `\n } \n\n {post.css}\n\n{@html post.html}\n```\n\nWhat I have to do to make it work…\n\n```\n\n import { onMount } from \"svelte\";\n\n export let post = {\n html: `This is purple\n\n`,\n css : `\n p{\n color: purple;\n font-weight: 900;\n }\n `\n }\n\n onMount(() => {\n let styler = document.getElementById(\"styler\");\n styler.innerText = post.css\n });\n\n \n\n{@html post.html}\n```\n\nIf you have any other alternatives to using the `css` property to style the `html` property of the `post` object, or know how to get Svelte to recognize `{post.css}` in a `` tag, please let me know.\n\n========================================\n\nCode:\n```text\n<style>\n p{\n color: purple;\n font-weight: 900;\n }\n </style>\n```\n\n```text\n<script>\n export let post = {\n html: `<p>This is purple</p>`,\n css : `\n p{\n color: purple;\n font-weight: 900;\n }\n `\n } \n</script>\n\n<svelte:head>\n <style>{post.css}</style>\n</svelte:head>\n\n{@html post.html}\n```\n\n```text\n<script>\n import { onMount } from \"svelte\";\n\n export let post = {\n html: `<p>This is purple</p>`,\n css : `\n p{\n color: purple;\n font-weight: 900;\n }\n `\n }\n\n onMount(() => {\n let styler = document.getElementById(\"styler\");\n styler.innerText = post.css\n });\n</script>\n\n<svelte:head>\n <style id=\"styler\"></style>\n</svelte:head>\n\n{@html post.html}\n```\n\n```text\nhtml\n```\n\n```text\ncss\n```\n\n```text\npost\n```\n\n```text\nsvelte:head\n```\n\n```text\n{post.css}\n```\n\n```text\npost.css\n```\n\n```text\n<style>{post.css}</style>\n```\n\n```text\ninnerText\n```\n\n```text\n<style>\n```\n\n```text\nonMount\n```\n\n```text\ncss\n```\n\n```text\nhtml\n```\n\n```text\npost\n```\n\n```text\n{post.css}\n```\n\n```text\n<style>\n```\n\n```html\n{@html `<style>${post.css}</style>`}\n```\n\n```text\npost.css\n```\n\n========================================\n\nComments:\n- Doesn't seem to work in SvelteKit. I'm getting Error while preprocessing `src/routes/__layout.svelte:1:3`: Unknown word\n- @Casimir If there's a postcss preprocessor in your stack, it can give you the \"Unknown word\" error. In that case, split up the `style` tag into 2 strings like `{@html `${post.css}`}`","metadata":{"transformedAt":"2026-08-18T18:33:40.675Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":207,"estimatedTokens":746}}235{"id":"stack-56393668","source":"stackoverflow","questionId":56393668,"title":"Break iteration (each) in Svelte?","tags":["svelte"],"text":"Title: Break iteration (each) in Svelte?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nIs it possible to break iteration in Svelte or limit like in angular (`ng-repeat=\"items in item | limitTo:4\"`)?\nFor example:\n\n```\n{#each items as item, i}\n ...\n {#if i > 4}\n {:break} <--- break here\n {/if}\n ...\n{/each}\n```\n\n========================================\n\nTop Answer:\nThere is no `{:break}` block, but you could `slice` out the first 4 elements in the array before you iterate over it.\n\n```\n{#each items.slice(0, 4) as item, i} ... {/each}\n```\n\n========================================\n\nCode:\n```text\n{#each items as item, i}\n ...\n {#if i > 4}\n {:break} <--- break here\n {/if}\n ...\n{/each}\n```\n\n```text\nng-repeat=\"items in item | limitTo:4\"\n```\n\n```html\n<script>\n let items = ['a', 'b', 'c', 'd', 'e'];\n $: filteredItems = items.slice(0, 4);\n const filterItems = (i) => i.slice(0, 4);\n</script>\n\n<div>\n {#each {length: 4} as _, i}\n {items[i]}\n {/each}\n</div>\n<div>\n {#each items.slice(0, 4) as item}\n {item}\n {/each}\n</div>\n<div>\n {#each filteredItems as item}\n {item}\n {/each}\n</div>\n<div>\n {#each filterItems(items) as item}\n {item}\n {/each}\n</div>\n```\n\n```text\n{length: N}\n```\n\n```text\n#each\n```\n\n```text\n{#each {length: 4} as _, i} {items[i]} {/each}\n```\n\n```text\n{#each items.slice(0, 4) as item, i} ... {/each}\n```\n\n```text\n{:break}\n```\n\n```text\nslice\n```\n\n```text\n{#each myItems as item}{#if yourtruevalue} {item} {/if} {/each}\n```\n\n```text\nyourtruevalue\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.675Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":104,"estimatedTokens":383}}236{"id":"stack-66960493","source":"stackoverflow","questionId":66960493,"title":"What's the best way to start Svelte app on production server?","tags":["svelte","svelte-3","sveltekit"],"text":"Title: What's the best way to start Svelte app on production server?\nTags: svelte, svelte-3, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm using SvelteKit (1.0.0) with the node adapter.\n\nI want to use it on my server and start it with `pm2`.\n\nWhat's the best way of starting a Svelte app with a node adapter without `npm start`?\n\nI don't need pm2 command, just an npm command for Svelte.\n\n========================================\n\nCode:\n```text\npm2\n```\n\n```text\nnpm start\n```\n\n```text\nnode build/index.js # Start production server\n```\n\n```text\nnpx sv create # Initialize project\nnpm install # Install dependencies\nnpm run build # Build production version\nnode build/index.js # Start production server\n```\n\n========================================\n\nComments:\n- Thank you! I'm getting 2 rows when I run `pm2 start node build/index.js --name Example`. Am I doing something wrong? What script do you recommend?\n- @Ulvi: Sorry, I'm not familiar with `pm2` and I don't know what \"2 rows\" means.\n- Thank you @Leftium! As a JS/Svelte/SvelteKit-beginner I was always wondering, what *\"serving your app\"* after running `npm run build` meant. Your post has shed a lot of light into my head :-).\n- @Ulvi for next runs you just need to type `pm2 start Example` but before that you need to remove your previously duplicates by `pm2 remove Example`.","metadata":{"transformedAt":"2026-08-18T18:33:40.675Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":42,"estimatedTokens":342}}237{"id":"stack-72081698","source":"stackoverflow","questionId":72081698,"title":"How to use get parameter on sveltekit when use adapter-static?","tags":["get","svelte","sveltekit"],"text":"Title: How to use get parameter on sveltekit when use adapter-static?\nTags: get, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI get error message this when build.\n\nCannot access `url.searchParams` on a page with prerendering enabled\n\nHow to load and use get parameter?\n\nsvelte.config.js\n\n```\nimport adapter from '@sveltejs/adapter-static';\nimport preprocess from 'svelte-preprocess';\n\nconst config = {\n preprocess: preprocess({\n }),\n kit: {\n adapter: adapter({\n pages: 'build',\n assets: 'build',\n fallback: null,\n precompress: false\n }),\n prerender: {\n default: true\n },\n trailingSlash: 'always'\n }\n};\n\nexport default config;\n```\n\nqna.svelte\n\n```\n...\nimport {page} from '$app/stores';\nconst id = $page.url.searchParams.get('id');\n...\n```\n\n========================================\n\nTop Answer:\nLet me expand on some other answers: url.searchParams *can* be used with prerended Sveltekit pages, but not on the server side (since their isn't any for prerendered pages)\n\nYou can however use url.searchParams in onMount or in constructs like:\n\n\r\n\r\n\n```\nimport {browser} from \"$app/environment\";\n const searchParams = browser && $page.url.searchParams\n \n if (searchParams && searchParams.get(\"myParam\")) console.log(\"myParam is: \",myParam)\n```\n\n\r\n\r\n\r\n\nNote the imported browser variable which is true if the code is run on the client side in the browser.\n\nFor more details, see https://kit.svelte.dev/docs/page-options#prerender\n\n========================================\n\nCode:\n```text\nimport adapter from '@sveltejs/adapter-static';\nimport preprocess from 'svelte-preprocess';\n\nconst config = {\n preprocess: preprocess({\n }),\n kit: {\n adapter: adapter({\n pages: 'build',\n assets: 'build',\n fallback: null,\n precompress: false\n }),\n prerender: {\n default: true\n },\n trailingSlash: 'always'\n }\n};\n\nexport default config;\n```\n\n```text\n...\nimport {page} from '$app/stores';\nconst id = $page.url.searchParams.get('id');\n...\n```\n\n```text\nurl.searchParams\n```\n\n```html\n<script context=\"module\">\n export const prerender = false;\n</script>\n```\n\n```text\nfallback\n```\n\n```js\nimport {browser} from \"$app/environment\";\n const searchParams = browser && $page.url.searchParams\n \n if (searchParams && searchParams.get(\"myParam\")) console.log(\"myParam is: \",myParam)\n```\n\n```text\n<!-- +page.svelte -->\n<script>\n import { page } from '$app/stores';\n import { onMount } from 'svelte';\n\n let id = '';\n onMount(() => {\n // save the id parameter if it's in the url or an empty string\n id = $page.url.searchParams.get('id') || '';\n });\n</script>\n\n{#if id}\n <h2>The id is {id}.</h2>\n{:else}\n <h2>No id was provided.</h2>\n{/if}\n```\n\n```html\n<script>\n let id = null;\n beforeUpdate(() => {\n id = url.searchParams.get('id');\n });\n</script>\n\n<div>\n <!-- Use `id ` -->\n</div>\n```\n\n```text\nbeforeUpdate\n```\n\n```text\nbeforeUpdate\n```\n\n```text\nonMount\n```\n\n```text\n/page-path?id=1\n```\n\n```text\n/page-path?id=2\n```\n\n```text\nonMount\n```\n\n```text\n?\n```\n\n```text\n/api/posts/get\n```\n\n```text\n/api/posts/[slug]\n```\n\n========================================\n\nComments:\n- This is not true. You can still fetch dynamic content in for instance onMount on a prerendered page. See \"When not to prerender\" under kit.svelte.dev/docs/page-options#prerender\n- yes, you can fetch dynamic content on a prerendered in `onMount`, but this makes this part **not** prerendered.\n- True. But can still be benefitial to combine the too, depending on the page. You can get the best of to world's with shorter load times, SEO etc but also allow some custom content.\n- Good point! Rewrote it to reflect this and made it bit more polite too :-)\n- This is explained in the *When not to prerender* part of the docs.","metadata":{"transformedAt":"2026-08-18T18:33:40.676Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":203,"estimatedTokens":963}}238{"id":"stack-72089474","source":"stackoverflow","questionId":72089474,"title":"How to configure VS Code to run npx vite dev when debugging","tags":["javascript","visual-studio-code","svelte","vscode-debugger"],"text":"Title: How to configure VS Code to run npx vite dev when debugging\nTags: javascript, visual-studio-code, svelte, vscode-debugger\nSource: Stack Overflow\n\nQuestion:\nI am new to VS Code and JavaScript, and I am trying to make a simple app using Vite and Svelte, but I have a problem which I can't seem to resolve. (My code is currently just the default code given when a new project is created; I haven't changed it at all.)\n\nWhen I run my app through Windows Terminal (by navigating to the project root directory and running `npx vite dev`), the app runs fine and my browser can connect to `localhost:3000`.\n\nHowever, when I press on either:\n\n- `Run > Start Debugging`, or\n\n- `Run > Run Without Debugging`\n\nin Visual Studio Code, it opens up Chrome to `localhost:3000` but I just see `localhost refused to connect`. I think VS Code is never actually running the command `npx vite dev`, but I don't know how to change this.\n\nWhen I open up `.vscode/launch.json`, I see this:\n\n```\n{\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"name\": \"Debug with Chrome\",\n \"type\": \"pwa-chrome\",\n \"request\": \"launch\",\n \"url\": \"http://localhost:3000\",\n \"webRoot\": \"${workspaceFolder}\",\n \n }\n ]\n}\n```\n\nAnd I am not sure what I should add here to get this to work. Any help would be appreciated, and sorry if this is a bit of a stupid question, but I couldn't fund any help searching Google or SO.\n\n**EDIT:**\n\nI have almost got this working by adding a `preLaunchTask`, but now chrome no longer automatically opens when I start debugging, so I might as well just run `npm: dev` on its own.\n\nHere is `.vscode/launch.json` now:\n\n```\n{\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"name\": \"Debug with Chrome\",\n \"type\": \"pwa-chrome\",\n \"request\": \"launch\",\n \"url\": \"http://localhost:3000\",\n \"webRoot\": \"${workspaceFolder}\",\n \"preLaunchTask\": \"npm: dev\"\n }\n ]\n}\n```\n\nI think this might be because the `npm: dev` task (which effectively runs `npx vite dev`) is blocking, and only finishes when I press the stop button (or double-click ctrl+c), so chrome is not opened because VS Code thinks the pre-launch task is still running.\n\nIf there any way I can tell VS Code to open Chrome while continuing to run `npm: dev`?\n\n========================================\n\nTop Answer:\nInstead of having it run `npx vite dev` (which is the `npm: dev` task), have it run `npx vite dev --open` :)\n\n========================================\n\nCode:\n```json\n{\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"name\": \"Debug with Chrome\",\n \"type\": \"pwa-chrome\",\n \"request\": \"launch\",\n \"url\": \"http://localhost:3000\",\n \"webRoot\": \"${workspaceFolder}\",\n \n }\n ]\n}\n```\n\n```json\n{\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"name\": \"Debug with Chrome\",\n \"type\": \"pwa-chrome\",\n \"request\": \"launch\",\n \"url\": \"http://localhost:3000\",\n \"webRoot\": \"${workspaceFolder}\",\n \"preLaunchTask\": \"npm: dev\"\n }\n ]\n}\n```\n\n```text\nnpx vite dev\n```\n\n```text\nlocalhost:3000\n```\n\n```text\nRun > Start Debugging\n```\n\n```text\nRun > Run Without Debugging\n```\n\n```text\nlocalhost:3000\n```\n\n```text\nlocalhost refused to connect\n```\n\n```text\nnpx vite dev\n```\n\n```text\n.vscode/launch.json\n```\n\n```text\npreLaunchTask\n```\n\n```text\nnpm: dev\n```\n\n```text\n.vscode/launch.json\n```\n\n```text\nnpm: dev\n```\n\n```text\nnpx vite dev\n```\n\n```text\nnpm: dev\n```\n\n```json\n// launch.json\n{\n // Use IntelliSense to learn about possible attributes.\n // Hover to view descriptions of existing attributes.\n // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"name\": \"Launch Vite DEV server\",\n \"request\": \"launch\",\n \"runtimeExecutable\": \"npx\",\n \"runtimeArgs\": [\n \"vite\"\n ],\n \"type\": \"node\",\n \"serverReadyAction\": {\n \"action\": \"debugWithChrome\",\n \"killOnServerStop\": true,\n \"pattern\": \"Local: http://localhost:([0-9]+)/\",\n \"uriFormat\": \"http://localhost:%s\"\n }\n }\n ]\n}\n```\n\n```text\nnpx vite dev\n```\n\n```text\nnpm: dev\n```\n\n```text\nnpx vite dev --open\n```\n\n```text\n{\n // Use IntelliSense to learn about possible attributes.\n // Hover to view descriptions of existing attributes.\n // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"type\": \"chrome\",\n \"request\": \"launch\",\n \"name\": \"Launch Chrome\",\n \"url\": \"http://localhost:5173\",\n \"webRoot\": \"${workspaceFolder}\",\n \"sourceMaps\": true,\n \"resolveSourceMapLocations\": [\n \"${workspaceFolder}/**\",\n \"!**/node_modules/**\"\n ],\n },\n ]\n}\n```\n\n```text\n\"dev\": \"vite --host --open\",\n```\n\n```text\nsudo firewall-cmd --permanent --add-port=5173/tcp\n```\n\n```text\nsudo shutdown -r now\n```\n\n```text\nyarn dev\n```\n\n```text\nvscode\n```\n\n```json\n\"env\": {\n \"NO_COLOR\": \"1\"\n},\n```\n\n========================================\n\nComments:\n- Are you using SvelteKit or plain svelte?\n- @JudahB. Plain Svelte\n- Have you tried running `npm dev --open`? I'm not 100% percent sure if this will work since I've only used SvelteKit, but it's worth a try.\n- Note: It should be `npx vite dev --open` not `npm dev --open`.\n- @Lecdi Noted :)\n- ⚠ If the output is colored, the color escape codes will affect your pattern. For vite, I'm using `\"pattern\": \"127\\\\.0\\\\.0\\\\.1:.*m([0-9]+)\",` (escape the periods properly, and then skip the `ESC[123m` style color codes, then group match the port)\n- Thanks @nathan for the tip about ANSI colour escape codes - I had struggled for hours. For some reason I had to remove the \\\\ escape characters from the regex to make it work: `\"pattern\": \"127.0.0.1:.*m([0-9]+)\"` This on VS Code v1.74\n- It doesn't start Chrome for me. I am running Vite 4.x. (React with Typescritp)\n- it does run the browser for me after changing to `\"pattern\": \"http://127.0.0.1:.*m([0-9]+)\", \"uriFormat\": \"http://127.0.0.1:%s\"`.\n- In my case (Vite 4.2 and VSCode 1.78) it worked with this config: `json \"pattern\": \"Local: http://localhost:([0-9]+)/\", \"uriFormat\": \"http://localhost:%s\",`\n- And for me it was the multiple spaces breaking it, so had to do `Local: *http://localhost:([0-9]+)`. Not the most stable pattern, it seems. :P\n- For Vite v6.0.7 I got it working with `\"pattern\": \"localhost:.*m([0-9]+)\", \"uriFormat\": \"http://localhost:%s\"` to work with colored output","metadata":{"transformedAt":"2026-08-18T18:33:40.676Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":262,"estimatedTokens":1631}}239{"id":"stack-72841684","source":"stackoverflow","questionId":72841684,"title":"Svelte/Typescript error : \"unexpected token\" during type declaration","tags":["node.js","typescript","npm","svelte"],"text":"Title: Svelte/Typescript error : \"unexpected token\" during type declaration\nTags: node.js, typescript, npm, svelte\nSource: Stack Overflow\n\nQuestion:\nSo I have a `Svelte` application with TypeScript enabled but now I am having an issue for running it :\n\n```\n[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)\nsrc\\api.ts (4:7)\n2:\n3: export default class API {\n4: url:string;\n ^\n5:\n```\n\nI don't understand because the app was working before, and suddenly raised this error.\nIt seems that some versions related to TypeScript for Svelte was changed:\n\n```\n{\n \"name\": \"...\",\n \"version\": \"...\",\n \"private\": ...,\n \"scripts\": {\n \"build\": \"rollup -c\",\n \"dev\": \"rollup -c -w\",\n \"start\": \"sirv public --no-clear\",\n \"validate\": \"svelte-check\",\n \"check\": \"svelte-check --tsconfig ./tsconfig.json\" /* + ADDED */\n },\n \"devDependencies\": {\n \"@rollup/plugin-commonjs\": \"...\",\n \"@rollup/plugin-json\": \"...\",\n \"@rollup/plugin-node-resolve\": \"^13.1.3\",\n \"@rollup/plugin-typescript\": \"^8.0.0\",\n /* @smui/... stuffs */\n \"@tsconfig/svelte\": \"^2.0.0\", /* ^1.0.0 -> ^2.0.0 */\n \"rollup\": \"^2.67.0\",\n \"rollup-plugin-css-only\": \"^3.1.0\",\n \"rollup-plugin-livereload\": \"^2.0.5\",\n \"rollup-plugin-svelte\": \"^7.1.0\",\n \"rollup-plugin-terser\": \"^7.0.2\",\n \"svelte\": \"^3.46.3\",\n \"svelte-check\": \"^2.0.0\", /* ^1.0.0 -> ^2.0.0 */\n \"svelte-preprocess\": \"^4.0.0\",\n \"tslib\": \"^2.0.0\",\n \"typescript\": \"^4.0.0\"\n },\n \"dependencies\": {\n \"sirv-cli\": \"^2.0.2\",\n \"svelte-material-ui\": \"...\"\n }\n}\n/* Note: I replaced some unrelated properties/version by '...'. */\n```\n\nOf course executing `npm install` didn't help. And if I just remove the `:string`, it will throw the same error for all other `:` in the code.\n\nNote that the file is named `.ts` and that VSCode doesn't detect any syntax error in those files.\n\n### Config files (edit)\n\n```\n/* tsconfig.json */\n{\n \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n\n \"include\": [\"src/**/*\"],\n \"exclude\": [\"node_modules/*\", \"__sapper__/*\", \"public/*\"]\n}\n```\n\n```\n/* rollup.config.js */\nimport svelte from 'rollup-plugin-svelte';\nimport commonjs from '@rollup/plugin-commonjs';\nimport json from '@rollup/plugin-json';\nimport resolve from '@rollup/plugin-node-resolve';\nimport livereload from 'rollup-plugin-livereload';\nimport { terser } from 'rollup-plugin-terser';\nimport sveltePreprocess from 'svelte-preprocess';\nimport typescript from '@rollup/plugin-typescript';\nimport css from 'rollup-plugin-css-only';\n\nconst production = !process.env.ROLLUP_WATCH;\n\nfunction serve() {\n let server;\n\n function toExit() {\n if (server) server.kill(0);\n }\n\n return {\n writeBundle() {\n if (server) return;\n server = require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {\n stdio: ['ignore', 'inherit', 'inherit'],\n shell: true\n });\n\n process.on('SIGTERM', toExit);\n process.on('exit', toExit);\n }\n };\n}\n\nexport default {\n input: 'src/main.ts',\n output: {\n sourcemap: true,\n format: 'iife',\n name: 'app',\n file: 'public/build/bundle.js'\n },\n plugins: [\n svelte({\n preprocess: sveltePreprocess({ sourceMap: !production }),\n compilerOptions: {\n dev: !production\n }\n }),\n css({ output: 'bundle.css' }),\n resolve({\n browser: true,\n dedupe: ['svelte']\n }),\n commonjs(),\n typescript({\n sourceMap: !production,\n inlineSources: !production\n }),\n json(),\n !production && serve(),\n !production && livereload('public'),\n production && terser()\n ],\n watch: {\n clearScreen: false\n }\n};\n```\n\nNo file `svelte.config.js`\n\n========================================\n\nTop Answer:\nHaving setup my project from the latest svelte template with Typescript enabled, faced a similar \"unexpected token\" complaint when trying to import types into .svelte files, not in the code editor but the server.\n\nFix was to explicitly set the preprocess option in svelte.config.js to `vitePreprocess()`.\nThis was unexpected since the svelte docs (currently) state that this is included by default if Typescript is enabled during setup!\nhttps://kit.svelte.dev/docs/integrations#preprocessors\n\n```\nimport { vitePreprocess } from '@sveltejs/kit/vite';\n \nexport default {\n preprocess: [vitePreprocess()]\n};\n```\n\n========================================\n\nCode:\n```text\n[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)\nsrc\\api.ts (4:7)\n2:\n3: export default class API {\n4: url:string;\n ^\n5:\n```\n\n```json\n{\n \"name\": \"...\",\n \"version\": \"...\",\n \"private\": ...,\n \"scripts\": {\n \"build\": \"rollup -c\",\n \"dev\": \"rollup -c -w\",\n \"start\": \"sirv public --no-clear\",\n \"validate\": \"svelte-check\",\n \"check\": \"svelte-check --tsconfig ./tsconfig.json\" /* + ADDED */\n },\n \"devDependencies\": {\n \"@rollup/plugin-commonjs\": \"...\",\n \"@rollup/plugin-json\": \"...\",\n \"@rollup/plugin-node-resolve\": \"^13.1.3\",\n \"@rollup/plugin-typescript\": \"^8.0.0\",\n /* @smui/... stuffs */\n \"@tsconfig/svelte\": \"^2.0.0\", /* ^1.0.0 -> ^2.0.0 */\n \"rollup\": \"^2.67.0\",\n \"rollup-plugin-css-only\": \"^3.1.0\",\n \"rollup-plugin-livereload\": \"^2.0.5\",\n \"rollup-plugin-svelte\": \"^7.1.0\",\n \"rollup-plugin-terser\": \"^7.0.2\",\n \"svelte\": \"^3.46.3\",\n \"svelte-check\": \"^2.0.0\", /* ^1.0.0 -> ^2.0.0 */\n \"svelte-preprocess\": \"^4.0.0\",\n \"tslib\": \"^2.0.0\",\n \"typescript\": \"^4.0.0\"\n },\n \"dependencies\": {\n \"sirv-cli\": \"^2.0.2\",\n \"svelte-material-ui\": \"...\"\n }\n}\n/* Note: I replaced some unrelated properties/version by '...'. */\n```\n\n```json\n/* tsconfig.json */\n{\n \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n\n \"include\": [\"src/**/*\"],\n \"exclude\": [\"node_modules/*\", \"__sapper__/*\", \"public/*\"]\n}\n```\n\n```js\n/* rollup.config.js */\nimport svelte from 'rollup-plugin-svelte';\nimport commonjs from '@rollup/plugin-commonjs';\nimport json from '@rollup/plugin-json';\nimport resolve from '@rollup/plugin-node-resolve';\nimport livereload from 'rollup-plugin-livereload';\nimport { terser } from 'rollup-plugin-terser';\nimport sveltePreprocess from 'svelte-preprocess';\nimport typescript from '@rollup/plugin-typescript';\nimport css from 'rollup-plugin-css-only';\n\nconst production = !process.env.ROLLUP_WATCH;\n\nfunction serve() {\n let server;\n\n function toExit() {\n if (server) server.kill(0);\n }\n\n return {\n writeBundle() {\n if (server) return;\n server = require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {\n stdio: ['ignore', 'inherit', 'inherit'],\n shell: true\n });\n\n process.on('SIGTERM', toExit);\n process.on('exit', toExit);\n }\n };\n}\n\nexport default {\n input: 'src/main.ts',\n output: {\n sourcemap: true,\n format: 'iife',\n name: 'app',\n file: 'public/build/bundle.js'\n },\n plugins: [\n svelte({\n preprocess: sveltePreprocess({ sourceMap: !production }),\n compilerOptions: {\n dev: !production\n }\n }),\n css({ output: 'bundle.css' }),\n resolve({\n browser: true,\n dedupe: ['svelte']\n }),\n commonjs(),\n typescript({\n sourceMap: !production,\n inlineSources: !production\n }),\n json(),\n !production && serve(),\n !production && livereload('public'),\n production && terser()\n ],\n watch: {\n clearScreen: false\n }\n};\n```\n\n```text\nSvelte\n```\n\n```text\nnpm install\n```\n\n```text\n:string\n```\n\n```text\n:<type>\n```\n\n```text\n.ts\n```\n\n```text\nsvelte.config.js\n```\n\n```text\n[!] Error: Could not resolve './api.js' from src/App.js`\n```\n\n```js\n/* Before (not working) */\nimport API from './api.js'\n/* After (Good) */\nimport API from './API' \n\n// NB. The filename is really in uppercase for me\n```\n\n```text\n./api.js\n```\n\n```text\n./API.ts\n```\n\n```text\nimport x from file.js\n```\n\n```text\nimport x from file\n```\n\n```text\n.ts\n```\n\n```text\n.js\n```\n\n```text\n.ts\n```\n\n```text\n.ts\n```\n\n```text\nimport { vitePreprocess } from '@sveltejs/kit/vite';\n \nexport default {\n preprocess: [vitePreprocess()]\n};\n```\n\n```text\nvitePreprocess()\n```\n\n```text\n<script>\n...\n</script>\n```\n\n```text\n<script lang=\"ts\">\n...\n</script>\n```\n\n```text\nlang\n```\n\n```text\n<script>\n```\n\n```text\n\"ts\"\n```\n\n```json\n{\n \"env\": {\n \"browser\": true,\n \"node\": true,\n \"es2021\": true\n },\n \"globals\": {\n ...\n },\n \"extends\": [\n \"standard\",\n \"plugin:svelte/recommended\",\n \"plugin:@typescript-eslint/recommended\"\n ],\n \"parser\": \"@typescript-eslint/parser\", // <-- you might say typescript here\n \"parserOptions\": {\n \"sourceType\": \"module\",\n \"extraFileExtensions\": [\".svelte\"]\n },\n \"plugins\": [\"@typescript-eslint\"],\n \"overrides\": [\n {\n \"files\": [\"*.svelte\"],\n \"parser\": \"svelte-eslint-parser\",\n \"parserOptions\": {\n \"parser\": \"@typescript-eslint/parser\" // <-- you HAVE TO say typescript here again\n }\n }\n ]\n }\n```\n\n```text\noverrides: [\n {\n files: ['*.svelte'],\n parser: 'svelte-eslint-parser',\n parserOptions: {\n parser: {\n // Specify a parser for each lang.\n ts: '@typescript-eslint/parser',\n js: 'espree',\n typescript: '@typescript-eslint/parser'\n }\n }\n }\n ],\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nvite.config.js\n```\n\n========================================\n\nComments:\n- seems like you need to add a plugin to import typescript files. This article could be useful. Looks like your question may have also been answered here\n- Show your other config files, in particular Rollup's, any `tsconfig.json` and the `svelte.config.js`, if there is one.\n- Thank you Ross and H.B. for your comments. @Ross, unfortunately I already followed this path and it didn't help. :(\n- Important to make sure it's `lang`, not `type` or anything else. They look very similar, but `type` doesn't work here.\n- Thanks @u32i64! I copied an error page template from SO and the tag was `type`. When viewing the file it looked correct and svelte marked the variable declaration as problematic, not the tag.","metadata":{"transformedAt":"2026-08-18T18:33:40.676Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":467,"estimatedTokens":2505}}240{"id":"stack-64799008","source":"stackoverflow","questionId":64799008,"title":"Make AJAX Request from Store","tags":["svelte","svelte-store"],"text":"Title: Make AJAX Request from Store\nTags: svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI have 3 questions regarding Svelte Stores:\n\n- How do I make ajax request inside a store? I've tried using the following:\n\n### REPL Demo\n\n```\n//store.js\n\nimport { writable } from 'svelte/store';\n\nlet data = [];\n\nconst apiURL = \"https://jsonplaceholder.typicode.com/todos\";\n\nasync function getData(){\n const response = await fetch(apiURL);\n data = (await response.json()).slice(0,20);\n console.log('Response:', data);\n}\ngetData();\n\nexport const testsStore = writable(data);\n```\n\nThe request goes trough but the data never gets passed to the export. All the examples I've seen use static data without async/await. I've also tried `return data;` and `writable(getData());` but it return a promise and not the data itself.\n\nIs this even the right way of loading data from API into a store or should I make the call somewhere else.\n\nHow and when do I use `export default testsStore;` I tried using it from another example and it throws saying that `store.js isn't exporting testsStore`\n\n========================================\n\nCode:\n```text\n//store.js\n\nimport { writable } from 'svelte/store';\n\nlet data = [];\n\nconst apiURL = \"https://jsonplaceholder.typicode.com/todos\";\n\nasync function getData(){\n const response = await fetch(apiURL);\n data = (await response.json()).slice(0,20);\n console.log('Response:', data);\n}\ngetData();\n\nexport const testsStore = writable(data);\n```\n\n```text\nreturn data;\n```\n\n```text\nwritable(getData());\n```\n\n```text\nexport default testsStore;\n```\n\n```text\nstore.js isn't exporting testsStore\n```\n\n```js\nimport { writable } from 'svelte/store';\n\nconst apiURL = \"https://jsonplaceholder.typicode.com/todos\";\n\nasync function getData(){\n const response = await fetch(apiURL);\n const data = (await response.json()).slice(0,20);\n testStore.set(data) // <================================\n}\ngetData();\n\nexport const testStore = writable([])\n```\n\n```js\nimport { readable } from 'svelte/store';\n\nconst apiURL = \"https://jsonplaceholder.typicode.com/todos\";\n\nconst getData = async () => {\n const res = await fetch(apiURL)\n if (!res.ok) throw new Error('Bad response')\n const items = await res.json()\n return items.slice(0, 20)\n}\n\nexport const todos = readable([], set => {\n // called when the store is first subscribed (when subscribers goes from 0 to 1)\n getData()\n .then(set)\n .catch(err => {\n console.error('Failed to fetch', err)\n })\n return () => {\n // you can do cleanup here if needed\n }\n})\n```\n\n```html\n<script>\n import { todos } from './store.js';\n</script>\n\n<h1>Todos:</h1>\n\n{#each $todos as item} \n <p>{item.title}</p>\n{/each}\n```\n\n```text\nset\n```\n\n```text\nupdate\n```\n\n```text\nset\n```\n\n```text\nset\n```\n\n```text\nupdate\n```\n\n```text\n.svelte\n```\n\n```text\n$\n```\n\n```text\ntodos\n```\n\n========================================\n\nComments:\n- Great that works. Thanks for the explanation. Also found out that you can handle the promise by wrapping it into `{#await}` block in the .svelte file. See this example\n- While you can have a store return a promise and use {#await}, you might find this to get a little tedious vs. resolving the promise then setting the readable store's value as rixo suggested in this answer.\n- Thank you for the concise explanation of async store setup. The problem I was having was completely resolved using your post as a ***direct*** template!","metadata":{"transformedAt":"2026-08-18T18:33:40.676Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":164,"estimatedTokens":868}}241{"id":"stack-62647804","source":"stackoverflow","questionId":62647804,"title":"Environment variables in svelte + rollup","tags":["javascript","environment","svelte","rollup"],"text":"Title: Environment variables in svelte + rollup\nTags: javascript, environment, svelte, rollup\nSource: Stack Overflow\n\nQuestion:\nI'm looking for a straightforward way to set up environments. I.E. It would be great if I could run `npm run dev:local` and `npm run dev:staging` which load different environment files which are accessible at runtime via `process.env`. In understand it's compiled so I may have to access the variables in a different way. I'm using svelte with rollup straight from sveltejs/template. It should be simple but I see no way of doing it. It's cumbersome, but possible to do with webpack. Is there a simple way to do this?\n\n========================================\n\nCode:\n```text\nnpm run dev:local\n```\n\n```text\nnpm run dev:staging\n```\n\n```text\nprocess.env\n```\n\n```js\nimport replace from '@rollup/plugin-replace'\n...\n\nconst production = !process.env.ROLLUP_WATCH\n\nexport default {\n ...\n plugins: [\n replace({\n 'process.env': production ? '\"production\"' : '\"dev\"',\n }),\n ...\n ]\n}\n```\n\n```text\nrollup.config.js\n```\n\n```text\n'\"production\"'\n```\n\n========================================\n\nComments:\n- Does dotenv help? You can also set env vars in the npm scripts themselves.\n- No, I don't understand why but .env only allows one environment file.","metadata":{"transformedAt":"2026-08-18T18:33:40.676Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":52,"estimatedTokens":321}}242{"id":"stack-69124800","source":"stackoverflow","questionId":69124800,"title":"SvelteKit: Disable internal link routing for certain links served from the same host","tags":["svelte","sveltekit"],"text":"Title: SvelteKit: Disable internal link routing for certain links served from the same host\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a link in a Svelte component. The destination of this link is handled by a reserve proxy server, thus the link destination is not part of a Svelte application, even though it shares the same URL path with the Svelte application.\n\nIf I click the link Svelte tries to resolve the link with its internal router. How can I force the link in Svelte to be loaded by the web browser and skipped by the internal router?\n\nMy link code is:\n\n```\n\nDocumentation\n```\n\n========================================\n\nCode:\n```html\n<!-- /docs/ is served from the reverse proxy by the web server and not part of Svelte -->\n<a href=\"https://tradingstrategy.ai/docs/index.html\">Documentation</a>\n```\n\n```html\n<a rel=\"external\" href=\"https://tradingstrategy.ai/docs/index.html\">Documentation</a>\n```\n\n```text\nrel=\"external\"\n```\n\n========================================\n\nComments:\n- As the linked documentation states you should use `data-sveltekit-reload` instead. `rel=\"external\"` has a semantic meaning and shouldn’t be used for internal links unless you have a specific reason.\n- @bfontaine The linked documentation specifies \"Links with a `rel=\"external\"` attribute will receive the same treatment [talking about triggering a full-page navigation]. In addition, they will be ignored during prerendering.\" As I read it, that means to avoid the issue OP describes, you need the rel=external.\n- @Plagiatus No, it means that to avoid the issue OP describes, you can use *either* `rel=\"external\"` *either* `data-sveltekit-reload`. However the first has a semantic meaning (by clicking on this link you go out of this website), so unless you have a good reason to use `rel=\"external\"`, you should use `data-sveltekit-reload`.\n- @bfontaine I disagree: something using a page reload and something not getting handled by svelte themselves are not the same thing. Sounds to me like OP needs to let the link be handled by the webserver, not svelte, hence they need `rel=\"external\"`. I agree about the issue with the semantic meaning, however it won't work in svelte without that.\n- @Plagiatus There’s a misunderstanding here: if you use `data-sveltekit-reload` it has exactly the same effect in Svelte as if you used `rel=\"external\"`.\n- @bfontaine except I tested it and it doesn't. If you e.g. use `adapter-static`, it tries to pre-render everything it can find an seemingly internal link to and fails if there is nothing there (e.g. because you have the file handled through a proxy server like OP does, not through svelte). `data-sveltekit-reload` does NOT help with this issue, but `rel=\"external\"` does, as it excludes the link from prerendering, which `data-sveltekit-reload` does not.\n- @Plagiatus The question is about routing, not pre-rendering.","metadata":{"transformedAt":"2026-08-18T18:33:40.676Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":42,"estimatedTokens":720}}243{"id":"stack-74974180","source":"stackoverflow","questionId":74974180,"title":"How to define CSS fields based on props in a Svelte component?","tags":["javascript","svelte","sveltekit"],"text":"Title: How to define CSS fields based on props in a Svelte component?\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI new to Svelte and interesting to conditional styling based on props. I have two Svelte components - `Parent` and `Child`, just for understanding.\n\nThe parent passes props to child - the `pt` property which should be the `padding-top` field of child's css. The `Parent` code looks like:\n\n```\n\n import Child from \"./Child.svelte\";\n\n```\n\nThe Child component has two styles: `padding-top` and `padding-bottom`. Depending on what props are passed, the corresponding fields of styles are created. If no props is passed, then the component will have no styles. In the following example, we passed only the `pt` props which activates `padding-top` field:\n\n```\n\n export let pb, pt;\n let styles = \"\";\n if (pt) styles += \"--pt:\" + pt;\n if (pb) styles += \"--pb:\" + pb;\n\n \n\n### Hello\n\n .child {\n padding-top: var(--pt);\n padding-bottom: var(--pb);\n }\n\n```\n\nEverything works, but is this the right way? Or is there a more effective implementation of this task?\nThanks for attension.\n\n========================================\n\nTop Answer:\n```\n\n export let pb, pt;\n\n \n\n### Hello\n\n```\n\nMore info:\n\n- How to use Svelte's style directive\n\n- Svelte docs: style:property\n\n========================================\n\nCode:\n```text\n<script>\n import Child from \"./Child.svelte\";\n</script>\n\n<Child pt=\"45px\" />\n```\n\n```text\n<script>\n export let pb, pt;\n let styles = \"\";\n if (pt) styles += \"--pt:\" + pt;\n if (pb) styles += \"--pb:\" + pb;\n</script>\n\n<div class=\"child\" style={styles}>\n <h3>Hello</h3>\n</div>\n\n<style>\n .child {\n padding-top: var(--pt);\n padding-bottom: var(--pb);\n }\n</style>\n```\n\n```text\nParent\n```\n\n```text\nChild\n```\n\n```text\npt\n```\n\n```text\npadding-top\n```\n\n```text\nParent\n```\n\n```text\npadding-top\n```\n\n```text\npadding-bottom\n```\n\n```text\npt\n```\n\n```text\npadding-top\n```\n\n```html\n<Child --pt=\"45px\" />\n```\n\n```text\nvar(--pt)\n```\n\n```text\n45px\n```\n\n```html\n<script>\n export let style = '';\n let className = '';\n export { className as class }; // Necessary because `class` is a keyword\n</script>\n\n<div class={className} {style}>\n ...\n</div>\n```\n\n```html\n<Child class=\"pt32\" />\n```\n\n```text\n''\n```\n\n```text\n<script>\n export let pb, pt;\n</script>\n\n<div class=\"child\" style:padding-top={pt} style:padding-bottom={pb}>\n <h3>Hello</h3>\n</div>\n```\n\n========================================\n\nComments:\n- (This also creates a wrapper element which can mess up layout.)\n- True, but caniuse.com/css-display-contents support is quite good (as long as you don't use IE11 )\n- (This disables svelte's detection to see which classes written in the block are unused)\n- True, there are always some trade-offs 😅","metadata":{"transformedAt":"2026-08-18T18:33:40.676Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":173,"estimatedTokens":688}}244{"id":"stack-49228098","source":"stackoverflow","questionId":49228098,"title":"Close modal popup while clicking outside of popup in Svelte","tags":["svelte"],"text":"Title: Close modal popup while clicking outside of popup in Svelte\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI have the popup modal in one of my app. I would like to close this popup while clicking outside of modal. I can achieve this behaviour using JavaScript but I can't quite find a way to make this work using Svelte framework. For now I'm achieving that behaviour like this\n\n```\nif (e.target.classList.contains('my-modal')){\n e.target.style.display=\"none\";\n}\n```\n\nbut I would like to have this worked using Svelte.\n\n========================================\n\nTop Answer:\nFor anyone reading this in 2023 or later, the syntax has been updated to `` instead of ``.\n\n```\n\n```\n\n========================================\n\nCode:\n```js\nif (e.target.classList.contains('my-modal')){\n e.target.style.display=\"none\";\n}\n```\n\n```html\n<:Window on:click='set({ message: \"clicked outside the box\" })'/>\n\n<div class='clickzone' on:click='event.stopPropagation()'>\n <div class='inner' on:click='set({ message: \"clicked inside the box\" })'>\n {{message}}\n </div>\n</div>\n```\n\n```text\n<:Window>\n```\n\n```text\non:outclick\n```\n\n```text\n<div class=\"modal\" tabindex=\"-1\" on:click={ () => send('CLOSE') }>\n```\n\n```text\n<script>\n export let open = false;\n export let onClosed;\n\n const modalClose = () => {\n open = false;\n if (onClosed) {\n onClosed();\n }\n }\n</script>\n\n{#if open}\n <div class=\"modal\" on:click={modalClose} >\n ...\n```\n\n```text\n<div class=\"modal-footer\">\n <button type=\"button\" class=\"btn btn-secondary\" on:click={modalClose}>\n Close\n </button>\n <button type=\"button\" class=\"btn btn-primary\" on:click|stopPropagation={yourSaveLogic()}>\n Save changes\n </button>\n</div>\n```\n\n```text\nstopPropagation\n```\n\n```text\non:click\n```\n\n```text\non:click|stopPropagation\n```\n\n```html\n<svelte:window on:click='set({ message: \"clicked outside the box\" })' />\n```\n\n```text\n<svelte:window />\n```\n\n```text\n<:window />\n```\n\n========================================\n\nComments:\n- You can also use `on:click|stopPropagation` for a shorter syntax\n- My working code looks like: hide()}>","metadata":{"transformedAt":"2026-08-18T18:33:40.676Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":113,"estimatedTokens":523}}245{"id":"stack-58877067","source":"stackoverflow","questionId":58877067,"title":"Svelte: Remount component to overwrite media elements","tags":["video","html5-video","svelte","svelte-component","svelte-3"],"text":"Title: Svelte: Remount component to overwrite media elements\nTags: video, html5-video, svelte, svelte-component, svelte-3\nSource: Stack Overflow\n\nQuestion:\n- Context\n\nIn my Svelte app, I have multiple pages, each showing one or multiple videos.\nFor rendering the videos I reuse a **video component** (simplified):\n\n```\n// video component\n\n \n\n```\n\nThe **main page** receives the video content via an api and calls the video component:\n\n```\n// calling video component on main page\n\n let source = {\n thumb: 'thumb.jpg',\n source: 'video.mp4',\n mime: 'video/mp4',\n };\n\n```\n\n**All works fine**, the video is rendered and can be played.\n\n- Problem\n\n**But:** when I navigate or want to replace a video with another, the old video element somehow still exists and playback continues.\n\nI could use `beforeUpdate()` to pause the video. But then, the new video weirdly is loaded at the exact same playback time and everything gets mixed up. Or if I remove the video element in `beforeUpdate()`, it doesn't get filled with the new information.\n\nIt kinda makes sense, because the `video` media element stays the exact same thing while only attributes and content change. Thus the state and already buffered source remains.\n\n**I somehow would need to assure, that when the data changes, the video component must completely be remounted.**\nDoes anyone know how to do that? Thanks!\n\n========================================\n\nTop Answer:\nTo trigger a rerender of the video when the source changes, a {#key} block could be used REPL\n\n```\n\n export let source;\n\n{#key source}\n\n \n\n{/key}\n```\n\n========================================\n\nCode:\n```js\n// video component\n<video poster=\"{source.thumb}\">\n <source type=\"{source.mime}\" src=\"{source.source}\" >\n</video>\n```\n\n```text\n// calling video component on main page\n<script>\n let source = {\n thumb: 'thumb.jpg',\n source: 'video.mp4',\n mime: 'video/mp4',\n };\n</script>\n<Video source={source} />\n```\n\n```text\nbeforeUpdate()\n```\n\n```text\nbeforeUpdate()\n```\n\n```text\nvideo\n```\n\n```js\n<script>\n export let source;\n\n let renderVideo = true;\n\n $: { reMountVideo( source.source ) }\n function reMountVideo(){\n renderVideo = false;\n setTimeout(() => renderVideo = true, 0);\n }\n</script>\n{#if renderVideo === true}\n <video poster=\"{source.thumb}\">\n <source type=\"{source.mime}\" src=\"{source.source}\" >\n </video>\n{/if}\n```\n\n```text\nreMountVideo()\n```\n\n```text\nlet video = true:\nfunction reMountVideo() {\n video = false; \n setTimeout(() => video = true, 0);\n} \n\n{#if video }\n <Video source={source} />\n{/if}\n```\n\n```text\n<input type=\"file\" ....>\n```\n\n```js\n<script>\n let src = ...\n function load(node, src){\n if(src){\n node.src = src;\n node.load();\n } \n return {\n update(src){\n if(src){\n node.src = src;\n node.load();\n }\n }\n }\n }\n</script>\n\n<video use:load={src}>\n```\n\n```text\nvideo\n```\n\n```text\nsrc\n```\n\n```text\n<script>\n export let source;\n</script>\n\n{#key source}\n<video poster=\"{source.thumb}\" controls>\n <source type=\"{source.mime}\" src=\"{source.source}\" >\n</video>\n{/key}\n```\n\n========================================\n\nComments:\n- it's counterintuitive to me that the old playback would still be in effect when the *source* changes. The snippet shown here is not reactive, how does the new source loading happens?\n- Every on-site link triggers a function that loads data from an API to render a new page, also including videos. I just replace the data object and all content updates as expected. Unless videos, the stay the same as long as the new page also features a video.\n- Ok, I understand. Generally, svelte does not arbitrarily duplicate elements, hence my question. The script shown here does not replace the data however, and that data replacement is probably important in solving the problem. Can you add the code to your question? Otherwise, maybe use the inspector to see what actually happens in the elements. If the video elements are duplicated, it would be a clue as to what happens.\n- why use the setTimeout instead of reassigning true directly?\n- To queue the true after the render.\n- Where do I call `reMountVideo()`? If I call it from a `beforeUpdate()` or `afterUpdate()`, it creates an infinite loop.\n- You call it only when you replace one video for another or after you have finished a video. So not all the time.","metadata":{"transformedAt":"2026-08-18T18:33:40.676Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":184,"estimatedTokens":1122}}246{"id":"stack-75315280","source":"stackoverflow","questionId":75315280,"title":"How to upload files - Sveltekit","tags":["svelte","sveltekit"],"text":"Title: How to upload files - Sveltekit\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\n+page.svelte\n\n```\n\n```\n\n+page.server.js\n\n```\nexport const actions = {\n upload: async ({ cookies, request, locals }) => {\n const data = await request.formData();\n\n //HOW CAN I GET and save the file locally with writeFileSync?\n\n return { success: true };\n }\n};\n```\n\nI haven't found a way to handle file uploads in sveltkit. Any ideas? The file is small.. so there is no problem in loading to memory.\n\n========================================\n\nCode:\n```text\n<form\n action=\"?/upload\"\n method=\"post\"\n enctype=\"multipart/form-data\"\n >\n<input\n type=\"file\"\n name=\"file\"\n id=\"file\"\n accept=\"application/pdf\"\n />\n```\n\n```js\nexport const actions = {\n upload: async ({ cookies, request, locals }) => {\n const data = await request.formData();\n\n //HOW CAN I GET and save the file locally with writeFileSync?\n\n return { success: true };\n }\n};\n```\n\n```js\n// would recommend using these async functions\nimport { writeFile } from 'fs/promises';\n\n//...\n\nconst file = data.get('file'); // value of 'name' attribute of input\n\nawait writeFile(`./files/${file.name}`, await file.text());\n// or\nawait writeFile(`./files/${file.name}`, file.stream());\n// or\nawait writeFile(`./files/${file.name}`, new Uint8Array(await file.arrayBuffer()));\n```\n\n```text\nFile\n```\n\n```text\ntext()\n```\n\n```text\nstream()\n```\n\n```text\narrayBuffer()\n```\n\n========================================\n\nComments:\n- Thanks! That what I was looking for... do you know any link where I can learn more?\n- The file API is a web standard, the linked MDN documentation should explain its properties, methods and the various related classes. I just read through that or search StackOverflow if there is a specific use case that might be common enough.\n- typescript support: `const file = data.get('file') as File;`. Furthermore on the documentation, File (constructor)","metadata":{"transformedAt":"2026-08-18T18:33:40.676Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":93,"estimatedTokens":487}}247{"id":"stack-68566201","source":"stackoverflow","questionId":68566201,"title":"How to trigger same function on different events in Svelte","tags":["javascript","svelte"],"text":"Title: How to trigger same function on different events in Svelte\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI have:\n\n```\n func(param)} on:auxclick={() => func(param)}>\n click\n\n```\n\nIs there any way I can combine `on:click` and `on:auxclick` into `on:click|auxclick`, or something similar to this effect? (Code below gives me a syntax error.)\n\n```\n func(param)}>\n click\n\n```\n\nEdit: for clearer description\n\n========================================\n\nTop Answer:\nNope, this is not possible without creating named function.\n\nAnd syntax you proposed: `on:click|auxclick={func}` is already reserved by event modifiers feature (you can learn about them from here)\n\nIn the future you maybe could listen for **all** events - proposal and syntax could be found in issue on github\n\nUPD: Also recommend you to look at @kindoflew answer. You can implement this using custom action.\n\n========================================\n\nCode:\n```text\n<a href={link} on:click={() => func(param)} on:auxclick={() => func(param)}>\n click\n</a>\n```\n\n```text\n<a href={link} on:click|auxclick={() => func(param)}>\n click\n</a>\n```\n\n```text\non:click\n```\n\n```text\non:auxclick\n```\n\n```text\non:click|auxclick\n```\n\n```js\n// multiClicks.js\n\nexport const multiClicks = (node, callback) => {\n node.addEventListener('click', callback)\n node.addEventListener('auxclick', callback})\n\n return {\n destroy() {\n node.removeEventListener('click', callback)\n node.removeEventListener('auxclick', callback})\n } \n }\n}\n```\n\n```html\n<script>\n import { multiClicks } from './multiClicks.js'\n</script>\n\n<a use:multiClicks={() => func(param)}>...</a>\n```\n\n```text\n<script>\nfunction handleClick(event) {\n // do something here\n}\n</script>\n\n<a href={link} on:click={handleClick} on:auxclick={handleClick}>\n click\n</a>\n```\n\n```text\non:click|auxclick={func}\n```\n\n========================================\n\nComments:\n- I'm asking if there's any valid syntax that is similar in concept to: `on:click|auxclick={handleClick}`, instead of `on:click` and `on:auxclick` being separated\n- A better description probably would have helped then, you can always go back and edit your question. There wont be though as the syntax you want uses an anonymous function which you wont be able to bind to 2 events.","metadata":{"transformedAt":"2026-08-18T18:33:40.676Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":106,"estimatedTokens":570}}248{"id":"stack-70935314","source":"stackoverflow","questionId":70935314,"title":"How to add an \"active\" class to navbar in sveltekit?","tags":["svelte","sveltekit"],"text":"Title: How to add an \"active\" class to navbar in sveltekit?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm trying to set `path` when a route changes, but its not updating:\n\n```\n\n import { page } from '$app/stores';\n let path;\n\n function getPath() {\n path = $page.url.pathname;\n console.log(path);\n }\n\n $: $page.url.pathname;\n $: getPath();\n\n \n \n \n Dashboard\n \n \n Messages\n \n \n \n\n nav li.active a {\n color: #fff;\n }\n\n```\n\nTHis isn't updating when i change routes in browser.\n\n========================================\n\nTop Answer:\n```\nlet dashboardActive = false;\nif(window.location.pathname == '/dashboard'){\n dashboardActive = true;\n}\n\n {#if dashboardActive}\n \n Dashboard\n {:else}\n \n Dashboard\n {/if}\n \n\n```\n\n========================================\n\nCode:\n```text\n<script>\n import { page } from '$app/stores';\n let path;\n\n function getPath() {\n path = $page.url.pathname;\n console.log(path);\n }\n\n $: $page.url.pathname;\n $: getPath();\n</script>\n\n<aside>\n <nav>\n <ul>\n <li class={path === '/' ? 'active' : ''}>\n <a href=\"/\"><img src=\"/icons/compass.svg\" alt=\"\" border=\"0\" />Dashboard</a>\n </li>\n <li class={path === '/messages' ? 'active' : ''}>\n <a href=\"/messages\"><img src=\"/icons/messages.svg\" alt=\"\" border=\"0\" /> Messages</a>\n </li>\n </ul>\n </nav>\n</aside>\n\n<style>\n nav li.active a {\n color: #fff;\n }\n</style>\n```\n\n```text\npath\n```\n\n```svelte\n<script>\n import { page } from '$app/stores';\n let path;\n\n function getPath(currentPath) {\n path = currentPath;\n console.log(path);\n }\n\n $: getPath($page.url.pathname);\n</script>\n```\n\n```svelte\n<script>\n import { page } from '$app/stores';\n let path;\n\n $: path = $page.url.pathname;\n</script>\n```\n\n```text\ngetPath()\n```\n\n```text\npath\n```\n\n```text\nlet dashboardActive = false;\nif(window.location.pathname == '/dashboard'){\n dashboardActive = true;\n}\n\n<a class=\"mainmenuNew\" href=\"/dashboard\" >\n {#if dashboardActive}\n <span class=\"mainmenuImg\"><img class='icnImg' src=\"/leftmenu/dashboard-active.png\"></span>\n <span class=\"mainmenutext activemenutxt\" >Dashboard</span>\n {:else}\n <span class=\"mainmenuImg\"><img class='icnImg' src=\"/leftmenu/dashboard.png\"></span>\n <span class=\"mainmenutext\" >Dashboard</span>\n {/if}\n <div style=\"clear:both;\"></div>\n</a>\n```\n\n========================================\n\nComments:\n- If you're reading this thread you may also want to see this thread: stackoverflow.com/questions/70613169/…","metadata":{"transformedAt":"2026-08-18T18:33:40.676Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":153,"estimatedTokens":653}}249{"id":"stack-70585661","source":"stackoverflow","questionId":70585661,"title":"How to use Tailwind background-image in SvelteKit","tags":["tailwind-css","svelte","svelte-3","sveltekit"],"text":"Title: How to use Tailwind background-image in SvelteKit\nTags: tailwind-css, svelte, svelte-3, sveltekit\nSource: Stack Overflow\n\nQuestion:\nhttps://tailwindcss.com/docs/background-image#arbitrary-values\n\nthis is how I want to use Tailwind bg-image feature. This does not work using SvelteKit next 160 and Tailwind 3.0.9.\n\nCode:\n\n```\n\n import globe from '$assets/bg/bg_globe2.png'\n\n //children\n\n```\n\nthe `bg-[right_-14rem_bottom_-10rem]` class works without problems, so I assume Tailwind has problem with Svelte file paths?\n\nEDIT:\noutput from console.log(globe) is `src/assets/bg/bg_globe2.png`.\n\n========================================\n\nTop Answer:\nHere's the oneliner util function I came up with based on the response comments I've got, and also handling some path shenanigans on windows.\n\n```\nexport const toImageUrl = processedImagePath => `url('${processedImagePath.slice(1).replaceAll('\\\\', '/')}')`\n```\n\nand the usage:\n\n```\nimport background from '$assets/bg/bg_setup.png?format=webp&quality=90'\n import { toImageUrl } from '$utils/index.js'\n\n \n```\n\nThe query params in image import are due to the usage of `vite-imagetools`\n\n========================================\n\nCode:\n```text\n<script>\n import globe from '$assets/bg/bg_globe2.png'\n</script>\n\n<div\n class={`flex flex-col bg-primary-dark h-64 overflow-hidden bg-no-repeat bg-[right_-14rem_bottom_-10rem] bg-[url('${globe}')]`}\n>\n //children\n</div>\n```\n\n```text\nbg-[right_-14rem_bottom_-10rem]\n```\n\n```text\nsrc/assets/bg/bg_globe2.png\n```\n\n```text\n<div class=\"bg-{ userThemeColor }\"></div>\n```\n\n```text\n<div style=\"background-color: { userThemeColor }\"></div>\n```\n\n```text\nexport const toImageUrl = processedImagePath => `url('${processedImagePath.slice(1).replaceAll('\\\\', '/')}')`\n```\n\n```text\nimport background from '$assets/bg/bg_setup.png?format=webp&quality=90'\n import { toImageUrl } from '$utils/index.js'\n\n <div style=\"background-image: {toImageUrl(background)}\"/>\n```\n\n```text\nvite-imagetools\n```\n\n========================================\n\nComments:\n- What's the output of `console.log(globe)`? Can you please add that to your question?\n- Tested it on my end with the same result as yours. Arbitrary values work for positioning and show up in the style inspector, but the arbitrary value for the background image is not taken into account even though the path is correct (and tested), so I'm not sure it's a path issue?\n- Have you tried resolving the abiguity? `bg-[image:url('${globe}')]`\n- @JHeth I checked, doesn't change anything. Tested both dev and build+preview, same thing. The path to the image is valid, the tailwind syntax looks correct, but no `background-image` style is generated for the div.\n- @ThomasHennes does it at least work with a valid external URL? Like shown here play.tailwindcss.com/JHnGi2O6TQ if the answer is yes then I'd say using import for images is the problem.\n- @ThomasHennes output from console.log(globe) is `src/assets/bg/bg_globe2.png`. I updated the question.\n- @JHeth Just tested with a hardcoded, absolute URL (the same as in your tailwind playground) and the background image doesn't show. So it's clearly not a URL/path issue.\n- Apologies, I was wrong. The hardcoded URL gets correctly translated into a `background-image` style for the div (though the image still doesn't show up). So it looks like it **is** indeed a path issue. Sorry for misreporting that. I need some sleep -_-\n- I just tested a fresh SvelteKit install and the following worked fine `bg-[image:url('/src/assets/svelte.png')]` but no form of that path as a variable works including the import. The external image URL works both inline and as a variable for me. Tailwind seems to be purging any attempts at using the local file as a variable.","metadata":{"transformedAt":"2026-08-18T18:33:40.676Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":102,"estimatedTokens":940}}250{"id":"stack-55594340","source":"stackoverflow","questionId":55594340,"title":"How to access url params in sapper outside of preload function?","tags":["url","parameters","svelte"],"text":"Title: How to access url params in sapper outside of preload function?\nTags: url, parameters, svelte\nSource: Stack Overflow\n\nQuestion:\nIn Sapper, AFAIK from documentation. The only way to access URL params are through `preload()` function, from which params are available inside `params` object.\n\nThe thing is that I want to access these params ouside of `preload()` function. From an eagle eye view of documentation. I don't / can't see the solution to my problem / requirement.\n\nI have tried setting a property for url param inside `data()`. But it seems `preload()` has no access to `data` whether getting wise or setting wise. *It is not meant for those things.*\n\n========================================\n\nTop Answer:\nIf you are using v3 Svelte and latest alpha of Sapper, import page which is now provided as a store.\n\n```\nimport { page } from '@sapper/app';\n\nconst {slug} = $page.params;\n```\n\n========================================\n\nCode:\n```text\npreload()\n```\n\n```text\nparams\n```\n\n```text\npreload()\n```\n\n```text\ndata()\n```\n\n```text\npreload()\n```\n\n```text\ndata\n```\n\n```text\n<script>\nimport { stores } from \"@sapper/app\";\n\nconst { page } = stores();\nconst { slug } = $page.params;\n</script>\n```\n\n```text\nimport { page } from '@sapper/app';\n\nconst {slug} = $page.params;\n```\n\n========================================\n\nComments:\n- This would be great, but it doesn't seem to work for me. What version of Sapper exactly are you using?\n- This was for an older version of Sapper (latest at time of answer). Accepted answer is the right way to do it now.","metadata":{"transformedAt":"2026-08-18T18:33:40.676Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":69,"estimatedTokens":389}}251{"id":"stack-69846025","source":"stackoverflow","questionId":69846025,"title":"Svelte / SvelteKit and Typescript: add properties to the window object, or extend the interface","tags":["typescript","svelte","sveltekit"],"text":"Title: Svelte / SvelteKit and Typescript: add properties to the window object, or extend the interface\nTags: typescript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have the following working (running) code but am getting the TypeScript error *Property 'onSubmit' does not exist on type 'Window & typeof globalThis'.*.\n\n```\nfunction onSubmit() {\n . . .\n}\n\nonMount(() => {\n window.onSubmit = onSubmit; {\n window.onSubmit = null; In my *global.d.ts* file I have tried exporting an interface to import\n\n```\nexport interface CustomWindow extends Window {\n onSubmit: () => void;\n}\n```\n\nand declaring a global\n\n```\ndeclare global {\n interface Window {\n onSubmit: () => void;\n }\n}\n```\n\nNeither solution has been successful, the error persists. How can we add properties to the window object for TypeScript to recognize?\n\n========================================\n\nCode:\n```text\nfunction onSubmit() {\n . . .\n}\n\nonMount(() => {\n window.onSubmit = onSubmit; <-- Error\n});\n\nonDestroy(() => {\n window.onSubmit = null; <-- Error\n});\n```\n\n```text\nexport interface CustomWindow extends Window {\n onSubmit: () => void;\n}\n```\n\n```text\ndeclare global {\n interface Window {\n onSubmit: () => void;\n }\n}\n```\n\n```js\ndeclare interface Window {\n onSubmit: () => void;\n}\n```\n\n```text\ndeclare\n```\n\n```text\nglobal\n```\n\n```text\nimport\n```\n\n```text\nexport\n```\n\n```text\nglobal.d.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.676Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":90,"estimatedTokens":344}}252{"id":"stack-73154257","source":"stackoverflow","questionId":73154257,"title":"How to properly remove event listener from window object?","tags":["svelte","web-component","custom-element"],"text":"Title: How to properly remove event listener from window object?\nTags: svelte, web-component, custom-element\nSource: Stack Overflow\n\nQuestion:\n**CustomElement.svelte**\n\n```\n\n import { onMount, onDestroy } from \"svelte\";\n\n onMount(() => {\n window.addEventListener(\"scroll\", funcRef);\n });\n\n onDestroy(() => {\n window.removeEventListener(\"scroll\", funcRef);\n });\n\n const funcRef = (event) => {\n doWhatever();\n }\n\n```\n\nActually, the event handler should be removed when the custom element gets removed from the document, but it won't. What am I missing?\n\n========================================\n\nTop Answer:\nthe code you provided will work properly and it will automatically remove event listeners when the component is destroyed but here is a better version\n\n```\n\n import { onMount} from \"svelte\";\n\n onMount(() => {\n const funcRef = (event) => {\n doWhatever();\n }\n window.addEventListener(\"scroll\", funcRef);\n\n return ()=>{\n // this function is called when the component is destroyed\n window.removeEventListener(\"scroll\", funcRef);\n }\n });\n\n```\n\n========================================\n\nCode:\n```text\n<svelte:options tag=\"custom-element\" />\n\n<script>\n import { onMount, onDestroy } from \"svelte\";\n\n onMount(() => {\n window.addEventListener(\"scroll\", funcRef);\n });\n\n onDestroy(() => {\n window.removeEventListener(\"scroll\", funcRef);\n });\n\n const funcRef = (event) => {\n doWhatever();\n }\n</script>\n```\n\n```text\n{#if}\n```\n\n```text\n$destroy\n```\n\n```js\n<svelte:options tag=\"custom-element\" />\n\n<script>\n import { onMount} from \"svelte\";\n\n onMount(() => {\n const funcRef = (event) => {\n doWhatever();\n }\n window.addEventListener(\"scroll\", funcRef);\n\n return ()=>{\n // this function is called when the component is destroyed\n window.removeEventListener(\"scroll\", funcRef);\n }\n });\n</script>\n```\n\n```html\n<svelte:window\n on:scroll={funcRef}\n/>\n```\n\n========================================\n\nComments:\n- I actually thought `onDestroy` was the equivalent of `disconnectedCallback`. So if I remove the custom element outside of a Svelte component, how do I call `$destroy`?\n- It is defined as a function of the custom element, so if you have a reference to it, you can just call it like any other function. E.g. `document.querySelector('custom-element').$destroy()`\n- Is there another/better way you would recommend?\n- Depends on the context, if you can just do everything within Svelte components, and you just have one root component which is never removed anyway, you will not have to deal with this at all. If this is not the case, you will have to dispose the components yourself. Maybe you can leverage some other event to tell you, when `$destroy` has to be called to make this easier. Or you can employ a `MutationObserver` to tell you when things get removed.\n- Why is your version better?\n- @Annika: It has two advantages: One less import and the event handler does not need to be declared outside the `onMount` to make the scoping work. The impact of this should be fairly minimal though.\n- Exactly, that's right @H.B.","metadata":{"transformedAt":"2026-08-18T18:33:40.677Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":117,"estimatedTokens":768}}253{"id":"stack-72511154","source":"stackoverflow","questionId":72511154,"title":"How would I go about creating a Django + SvelteKit webapp?","tags":["javascript","django","svelte","sveltekit","web-development-server"],"text":"Title: How would I go about creating a Django + SvelteKit webapp?\nTags: javascript, django, svelte, sveltekit, web-development-server\nSource: Stack Overflow\n\nQuestion:\nI've already gotten my fair of Bootstrap and Django but never tried out other frontend frameworks like Angular, React, etc. and finally wanted to try SvelteKit. So I'm really inexperienced and new with this sort of stuff.\n\nCurrently I've already set-up my Django project as well as a SvelteKit project by following the tutorial on their website.\n\nMy problem is that I'm confused about how to combine Django and SvelteKit now. Do I just run both servers simultaneously on different ports and get the data from Django JSON APIs into my Svelte frontend or is there some kind of approach to this? I thought that maybe there's a way to get my Django app to render the Svelte files from the Svelte server for me. I just feel really lost at the moment so if anyone could help me or has some resources I could read to get more familiar with the topic, since I didn't find a lot online, that'd be great!\n\n========================================\n\nTop Answer:\nI find myself having the same question, it's not perfect but I got it to work with the following:\n\nCreate a directory that will contain everything, e.g. *my-project*\n\nInside the directory create your Django project, e.g. *django-svelte*, with `django-admin startproject django-svelte`\n\nFrom *my-project/django-svelte* create an app to contain the svelte app, e.g. *frontend*, with `python manage.py startapp frontend`\n\nInside *frontend* create two subdirectories *templates* and *static*; inside each of them create a *frontend* directory. (You should have *frontend/templates/frontend* and *frontend/static/frontend* in the end)\n\nInside *my-project* initialize a svelte-kit project, e.g. *client*, with `npm init svelte client`\n\nInside *client* install all packages and add *@sveltejs/adapter-static* with `npm install` and `npm i -D @sveltejs/adapter-static`\n\nReplace the content of *svelte.config.js* with:\n\n```\nimport adapter from '@sveltejs/adapter-static';\n\nexport default {\n kit: {\n paths: { base: \"/static/frontend\" }, // Adjust according to where you collect static files and the name of the Django app \n adapter: adapter({\n pages: '../django-svelte/frontend/templates/frontend', // Adjust according to the name of the Django app\n assets: '../django-svelte/frontend/static/frontend', // Adjust according to the name of the Django app\n fallback: null,\n precompress: false\n }),\n\n prerender: {\n // This can be false if you're using a fallback (i.e. SPA mode)\n default: true\n }\n }\n};\n```\n\nThis will write your HTML, JS and CSS files inside the *frontend* app.\n\nCreate a build with `npm run build`\n\nCollect static files in Django with `python manage.py collectstatic`\n\nRun Django with `python manage.py runserver` or other servers\n\nI'm sure there are simpler ways though :-)\n\n========================================\n\nCode:\n```text\ndjango.example.com\n```\n\n```text\nkit.example.com\n```\n\n```text\nexample.com:8000\n```\n\n```text\nexample.com:3000\n```\n\n```text\nhandle()\n```\n\n```text\nimport adapter from '@sveltejs/adapter-static';\n\nexport default {\n kit: {\n paths: { base: \"/static/frontend\" }, // Adjust according to where you collect static files and the name of the Django app \n adapter: adapter({\n pages: '../django-svelte/frontend/templates/frontend', // Adjust according to the name of the Django app\n assets: '../django-svelte/frontend/static/frontend', // Adjust according to the name of the Django app\n fallback: null,\n precompress: false\n }),\n\n prerender: {\n // This can be false if you're using a fallback (i.e. SPA mode)\n default: true\n }\n }\n};\n```\n\n```text\ndjango-admin startproject django-svelte\n```\n\n```text\npython manage.py startapp frontend\n```\n\n```text\nnpm init svelte client\n```\n\n```text\nnpm install\n```\n\n```text\nnpm i -D @sveltejs/adapter-static\n```\n\n```text\nnpm run build\n```\n\n```text\npython manage.py collectstatic\n```\n\n```text\npython manage.py runserver\n```\n\n========================================\n\nComments:\n- If you use a vanilla svelte app instead of sveltekit, it's probably possible to set up a flow where your Django API will try to route and handle the request, and for anything it doesn't understand it will serve the svelte app instead of a 400 code. From there the svelte app will try to handle the request, and if it doesn't understand, render a 404 page. I haven't seen this done though so you would have to research how on your own. I've only seen this pattern with a .NET and React combo.\n- I made a simple template for svelte and django. please check this link: github.com/Pei2tech/svelte4django. What you need to add routing to support svelte instead of using sveltekit.\n- +1 to this, and it's also worth mentioning that you can get the full SPA experience with a vanilla svelte app including client side routing and many other features, and in some situations serving the front end from a CDN might actually be better for your users. All Sveltekit is doing is formalizing features people commonly use and adding a \"batteries included\" server layer. (but I still love sveltekit, and I'm still writing 2 side projects with it!)\n- Hi @mur762, I was able to set up and loaded the page but I think the slot is not working as expected. I added a few lines before and after the slot in layout.svelte and those lines are working as expected. but anything under the slot is not working at all. Can you please help me here. The only error message I'm getting is Not Found 404: at / However Django logs show that requests for static assets is 200 (Successfull). On Sveltekit side only layout page is working not even +page.svelte or index.svelte","metadata":{"transformedAt":"2026-08-18T18:33:40.677Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":144,"estimatedTokens":1450}}254{"id":"stack-72773373","source":"stackoverflow","questionId":72773373,"title":"'Buffer' is not exported by __vite-browser-external:buffer","tags":["javascript","svelte","vite","sveltekit"],"text":"Title: 'Buffer' is not exported by __vite-browser-external:buffer\nTags: javascript, svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm getting this build error with vite and sveltekit using adapter-node\n\nI'm not sure why it won't build since it relies on node to server the client.\n\ndev works fine\n\n`'Buffer' is not exported by __vite-browser-external:buffer`\n\nI tried polyfills but they don't work.\n\n```\noptimizeDeps: {\n esbuildOptions: {\n // Node.js global to browser globalThis\n define: {\n global: 'globalThis'\n },\n // Enable esbuild polyfill plugins\n plugins: [\n NodeGlobalsPolyfillPlugin({\n process: true,\n buffer: true,\n webworkers: true,\n }),\n NodeModulesPolyfillPlugin()\n ]\n }\n },\n build: {\n minify: true,\n rollupOptions: {\n plugins: [\n // Enable rollup polyfills plugin\n // used during production bundling\n rollupNodePolyFill()\n ]\n }\n }\n```\n\n========================================\n\nTop Answer:\nI solved it by adding the right aliases (including `buffer` and `process`) to `config.vite.ts`. That's how mine looks like:\n\n```\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport tsconfigPaths from 'vite-tsconfig-paths'\nimport { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'\nimport { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill'\nimport rollupNodePolyFill from 'rollup-plugin-node-polyfills'\n\nexport default defineConfig({\n plugins: [react(), tsconfigPaths()],\n server: {\n port: 3001,\n open: true\n },\n resolve: {\n alias: {\n // This Rollup aliases are extracted from @esbuild-plugins/node-modules-polyfill, \n // see https://github.com/remorses/esbuild-plugins/blob/master/node-modules-polyfill/src/polyfills.ts\n util: 'rollup-plugin-node-polyfills/polyfills/util',\n sys: 'util',\n events: 'rollup-plugin-node-polyfills/polyfills/events',\n stream: 'rollup-plugin-node-polyfills/polyfills/stream',\n path: 'rollup-plugin-node-polyfills/polyfills/path',\n querystring: 'rollup-plugin-node-polyfills/polyfills/qs',\n punycode: 'rollup-plugin-node-polyfills/polyfills/punycode',\n url: 'rollup-plugin-node-polyfills/polyfills/url',\n string_decoder:\n 'rollup-plugin-node-polyfills/polyfills/string-decoder',\n http: 'rollup-plugin-node-polyfills/polyfills/http',\n https: 'rollup-plugin-node-polyfills/polyfills/http',\n os: 'rollup-plugin-node-polyfills/polyfills/os',\n assert: 'rollup-plugin-node-polyfills/polyfills/assert',\n constants: 'rollup-plugin-node-polyfills/polyfills/constants',\n _stream_duplex:\n 'rollup-plugin-node-polyfills/polyfills/readable-stream/duplex',\n _stream_passthrough:\n 'rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough',\n _stream_readable:\n 'rollup-plugin-node-polyfills/polyfills/readable-stream/readable',\n _stream_writable:\n 'rollup-plugin-node-polyfills/polyfills/readable-stream/writable',\n _stream_transform:\n 'rollup-plugin-node-polyfills/polyfills/readable-stream/transform',\n timers: 'rollup-plugin-node-polyfills/polyfills/timers',\n console: 'rollup-plugin-node-polyfills/polyfills/console',\n vm: 'rollup-plugin-node-polyfills/polyfills/vm',\n zlib: 'rollup-plugin-node-polyfills/polyfills/zlib',\n tty: 'rollup-plugin-node-polyfills/polyfills/tty',\n domain: 'rollup-plugin-node-polyfills/polyfills/domain',\n buffer: 'rollup-plugin-node-polyfills/polyfills/buffer-es6',\n process: 'rollup-plugin-node-polyfills/polyfills/process-es6'\n }\n },\n optimizeDeps: {\n esbuildOptions: {\n // Node.js global to browser globalThis\n define: {\n global: 'globalThis'\n },\n // Enable esbuild polyfill plugins\n plugins: [\n NodeGlobalsPolyfillPlugin({\n process: true,\n buffer: true\n }),\n NodeModulesPolyfillPlugin()\n ]\n }\n },\n build: {\n rollupOptions: {\n plugins: [\n // Enable rollup polyfills plugin\n // used during production bundling\n // @ts-ignore\n rollupNodePolyFill(),\n ]\n }\n }\n})\n```\n\n========================================\n\nCode:\n```text\noptimizeDeps: {\n esbuildOptions: {\n // Node.js global to browser globalThis\n define: {\n global: 'globalThis'\n },\n // Enable esbuild polyfill plugins\n plugins: [\n NodeGlobalsPolyfillPlugin({\n process: true,\n buffer: true,\n webworkers: true,\n }),\n NodeModulesPolyfillPlugin()\n ]\n }\n },\n build: {\n minify: true,\n rollupOptions: {\n plugins: [\n // Enable rollup polyfills plugin\n // used during production bundling\n rollupNodePolyFill()\n ]\n }\n }\n```\n\n```text\n'Buffer' is not exported by __vite-browser-external:buffer\n```\n\n```text\nnpm install -D buffer\n```\n\n```js\n// vite.config.js\nbuild: {\n commonjsOptions: {\n include: ['node_modules/buffer/index.js']\n }\n}\n```\n\n```js\n// vite.config.js\nbuild: {\n commonjsOptions: {\n include: ['node_modules/**/*.js']\n }\n}\n```\n\n```text\n.js\n```\n\n```text\nbuild: {\n rollupOptions: {\n plugins: [inject({ Buffer: ['Buffer', 'Buffer'] })],\n },\n },\n```\n\n```text\nnpm i -D buffer\n```\n\n```js\nimport { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport tsconfigPaths from 'vite-tsconfig-paths'\nimport { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'\nimport { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill'\nimport rollupNodePolyFill from 'rollup-plugin-node-polyfills'\n\nexport default defineConfig({\n plugins: [react(), tsconfigPaths()],\n server: {\n port: 3001,\n open: true\n },\n resolve: {\n alias: {\n // This Rollup aliases are extracted from @esbuild-plugins/node-modules-polyfill, \n // see https://github.com/remorses/esbuild-plugins/blob/master/node-modules-polyfill/src/polyfills.ts\n util: 'rollup-plugin-node-polyfills/polyfills/util',\n sys: 'util',\n events: 'rollup-plugin-node-polyfills/polyfills/events',\n stream: 'rollup-plugin-node-polyfills/polyfills/stream',\n path: 'rollup-plugin-node-polyfills/polyfills/path',\n querystring: 'rollup-plugin-node-polyfills/polyfills/qs',\n punycode: 'rollup-plugin-node-polyfills/polyfills/punycode',\n url: 'rollup-plugin-node-polyfills/polyfills/url',\n string_decoder:\n 'rollup-plugin-node-polyfills/polyfills/string-decoder',\n http: 'rollup-plugin-node-polyfills/polyfills/http',\n https: 'rollup-plugin-node-polyfills/polyfills/http',\n os: 'rollup-plugin-node-polyfills/polyfills/os',\n assert: 'rollup-plugin-node-polyfills/polyfills/assert',\n constants: 'rollup-plugin-node-polyfills/polyfills/constants',\n _stream_duplex:\n 'rollup-plugin-node-polyfills/polyfills/readable-stream/duplex',\n _stream_passthrough:\n 'rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough',\n _stream_readable:\n 'rollup-plugin-node-polyfills/polyfills/readable-stream/readable',\n _stream_writable:\n 'rollup-plugin-node-polyfills/polyfills/readable-stream/writable',\n _stream_transform:\n 'rollup-plugin-node-polyfills/polyfills/readable-stream/transform',\n timers: 'rollup-plugin-node-polyfills/polyfills/timers',\n console: 'rollup-plugin-node-polyfills/polyfills/console',\n vm: 'rollup-plugin-node-polyfills/polyfills/vm',\n zlib: 'rollup-plugin-node-polyfills/polyfills/zlib',\n tty: 'rollup-plugin-node-polyfills/polyfills/tty',\n domain: 'rollup-plugin-node-polyfills/polyfills/domain',\n buffer: 'rollup-plugin-node-polyfills/polyfills/buffer-es6',\n process: 'rollup-plugin-node-polyfills/polyfills/process-es6'\n }\n },\n optimizeDeps: {\n esbuildOptions: {\n // Node.js global to browser globalThis\n define: {\n global: 'globalThis'\n },\n // Enable esbuild polyfill plugins\n plugins: [\n NodeGlobalsPolyfillPlugin({\n process: true,\n buffer: true\n }),\n NodeModulesPolyfillPlugin()\n ]\n }\n },\n build: {\n rollupOptions: {\n plugins: [\n // Enable rollup polyfills plugin\n // used during production bundling\n // @ts-ignore\n rollupNodePolyFill(),\n ]\n }\n }\n})\n```\n\n```text\nbuffer\n```\n\n```text\nprocess\n```\n\n```text\nconfig.vite.ts\n```\n\n```text\nnpm install -D buffer\n```\n\n```js\nimport { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'\n\nexport default defineConfig({\n...\n optimizeDeps: {\n esbuildOptions: {\n // Node.js global to browser globalThis\n define: {\n global: 'globalThis'\n },\n // Enable esbuild polyfill plugins\n plugins: [\n NodeGlobalsPolyfillPlugin({\n process: true,\n buffer: true\n })\n ]\n },\n },\n...\n})\n```\n\n```text\nnpm install rollup-plugin-node-polyfills\n```\n\n```js\n// vite.config.ts\nresolve: {\n alias: {\n ...\n buffer: 'rollup-plugin-node-polyfills/polyfills/buffer-es6',\n process: 'rollup-plugin-node-polyfills/polyfills/process-es6'\n }\n },\n```\n\n========================================\n\nComments:\n- can you show where the \"inject()\" came from? I want to apply this solution but I don't know what the inject() is\n- it seems `inject` comes from `const inject = require('@rollup/plugin-inject')`\n- if only I saw this earlier, thanks a lot sir. I am just wondering why it not ``` [inject({ Buffer: ['Buffer', 'buffer'] })], ``` is it because they are case insensitive?\n- I have that. Didn't work for me.\n- I edited my answer, adding the buffer alias is what made it work for me (although that's a React project, it shouldn't change anything)\n- Adding this solved my issue but then created a new error in a React default import : `RollupError: node_modules/rc-util/es/Children/toArray.js (1:7): \"default\" is not exported by \"node_modules/react/index.js\",`\n- You can also try `include: ['node_modules/**/*.js']`","metadata":{"transformedAt":"2026-08-18T18:33:40.677Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":354,"estimatedTokens":2641}}255{"id":"stack-63066511","source":"stackoverflow","questionId":63066511,"title":"Svelte dev server is stuck on old version","tags":["svelte","rollupjs"],"text":"Title: Svelte dev server is stuck on old version\nTags: svelte, rollupjs\nSource: Stack Overflow\n\nQuestion:\nI'm using Svelte with Rollup. I've always had a great dev server experience using npm run dev. Now, though the dev server seems stuck on an older version of my application. If I deploy with run build I get my latest changes, but npm run dev attempts to run the same thing from yesterday every time. I think this may be a browser session/cookie issue, as localhost:5000 in a chrome incognito tab served the latest version... but now it is also stuck on that version and won't update as I make and save changes. Any tips?\n\n========================================\n\nTop Answer:\nNothing on internet worked for me in this case, so I found following to (sort of) unblock myself\n\n```\nnpm run build\nnpm run preview\n```\n\nThis allows me to check the progress of my work.\n\nDisadvantages of going this way:\n\n- Your changes are no longer live, you need to run these commands again in order to load any new changes.\n\n- It no longer retains the actual file structure. It has built your project for production, so it does some optimisations. As a result of which, it will be hard for you to debug the code in browsers.\n\n========================================\n\nCode:\n```text\nnpm run build\nnpm run preview\n```\n\n========================================\n\nComments:\n- thanks Carlos. I had the same issue while following the Svelte tutorials., your answer fixed it.\n- I wish svelte had something to invalidate local cache, but this works, thanks!","metadata":{"transformedAt":"2026-08-18T18:33:40.677Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":38,"estimatedTokens":383}}256{"id":"stack-69630422","source":"stackoverflow","questionId":69630422,"title":"svelte: how to use event modifiers in my own components","tags":["event-handling","svelte"],"text":"Title: svelte: how to use event modifiers in my own components\nTags: event-handling, svelte\nSource: Stack Overflow\n\nQuestion:\nI want to developt my own Button component and be able to handle event modifiers, like this:\n\n```\nClick me\n```\n\nBut I get the following error:\n\n```\nEvent modifiers other than 'once' can only be used on DOM elementssvelte(invalid-event-modifier)\n```\n\nIn MyButton I can pass the on:click event like this:\n\n```\n\n \n\n```\n\nBut then I won't be able to use MyButton without the preventDefault\n\nSo another option would be to optionally pass event modifiers, to do something like this:\n\n```\nClick me\n```\n\nAnd then in MyButton.svelte to something like this (I know this doesn't work) to optionally apply the event modifier.\n\n```\n\n export let prevenDefault=false\n\nClick me\n```\n\nAny idea about how to deal with it?\n\n========================================\n\nTop Answer:\n**Custom button component**\n\n```\n\n export let preventDefault: boolean = false;\n export let stopPropagation: boolean = false;\n type MouseEvent = Parameters>[0];\n type $$Events = {\n click: MouseEvent;\n };\n\n{#if preventDefault}\n {#if stopPropagation}\n \n {:else}\n \n {/if}\n{:else if stopPropagation}\n \n{:else}\n \n{/if}\n```\n\n**Custom button component usage**\n\n```\n\n Send complaint\n\n```\n\nIf you can endure to insane branch statements drive your brain crazy, this code should achieve what you're looking for. I know. this is really poor workaround. I really want Svelte has a better way of doing this.\n\n========================================\n\nCode:\n```text\n<MyButton on:click|preventDefault={handler}>Click me</MyButton>\n```\n\n```text\nEvent modifiers other than 'once' can only be used on DOM elementssvelte(invalid-event-modifier)\n```\n\n```text\n<button on:click|preventDefault>\n <slot />\n</button>\n```\n\n```text\n<MyButton preventDefault on:click={handler}>Click me</MyButton>\n```\n\n```text\n<script>\n export let prevenDefault=false\n</script>\n\n<button on:click|{preventDefault ? 'preventDefault' : ''}={handler}>Click me</MyButton>\n```\n\n```html\n<script>\n // Button.svelte\n</script>\n\n<!-- Note that we're not providing any callback, which forwards it -->\n<button on:click>\n <slot />\n</button>\n```\n\n```html\n<script>\n // App.svelte\n\n import Button from './Button.svelte';\n</script>\n\n<Button\n on:click={(event) => {\n event.preventDefault();\n\n // your code here\n }}\n>\n Click Me!\n</Button>\n```\n\n```html\n<script>\n // Button.svelte\n\n import {\n onMount,\n onDestroy,\n createEventDispatcher,\n } from 'svelte';\n\n export let preventDefault = false;\n\n let button;\n const dispatch = createEventDispatcher();\n\n onMount(() => {\n button.addEventListener('click', onClick);\n });\n\n onDestroy(() => {\n button.removeEventListener('click', onClick);\n });\n\n function onClick(event) {\n if (preventDefault) event.preventDefault();\n\n dispatch('click', event);\n }\n</script>\n\n<button bind:this={button}>\n <slot />\n</button>\n```\n\n```html\n<script>\n // App.svelte\n\n import Button from './Button.svelte';\n</script>\n\n<Button\n preventDefault\n on:click={({ detail: event }) => {\n // your code here\n })\n>\n Click me!\n</Button>\n```\n\n```text\nEvent#preventDefault\n```\n\n```text\n<Button>\n```\n\n```text\nEvent#preventDefault\n```\n\n```text\nEvent\n```\n\n```text\nCustomEvent#detail\n```\n\n```text\n<Button>\n```\n\n```text\n<script>\n```\n\n```text\npreventDefault\n```\n\n```text\n<script lang=\"ts\">\n export let preventDefault: boolean = false;\n export let stopPropagation: boolean = false;\n type MouseEvent = Parameters<MouseEventHandler<HTMLButtonElement>>[0];\n type $$Events = {\n click: MouseEvent;\n };\n</script>\n\n{#if preventDefault}\n {#if stopPropagation}\n <button {...$$restProps} on:click|preventDefault|stopPropagation\n ><slot /></button>\n {:else}\n <button {...$$restProps} on:click|preventDefault><slot /></button>\n {/if}\n{:else if stopPropagation}\n <button {...$$restProps} on:click|stopPropagation><slot /></button>\n{:else}\n <button {...$$restProps} on:click><slot /></button>\n{/if}\n```\n\n```text\n<Button\n type=\"button\"\n class=\"primary-button\"\n title=\"this is a button\"\n on:click={onClick}\n preventDefault\n stopPropagation\n>\n Send complaint\n</Button>\n```\n\n```text\n<button on:click|preventDefault>\n <MyButton on:click={handleClick}>\n Click Me\n </MyButton>\n</button>\n```\n\n========================================\n\nComments:\n- As is not a DOM element, you won't be able to add modifiers except \"once\". Maybe a component for a button is not accurate ? I'm not sure there is any gain about it.\n- Why not add preventDefault as a bool prop. In your MyButton componend you can use: event.preventDefault() if the preventDefault prop is true.\n- This does the job, but looks like a poor workaround. I wish Svelte had a better way of doing this.","metadata":{"transformedAt":"2026-08-18T18:33:40.677Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":274,"estimatedTokens":1195}}257{"id":"stack-74542864","source":"stackoverflow","questionId":74542864,"title":"Difference between Resumability , Hydration and Reconcillation in modern web app?","tags":["next.js","svelte","remix","solid-js","qwik"],"text":"Title: Difference between Resumability , Hydration and Reconcillation in modern web app?\nTags: next.js, svelte, remix, solid-js, qwik\nSource: Stack Overflow\n\nQuestion:\nWhat are the main differences between Resumability , Hydration and Reconcillation ?\n\nWe know Resumability is future of web app, Is it possible to make most of the current meta framework (Nextjs,Remix, Sveltekit, Solidstart, etc.. ) resumable ?\n\n========================================\n\nComments:\n- I wish. I want Seveltekit so use resumability instead of hydration. It would make it my complexly favorite framework\n- I would like to see a more in depth look at the trade off of resumability because on paper it is really the solution we look for in production websites. Thank you for your comment of resumability being the the future has a bold statement. For most production websites it does solve a big issue with scalability\n- @RoyerAdames Resumability is overly hyped and I believe it does not deserve the publicity it receives. The UI lags when the network is slow and the application is unnecessarily complex and bloated. Future lies in component level server side rendering because the end product tends to be small, secure and efficient.\n- Thank you for responding. The you can take off Resumability from your respond and I will still agree with you. A good example of this is universalorlando.com/web/en/us. Is very slow. Making JS cost be a constant can be a solution for it. There is a lot of JS we load before we can us the page in the example I shared. Can you some examples of why Resumability is all hype? How can I test it myself? Something that I do like about it is that the framework handles the implementation of it while I can keep my current workflow. Now we just need Angular, Svelte, and others to update.","metadata":{"transformedAt":"2026-08-18T18:33:40.677Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":16,"estimatedTokens":450}}258{"id":"stack-56107542","source":"stackoverflow","questionId":56107542,"title":"Are Svelte transitions/animations done with CSS or JS?","tags":["svelte","svelte-transition"],"text":"Title: Are Svelte transitions/animations done with CSS or JS?\nTags: svelte, svelte-transition\nSource: Stack Overflow\n\nQuestion:\nI'm checking out Svelte, and I'm finding a lot more out of the box that I would've expected.\n\nOne thing that surprised me a little bit where the amount of transition and animation tools, especially the tooling for custom transitions, and I can't quite tell from their syntax if these are functions that write CSS, or if they're functions that manipulate styles directly with a CSS-like syntax.\n\nAre the resulting animations CSS only or not?\n\n========================================\n\nCode:\n```js\ncss: t => `opacity: ${t}`\n```\n\n```js\nkeyframes = [\n '0% { opacity: 0 }',\n '10% { opacity: 0.1 }',\n '20% { opacity: 0.2 }',\n // ...\n];\n```\n\n```text\ncss\n```\n\n```text\ntick\n```\n\n```text\ntick\n```\n\n```text\nrequestAnimationFrame\n```\n\n```text\ncss\n```\n\n```text\nt\n```\n\n```text\n0% { opacity: 0 }\n```\n\n```text\n100% { opacity: 1 }\n```\n\n========================================\n\nComments:\n- Thanks! Just to clarify: if I understand you correctly, a `tick` method will manipulate styles in JavaScript but it is there to provide effects CSS itself simply cannot do?\n- It can manipulate styles, or change some state, or log something to the console — whatever you want. It's just there as an escape hatch for when CSS isn't powerful enough.","metadata":{"transformedAt":"2026-08-18T18:33:40.677Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":64,"estimatedTokens":338}}259{"id":"stack-65450487","source":"stackoverflow","questionId":65450487,"title":"Svelte - import const from component does not work","tags":["javascript","svelte","rollup"],"text":"Title: Svelte - import const from component does not work\nTags: javascript, svelte, rollup\nSource: Stack Overflow\n\nQuestion:\nI try to import a const value from a Svelte component, but rollup says, the component does not export this value.\nWhat do I wrong, or is it a rollup problem ?\n\nrelated REPL\n\nComponent.svelte:\n\n\r\n\r\n\n```\n\nexport const answer = 42;\n\n```\n\n\r\n\r\n\r\n\nApp.svelte:\n\n\r\n\r\n\n```\n\nimport { answer } from './Component.svelte';\n\n### {answer}\n\n```\n\n\r\n\r\n\r\n\nThe same problem appears when importing an enum definition.\n\n========================================\n\nTop Answer:\nTry replacing with in Component.svelte. But please note it’ll be read-only no matter how you define it (const or let), so if you want to change the value you may want to create setter or getter function to do that and then access the variable using that.\n\n```\n\n export const answer = 42;\n \n```\n\n========================================\n\nCode:\n```js\n<script>\nexport const answer = 42;\n</script>\n```\n\n```js\n<script>\nimport { answer } from './Component.svelte';\n</script>\n\n<h1>{answer}</h1>\n```\n\n```html\n<script context=\"module\">\n export const answer = 42;\n</script>\n```\n\n```text\nexport\n```\n\n```text\nexport\n```\n\n```text\ncontext=\"module\"\n```\n\n```text\n<script context=\"module\">\n export const answer = 42;\n </script>\n```\n\n========================================\n\nComments:\n- try replacing with in Component.svelte. I have added this as a answer below.\n- more about it in here: svelte.dev/tutorial/module-exports\n- Note that this code and the REPL linked work correctly, but if you're using the Svelte IntelliJ plugin v0.20.0 - it will incorrectly complain about the import as per this issue: github.com/tomblachut/svelte-intellij/issues/241","metadata":{"transformedAt":"2026-08-18T18:33:40.679Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":102,"estimatedTokens":430}}260{"id":"stack-73282472","source":"stackoverflow","questionId":73282472,"title":"Firebase hosting using SvelteKit","tags":["firebase","svelte","firebase-hosting","sveltekit","svelte-3"],"text":"Title: Firebase hosting using SvelteKit\nTags: firebase, svelte, firebase-hosting, sveltekit, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI have created a svelte app and building app using SvelteKit everything is works fine.\n\nI tried to deploy this app in firebase hosting but it fails. Sveltekit generating production build under `.svelte-kit` folder. I tried to change the `public` object value to `\".svelte-kit\"` from `firebase.json` file but it returns error like there is no index.html and 404.html. What we need to change in `firebase.json` to make it work?\n\n```\n{\n \"hosting\": {\n \"public\" : \"public\",\n\n \"ignore\": [\n \"firebase.json\",\n \"**/.*\",\n \"**/node_modules/**\"\n ]\n }\n}\n```\n\n========================================\n\nTop Answer:\nFirebase Hosting now supports Sveltekit natively (Beta). Unfortunately, the current state of documentation is not amazing :) The setup process is pretty straight forward though and there is no need to use the adapters anymore.\n\nI wrote a short Gist on how I did install it on Firebase Hosting and added a few links to useful docs: https://gist.github.com/coehne/caf0b3934455d842dfbfe1f4c1544348\n\n========================================\n\nCode:\n```text\n{\n \"hosting\": {\n \"public\" : \"public\",\n\n \"ignore\": [\n \"firebase.json\",\n \"**/.*\",\n \"**/node_modules/**\"\n ]\n }\n}\n```\n\n```text\n.svelte-kit\n```\n\n```text\npublic\n```\n\n```text\n\".svelte-kit\"\n```\n\n```text\nfirebase.json\n```\n\n```text\nfirebase.json\n```\n\n```text\nimport adapter from '@sveltejs/adapter-static';\n\nimport preprocess from 'svelte-preprocess';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: [\n preprocess({\n postcss: true,\n }),\n ],\n\n kit: {\n adapter: adapter({\n pages: 'public',\n assets: 'public',\n fallback: null,\n precompress: false\n }),\n prerender: {\n default: true\n }\n }\n};\n\nexport default config;\n```\n\n```text\n{\n \"hosting\": {\n \"public\" : \"public\",\n\n \"ignore\": [\n \"firebase.json\",\n \"**/.*\",\n \"**/node_modules/**\"\n ]\n }\n}\n```\n\n```text\nsvelte.config.js\n```\n\n```text\n@sveltejs/adapter-static\n```\n\n```text\nfirebase.json\n```\n\n========================================\n\nComments:\n- Are you using SSR? Then this might be of interest github.com/jthegedus/svelte-adapter-firebase (You might add the info which adapter you are using)\n- Hi, I'm starting a new project. Is there a difference between your adapter and svelte-adapter-firebase?\n- @JanB My adapter generates the cloud function for you while in the other adapter you have to take care of that file yourself. In the grand scheme of things I'd say my adapter is simpler the use while the other one offers you more flexibility","metadata":{"transformedAt":"2026-08-18T18:33:40.679Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":130,"estimatedTokens":722}}261{"id":"stack-61272669","source":"stackoverflow","questionId":61272669,"title":"How can I systematically disable certain irrelevant a11y warnings when compiling with Svelte?","tags":["accessibility","svelte","rollupjs","svelte-3"],"text":"Title: How can I systematically disable certain irrelevant a11y warnings when compiling with Svelte?\nTags: accessibility, svelte, rollupjs, svelte-3\nSource: Stack Overflow\n\nQuestion:\nHere is the warning I get when I compile a component with an img that lacks an alt attribute:\n\n```\nPlugin svelte: A11y: element should have an alt attribute\n```\n\nAll developers will agree A11y is a good thing; except in my case, it would serve only to annoy a screen reader. I'm making a game engine and my objects look like this:\n\nhttps://i.sstatic.net/Tp3g2.png\n\nSVG image, item label. To the screen reader, this would read \"Fabric Scrap Fabric Scrap\"; it really doesn't make sense to have an alt attribute here, but the best the docs have to offer me is that I can clutter up my code like such:\n\n```\n\n```\n\nI really want to avoid that, so how can I get Svelte to stop showing me this specific error? Ideally without disabling the A11y module as a whole.\n\n========================================\n\nTop Answer:\nIn Svelte 5 you can use the `warningFilter` compiler option:\n\n```\n// svelte.config.js\nexport default {\n compilerOptions: {\n warningFilter: (warning) => (warning.code !== 'a11y-autofocus')\n }\n}\n```\n\nSee https://github.com/sveltejs/language-tools/issues/650#issuecomment-2260462839\n\n========================================\n\nCode:\n```text\nPlugin svelte: A11y: <img> element should have an alt attribute\n```\n\n```text\n<!-- svelte-ignore a11y-autofocus -->\n<input bind:value={name} autofocus>\n```\n\n```js\nimport svelte from 'rollup-plugin-svelte'\n\nexport default {\n plugins: [\n svelte({\n // Warnings are normally passed straight to Rollup. You can\n // optionally handle them here, for example to squelch\n // warnings with a particular code\n onwarn: (warning, handler) => {\n // e.g. don't warn on a11y-autofocus\n if (warning.code === 'a11y-autofocus') return\n\n // let Rollup handle all other warnings normally\n handler(warning)\n }\n })\n ]\n}\n```\n\n```text\nonwarn\n```\n\n```js\n// svelte.config.js\nexport default {\n compilerOptions: {\n warningFilter: (warning) => (warning.code !== 'a11y-autofocus')\n }\n}\n```\n\n```text\nwarningFilter\n```\n\n========================================\n\nComments:\n- If this is an SVG loaded via an external call (i.e. not inline in the HTML) you MUST have an alt attribute. The warning you are seeing is because you have left the alt attribute off or have made it null (either `` or ``). You must use `alt=\"\"` so that a screen reader does not announce an image. Leaving it off will then read the file name. Obviously if this SVG is inline within you HTML and not reference via an `` tag then this is irrelevant (but at that point I would guess svelte wouldn't be complaining).\n- Why would you want to disable valid a11y warnings?\n- Ah, good to know about the empty `alt=\"\"` @GrahamRitchie. It would still muddy up the code, though, and I'm going with the selected answer. Nathaniel: please read my question to see why these warnings are indeed irrelevant (actually, worse) in my application.\n- It doesn't work like that, you must have an alt tag as described (`alt=\"\"`) if the image is being loaded externally. If you don't it will be awful for screen reader users and at that point there is no point in running accessibility tests at all. You don't get to decide how clean your code looks sadly. You are concerned about 'Fabric Scrap Fabric Scrap' annoying screen reader users but how do you think 'yourdomain/assets/images/icons/fabric-scrap.svg Fabric Scrap' would sound on a screen reader? That is how it sounds if you do not add a `alt=\"\"` attribute.\n- @GrahamRitchie I missed the line, \"Leaving it off will then read the file name.\" Yikes! I've had a look around the web and confirmed this is true; though I suspect it might be possible to disable per-site. I will be a good boy and add all those alt='' now. Thank you!\n- yet again that would be great if we could disable per site, i.e missing alt tag is equivalent to `alt=\"\"` but sadly we can't. No probs bud, good luck with the game!\n- Thanks! Note it might actually be `warning.pluginCode`. For ambiguous pluginCodes, just check in this way: `warning.message.includes('your error msg')`\n- how can I do it in sveltekit ?","metadata":{"transformedAt":"2026-08-18T18:33:40.679Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":100,"estimatedTokens":1063}}262{"id":"stack-72129162","source":"stackoverflow","questionId":72129162,"title":"Styling issues in monorepo with Turborepo, SvelteKit and Tailwind","tags":["tailwind-css","svelte","monorepo","sveltekit","turborepo"],"text":"Title: Styling issues in monorepo with Turborepo, SvelteKit and Tailwind\nTags: tailwind-css, svelte, monorepo, sveltekit, turborepo\nSource: Stack Overflow\n\nQuestion:\nI’ve created a monorepo with Turborepo that contains 2 SvelteKit apps and 2 packages: a component library (which is also based on SvelteKit) and a configuration package.\n\n```\nroot\n|\n|- packages\n| |- component-library\n| `- config\n|\n`- apps\n |- app1\n `- app2\n```\n\nThe *config* package contains the Tailwind and PostCSS config files, which are used in the component library and both apps.\n\nMy issue is that components imported from the *component-library* are displayed correctly in *app1* but appear to have issues with Tailwind classes in *app2*. Some classes are present but some are not. I’m using Tailwind in JIT mode.\n\nVersions of used packages:\n\n```\n\"turbo\": \"^1.2.4\",\n\"svelte\": \"^3.34.0\",\n\"@sveltejs/kit\": \"1.0.0-next.316\",\n\"tailwindcss\": \"3.0.23\",\n```\n\nI’m not even sure if this is because SvelteKit, but if anyone has experience with a similar Turborepo-SvelteKit-Tailwind setup I would appreciate some help.\n\n========================================\n\nTop Answer:\nIt turns out that I don't have to install tailwindcss-related packages in the root of monorepo.\n\nBut I have to add files of shared package (like component-library in the original question) to `tailwind.config.js`.\n\nSo in the `/apps/app1/tailwind.config.js`, below content should be added.\n\n```\n/** @type {import('tailwindcss').Config} */\nexport default {\n ...\n content: ['./src/**/*.{html,js,svelte,ts}', '../../packages/component-library/**/*.{html,js,svelte,ts}'],\n ...\n};\n```\n\n========================================\n\nCode:\n```text\nroot\n|\n|- packages\n| |- component-library\n| `- config\n|\n`- apps\n |- app1\n `- app2\n```\n\n```text\n\"turbo\": \"^1.2.4\",\n\"svelte\": \"^3.34.0\",\n\"@sveltejs/kit\": \"1.0.0-next.316\",\n\"tailwindcss\": \"3.0.23\",\n```\n\n```text\n\"devDependencies\": {\n \"autoprefixer\": \"^10.3.4\",\n \"postcss\": \"^8.2.15\",\n \"tailwindcss\": \"^3.1.4\",\n \"turbo\": \"^1.3.1\"\n}\n```\n\n```text\nmodule.exports = require('config/tailwind.config.cjs')\n```\n\n```text\ncontent: [\n '../../packages/component-library/src/**/*.{html,js,svelte,ts,svx}',\n './src/**/*.{html,js,svelte,ts,svx}'\n]\n```\n\n```text\npackage.json\n```\n\n```text\ntailwind.config.cjs\n```\n\n```text\napp\n```\n\n```text\ntailwind.config.cjs\n```\n\n```text\npackages/config/tailwind.config.cjs\n```\n\n```text\ncomponent-library\n```\n\n```text\n/** @type {import('tailwindcss').Config} */\nexport default {\n ...\n content: ['./src/**/*.{html,js,svelte,ts}', '../../packages/component-library/**/*.{html,js,svelte,ts}'],\n ...\n};\n```\n\n```text\ntailwind.config.js\n```\n\n```text\n/apps/app1/tailwind.config.js\n```\n\n========================================\n\nComments:\n- 0 This answer is not useful Show activity on this post. please could you include your `tailwind.config.js` or `tailwind.config.cjs` file content in your description.\n- Take a look at this answer: stackoverflow.com/a/78804843/6666348\n- Thanks for that @Adam. In my case, I only have one web app in the turbo repo so I only have one tailwind.config.js. Fortunately, you can just use relative paths for the content paths back up to the main `node_modules` folder.\n- [edited after 5 minutes so a new comment was needed...] Specifically, I needed the following to use `react-daisyui` ``` content: [ \"./app/**/*.{ts,tsx,jsx,js}\", \"../../node_modules/daisyui/dist/**/*.{ts,tsx,jsx,js}\", \"../../node_modules/react-daisyui/dist/**/*.{ts,tsx,jsx,js}\"‌​, ], ```\n- I'm not sure about how to connect DaisyUI with a monorepo but I don't think making Tailwind look for classes in files that are in `node-modules` is the best way. This in the `tailwind.config.js` should be enough to make it work I **think**: `content: ['./src/**/*.{js,ts,jsx,tsx}'], plugins: [require('daisyui')]`\n- This doesn’t make any sense. tailwind is a plugin to postcss, postcss is a plugin to sveltePreprocess, and sveltePreprocess is a plugin to vite. The apps encapsulate their own vite build environments within their workspaces. tailwind, autoprefixer and postcss should be defined as dependents within the application workspaces. How did you arrive at this conclusion and why does it work?\n- Also relative imports in the base config isn’t ideal because it requires that you that folder hierarchy. And it specifies that the dependent should also be depending on the UI package. It’s best to exclude context from the base config","metadata":{"transformedAt":"2026-08-18T18:33:40.679Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":145,"estimatedTokens":1118}}263{"id":"stack-70031167","source":"stackoverflow","questionId":70031167,"title":"Event type typescript for event handler in Svelte","tags":["typescript","types","svelte","svelte-3"],"text":"Title: Event type typescript for event handler in Svelte\nTags: typescript, types, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI'm using Typescript inside my svelte project, I need to define strong type for my event. But I can't find any way to do that.\n\n```\n\n const onKeyUp = (event: [type here]) => {\n console.log({ event })\n // const {target, keyCode} = event\n }\n\n```\n\nAnyone can help me!\n\n========================================\n\nTop Answer:\nThis is the only way I could do it:\n\n```\nconst handleKey = (e: CustomEvent) => {\n\n const event = e as unknown as KeyboardEvent;\n \n if (event.key === 'Backspace') {\n ...\n```\n\n```\n\n```\n\nI had to typecast.\n\nJ\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n const onKeyUp = (event: [type here]) => {\n console.log({ event })\n // const {target, keyCode} = event\n }\n</script>\n<input type=\"text\" on:keyup={onKeyUp} />\n```\n\n```html\n<script lang=\"ts\">\n const onKeyUp = (event: KeyboardEvent) => {\n // ...\n (event.target as HTMLInputElement)...;\n }\n</script>\n<input type=\"text\" on:keyup={onKeyUp} />\n```\n\n```text\nexport type WithTarget<Event, Target> = Event & { currentTarget: Target };\n```\n\n```html\n<script lang=\"ts\">\n import type { WithTarget } from './path/to/your/types/file.ts';\n const onKeyUp = (event: WithTarget<KeyboardEvent, HTMLInputElement>) => {\n // ...\n }\n</script>\n<input type=\"text\" on:keyup={onKeyUp} />\n```\n\n```text\nKeyboardEvent\n```\n\n```text\ntarget\n```\n\n```text\ncurrentTarget\n```\n\n```js\nconst handleKey = (e: CustomEvent) => {\n\n const event = e as unknown as KeyboardEvent;\n \n if (event.key === 'Backspace') {\n ...\n```\n\n```html\n<TextField bind:value on:keyup={handleKey}>\n```\n\n```ts\nconst handleKeyUp: KeyboardEventHandler<HTMLInputElement> = (event) => {\n console.log(event) // type KeyboardEvent\n console.log(event.target) // type EventTarget\n console.log(event.currentTarget) // type EventTarget & HTMLInputElement\n}\n```\n\n```text\nKeyboardEventHandler\n```\n\n```text\nHTMLInputElement\n```\n\n```text\nevent\n```\n\n```text\nKeyboardEvent\n```\n\n```text\nevent.target\n```\n\n```text\nEventTarget\n```\n\n```text\nevent.currentTarget\n```\n\n```text\nEventTarget & HTMLInputElement\n```\n\n```text\ntarget\n```\n\n```text\ncurrentTarget\n```\n\n========================================\n\nComments:\n- see also `React.MouseEvent` etc here and here\n- Seem to be it's wrong! Because the base `on:keyup` type of Svelte is `KeyboardEventHandler`. I received the typescript error like this: `Type '(event: WithTarget) => void' is not assignable to type 'KeyboardEventHandler'`\n- You are right, I adjusted my post.\n- This answer works perfectly. Thanks\n- Almost works great for me, I have currently `({ target : { value } }: WithTarget ) => debounce(value)` and now defined it as a function `const onKeyUp = (event:WithTarget) => { const target = event.target const value = target?.value debounce(value) }` but it complains about `target.value`","metadata":{"transformedAt":"2026-08-18T18:33:40.679Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":158,"estimatedTokens":732}}264{"id":"stack-59899928","source":"stackoverflow","questionId":59899928,"title":"Sapper/Svelte rollup/plugin-json giving error with stripejs","tags":["svelte","rollupjs","sapper"],"text":"Title: Sapper/Svelte rollup/plugin-json giving error with stripejs\nTags: svelte, rollupjs, sapper\nSource: Stack Overflow\n\nQuestion:\nI'm using sapper and stripejs. After installing stripejs using the command \"npm install stripe --save\" and followed the npm instruction to use the package:\n\n```\nimport Stripe from 'stripe';\n const stripe = new Stripe('mystripekey');\n```\n\nI get an error during reloading. This is a screenshot because I've never seen it before and I don't know how to fix this issue at all. It needs someone from the rollup team/expert and let us know how to fix it:\nhttps://i.sstatic.net/0uJw3.png\n\nI installed the plugin-json as per the instruction and it is showing in the rollup.config.js so it is not the stripe package but it seems that the rollup has a bug or is not processing something. \n\nHere is my rollup.config.js after installing the rollup plugin installation from this url : \n\n```\nimport resolve from '@rollup/plugin-node-resolve';\nimport replace from '@rollup/plugin-replace';\nimport commonjs from '@rollup/plugin-commonjs';\nimport svelte from 'rollup-plugin-svelte';\nimport babel from 'rollup-plugin-babel';\nimport { terser } from 'rollup-plugin-terser';\nimport config from 'sapper/config/rollup.js';\nimport pkg from './package.json';\nimport json from '@rollup/plugin-json';\n\nconst mode = process.env.NODE_ENV;\nconst dev = mode === 'development';\nconst legacy = !!process.env.SAPPER_LEGACY_BUILD;\n\nconst onwarn = (warning, onwarn) => (warning.code === 'CIRCULAR_DEPENDENCY' && /[/\\\\]@sapper[/\\\\]/.test(warning.message)) || onwarn(warning);\nconst dedupe = importee => importee === 'svelte' || importee.startsWith('svelte/');\n\nexport default {\n client: {\n input: config.client.input(),\n output: config.client.output(),\n plugins: [\n json(),\n replace({\n 'process.browser': true,\n 'process.env.NODE_ENV': JSON.stringify(mode)\n }),\n svelte({\n dev,\n hydratable: true,\n emitCss: true\n }),\n resolve({\n browser: true,\n dedupe\n }),\n commonjs(),\n\n legacy && babel({\n extensions: ['.js', '.mjs', '.html', '.svelte'],\n runtimeHelpers: true,\n exclude: ['node_modules/@babel/**'],\n presets: [\n ['@babel/preset-env', {\n targets: '> 0.25%, not dead'\n }]\n ],\n plugins: [\n '@babel/plugin-syntax-dynamic-import',\n ['@babel/plugin-transform-runtime', {\n useESModules: true\n }]\n ]\n }),\n\n !dev && terser({\n module: true\n })\n ],\n\n onwarn,\n },\n\n server: {\n input: config.server.input(),\n output: config.server.output(),\n plugins: [\n replace({\n 'process.browser': false,\n 'process.env.NODE_ENV': JSON.stringify(mode)\n }),\n svelte({\n generate: 'ssr',\n dev\n }),\n resolve({\n dedupe\n }),\n commonjs()\n ],\n external: Object.keys(pkg.dependencies).concat(\n require('module').builtinModules || Object.keys(process.binding('natives'))\n ),\n\n onwarn,\n },\n\n serviceworker: {\n input: config.serviceworker.input(),\n output: config.serviceworker.output(),\n plugins: [\n resolve(),\n replace({\n 'process.browser': true,\n 'process.env.NODE_ENV': JSON.stringify(mode)\n }),\n commonjs(),\n !dev && terser()\n ],\n\n onwarn,\n }\n};\n```\n\n**From the package install instruction:**\nI'm suppose to do this:\n\n```\n**Then call rollup either via the CLI or the API. \n With an accompanying file src/index.js, the local package.json file would \n now be importable as seen below:**\n\n// src/index.js\nimport pkg from './package.json';\nconsole.log(`running version ${pkg.version}`);\n```\n\nBut I don't have index.js file?...This is my project sapper structure:\n\nhttps://i.sstatic.net/U9MYE.png\n\nwithout that last step, it seems to break the whole thing because when I reload everything, I get this in the command prompt:\n\nhttps://i.sstatic.net/AleTn.png\n\nand opening the browser with localhost:3000/stripe gives me a 500 error\n\n```\nFailed to resolve module specifier \"http\". Relative references must start with either \"/\", \"./\", or \"../\".\n\nTypeError: Failed to resolve module specifier \"http\". Relative references must start with either \"/\", \"./\", or \"../\".\n```\n\nHow should I deal with this issue? I appreciate any help and I think this is a rollup configuration issue.\n\n========================================\n\nTop Answer:\nFor my scenario, problem was still persisting after installation of @rollup/plugin-json and config in rollup.config.js.\n\nI found out that rollup config has 2 sections: client and server and the problem is gone after adding json() config to plugin of both sections.\n\nHope can help someone.\n\n========================================\n\nCode:\n```text\nimport Stripe from 'stripe';\n const stripe = new Stripe('mystripekey');\n```\n\n```text\nimport resolve from '@rollup/plugin-node-resolve';\nimport replace from '@rollup/plugin-replace';\nimport commonjs from '@rollup/plugin-commonjs';\nimport svelte from 'rollup-plugin-svelte';\nimport babel from 'rollup-plugin-babel';\nimport { terser } from 'rollup-plugin-terser';\nimport config from 'sapper/config/rollup.js';\nimport pkg from './package.json';\nimport json from '@rollup/plugin-json';\n\nconst mode = process.env.NODE_ENV;\nconst dev = mode === 'development';\nconst legacy = !!process.env.SAPPER_LEGACY_BUILD;\n\nconst onwarn = (warning, onwarn) => (warning.code === 'CIRCULAR_DEPENDENCY' && /[/\\\\]@sapper[/\\\\]/.test(warning.message)) || onwarn(warning);\nconst dedupe = importee => importee === 'svelte' || importee.startsWith('svelte/');\n\nexport default {\n client: {\n input: config.client.input(),\n output: config.client.output(),\n plugins: [\n json(),\n replace({\n 'process.browser': true,\n 'process.env.NODE_ENV': JSON.stringify(mode)\n }),\n svelte({\n dev,\n hydratable: true,\n emitCss: true\n }),\n resolve({\n browser: true,\n dedupe\n }),\n commonjs(),\n\n legacy && babel({\n extensions: ['.js', '.mjs', '.html', '.svelte'],\n runtimeHelpers: true,\n exclude: ['node_modules/@babel/**'],\n presets: [\n ['@babel/preset-env', {\n targets: '> 0.25%, not dead'\n }]\n ],\n plugins: [\n '@babel/plugin-syntax-dynamic-import',\n ['@babel/plugin-transform-runtime', {\n useESModules: true\n }]\n ]\n }),\n\n !dev && terser({\n module: true\n })\n ],\n\n onwarn,\n },\n\n server: {\n input: config.server.input(),\n output: config.server.output(),\n plugins: [\n replace({\n 'process.browser': false,\n 'process.env.NODE_ENV': JSON.stringify(mode)\n }),\n svelte({\n generate: 'ssr',\n dev\n }),\n resolve({\n dedupe\n }),\n commonjs()\n ],\n external: Object.keys(pkg.dependencies).concat(\n require('module').builtinModules || Object.keys(process.binding('natives'))\n ),\n\n onwarn,\n },\n\n serviceworker: {\n input: config.serviceworker.input(),\n output: config.serviceworker.output(),\n plugins: [\n resolve(),\n replace({\n 'process.browser': true,\n 'process.env.NODE_ENV': JSON.stringify(mode)\n }),\n commonjs(),\n !dev && terser()\n ],\n\n onwarn,\n }\n};\n```\n\n```text\n**Then call rollup either via the CLI or the API. \n With an accompanying file src/index.js, the local package.json file would \n now be importable as seen below:**\n\n// src/index.js\nimport pkg from './package.json';\nconsole.log(`running version ${pkg.version}`);\n```\n\n```text\nFailed to resolve module specifier \"http\". Relative references must start with either \"/\", \"./\", or \"../\".\n\nTypeError: Failed to resolve module specifier \"http\". Relative references must start with either \"/\", \"./\", or \"../\".\n```\n\n```text\n...\n\"@rollup/plugin-json\": \"^4.0.0\",\n```\n\n```text\nimport json from '@rollup/plugin-json';\n\n...\n\nexport default {\n input: 'src/main.js',\n output: {\n ...\n },\n plugins: [\n json(), <<--------- HERE\n svelte({\n...\n```\n\n```text\nplugin-json\n```\n\n```text\nrollup\n```\n\n```text\nplugins\n```\n\n```text\npackage.json\n```\n\n```text\nrollup.config.js\n```\n\n========================================\n\nComments:\n- @Rich Harris We need your expertise here.\n- I think you have to put the rollup config in your question.\n- @V-Sambor Thank you for helping. I added everything you mentioned in your answer and now II'm getting http error. It seems we're close but now we broke the http model. I have no experience with rollup and I have no idea where is the conflict problem but I think it is rollup... Also, I added the rollup config file, and updated screenshots of all the project structure and error that I'm getting. Please review.\n- Hi @Marco, I think better would be if you can put your code on github into a public repository, so that people can try and help.. ;) Meanwhile Try to comment the lines with `dedupe` in resolve plugins (both client and server) and let me know if you see any difference\n- @V-Sambor Thank you. I will do that and update my question with the link to github.\n- From the code posted in the question. this was also likely the issue with the config (note no `json()` in server section)","metadata":{"transformedAt":"2026-08-18T18:33:40.680Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":345,"estimatedTokens":2363}}265{"id":"stack-59624611","source":"stackoverflow","questionId":59624611,"title":"How do I make a contentEditable on doubleclick using Svelte?","tags":["javascript","html","css","svelte","svelte-3"],"text":"Title: How do I make a contentEditable on doubleclick using Svelte?\nTags: javascript, html, css, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI'm brand new to **Svelte** (3.0+)...and for my latest project, I'd like to emulate the functionality of many \"todo\" lists that allow you to edit todo items previously submitted by double-clicking on them (Here's an example of the functionality I'm looking for).\n\nI imagine, the first step is figuring out how to make a div `contentEditable` with Svelte with the `on:dblclick` event handler. I'm having trouble figuring out the syntax for this task (though I can do it with vanilla javascript).\n\nHere's the Svelte code I have so far: ( Here it is on CodeSandBox.io - see page: CEDiv.svelte) \n\n```\n\nfunction edit(event) {\n //update db functionality goes here\n //alert(\"you've 'submitted' your edit\")\n}\n\nfunction handleDblClick() {\n //I need help HERE...and probably on the div on:dblclick down below....\n}\nfunction handleKeydown() {\n key = event.key;\n keyCode = event.keyCode;\n //submit the div's content to the edit function if enter or tab is pressed.\n keyCode == 13 || keyCode == 9 ? edit(event) : null;\n}\n\ndiv.read-mode {\n padding:10px;\n border:1px solid green;\n height:30px;\n line-height:30px;\n width:500px;\n margin:0 auto;\n}\ndiv.edit-mode {\n padding:10px;\n background: lightgreen;\n border:3px solid green;\n height:26px;\n line-height:26px;\n width:496px;\n margin:0 auto;\n}\n\n I want this Div to be editable one double click.\n\n```\n\nThanks in advance for your help!\n\n========================================\n\nCode:\n```text\n<script>\nfunction edit(event) {\n //update db functionality goes here\n //alert(\"you've 'submitted' your edit\")\n}\n\nfunction handleDblClick() {\n //I need help HERE...and probably on the div on:dblclick down below....\n}\nfunction handleKeydown() {\n key = event.key;\n keyCode = event.keyCode;\n //submit the div's content to the edit function if enter or tab is pressed.\n keyCode == 13 || keyCode == 9 ? edit(event) : null;\n}\n</script>\n<style>\ndiv.read-mode {\n padding:10px;\n border:1px solid green;\n height:30px;\n line-height:30px;\n width:500px;\n margin:0 auto;\n}\ndiv.edit-mode {\n padding:10px;\n background: lightgreen;\n border:3px solid green;\n height:26px;\n line-height:26px;\n width:496px;\n margin:0 auto;\n}\n</style>\n<div on:dblclick={handleDblClick} class=\"read-mode\" on:keydown={handleKeydown} contentEditable=\"false\">\n I want this Div to be editable one double click.\n</div>\n```\n\n```text\ncontentEditable\n```\n\n```text\non:dblclick\n```\n\n```text\nlet editable = false;\n```\n\n```text\nfunction handleDblClick(event) {\n editable = true; // or use editable=!editable to toggle\n}\n```\n\n```text\n<div \n on:dblclick={handleDblClick} \n class={editable ? 'edit-mode': 'read-mode'} \n on:keydown={handleKeydown}\n contenteditable={editable}>\n I want this Div to be editable on double click.\n</div>\n```\n\n```text\neditable\n```\n\n```text\n\"edit-mode\"\n```\n\n========================================\n\nComments:\n- You need to grab the div element associated with the clicked element then add a child input element, when editing is done, grab the value of the input element then remove the input element from the div.\n- This works well...and I think it's more \"officially\" Svelte...which is what I'm trying to learn. Thank you.\n- @Doomd yes, that's the \"data binding\" way Svelte inherited from predecessors. You're welcome.","metadata":{"transformedAt":"2026-08-18T18:33:40.680Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":138,"estimatedTokens":859}}266{"id":"stack-75259772","source":"stackoverflow","questionId":75259772,"title":"What's the correct way to dispatch/forward events across nested in components in Svelte?","tags":["javascript","events","svelte"],"text":"Title: What's the correct way to dispatch/forward events across nested in components in Svelte?\nTags: javascript, events, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm curious, what's the best way to forward or dispatch events across multiple levels in component tree in Svelte JS?\n\nSay I have App.Svelte, some intermediate number levels, each containing a child component, and Modal.Svelte. If I want to forward or dispatch an event from Modal to App, what's the right way to do this?\n\nAs I understand it, event forwarding in Svelte will traverse up the component tree and forward the event to the first parent that references the forwarded event. (Is this the correct interpretation?)\n\nAnd using event dispatch approach, each nested component would need to 1/ import createEventDispatcher, 2/ create a dispatcher variable, 3/ define a function, which dispatches the event. Then parent's would need to import the function and reference it inside a tag, such as ``. (Is this correct?)\n\nIf I'm correct on both of the above, I'm wondering if there isn't a more streamlined approach, eg connecting the event to stores, which would effectively flatten the component tree such that any component could receive the forwarded event. Though I imagine that this could induce some hard to debug behavior if multiple components reference the same forwarded event.\n\n========================================\n\nTop Answer:\nYou might consider instead using accessor functions. In App.svelte, define a function that manipulates your top-level variables. Then place that function in an accessor object and pass that down as a prop to all your components that may need it.\n\n```\n\n[App.svelte]\n\nlet myVar, myObj, myWhatever\n\nfunction updateMyVal(newValue) {\n myVar = newValue\n}\n\nfunction mergeMyObject(mergeObj) {\n myObj = {...myObj, ...mergeObj}\n}\n\nlet accessorObject = {\n updateMyVal: updateMyVal,\n mergeMyObject: mergeMyObject\n}\n\n. . .\n[ChildComponent.svelte]\n\n export let accessorObject, myVar, myObj\n\n accessorObject.updateMyVal(1234)\n\n accessorObject.mergeMyObject({newProp: newVal})\n\n```\n\nAnd so forth... this has the advantage of pushing changes to application-wide variables from the top down, which I've found to work better for complex SPAs than a web of events, two-way-bindings or stores, at least in my limited experience.\n\n========================================\n\nCode:\n```text\n<p>\n```\n\n```html\n<button on:click >\n<Component on:open >\n```\n\n```js\nsomeElement.dispatchEvent(\n new CustomEvent('my-event', { bubbles: true })\n);\n```\n\n```html\n<svelte:window on:my-event={() => ...} />\n```\n\n```text\non:event\n```\n\n```text\ncreateEventDispatcher\n```\n\n```text\nEventTarget\n```\n\n```text\non:event\n```\n\n```text\nwindow\n```\n\n```text\nsvelte:window\n```\n\n```text\n<script>\n[App.svelte]\n\nlet myVar, myObj, myWhatever\n\nfunction updateMyVal(newValue) {\n myVar = newValue\n}\n\nfunction mergeMyObject(mergeObj) {\n myObj = {...myObj, ...mergeObj}\n}\n\nlet accessorObject = {\n updateMyVal: updateMyVal,\n mergeMyObject: mergeMyObject\n}\n\n</script>\n\n<ChildComponent {accessorObject} {myVar} {myObj} />\n\n\n\n. . .\n[ChildComponent.svelte]\n<script>\n export let accessorObject, myVar, myObj\n\n accessorObject.updateMyVal(1234)\n\n accessorObject.mergeMyObject({newProp: newVal})\n</script>\n```\n\n========================================\n\nComments:\n- Can you shed some light on EventTarget, subscriptions and listeners? (And so using context would be an alternative to the former, right?)\n- The distinction would be between exporting an `EventTarget` instance from a file or setting it as context. An exported instance can be imported anywhere, it would be a singleton. All DOM elements are EventTargets, there is nothing special about creating one separately and using it to send/receive events. See the linked documentation for the relevant functions.\n- Here is an example for the global export/import approach. If subscriptions always happen on component initialization, code for adding/removing subscriptions could be extracted to make everything more concise.\n- Oh this is a really clever design pattern!\n- Is this the same as Prop drilling in React? The problem being if you want to pass it down several layers of the tree you need to put the `accessorObject` in every component prop list.\n- I don't know React, but yes, it does require you to add the accessor object to the prop list of every downstream that might need it. While that adds a few characters of boilerplate I haven't yet found a better way to maintain a sane reaction sequence in a complex SPA. It permits two-way (read/write, up/down) communication vertically through the stack, unlike events which are only up, or two-way bindings that get overly complex very quickly when nesting layers, or stores which don't impose any order on reaction flow. I'm always open for better ideas, but this model has been working well for me.\n- Yes, this is one of the primary ways to make React components talk to parents, however the main problem is that if you have a deep chain of nested components the prop you're trying to pass from the top down to the bottom obviously affects every component in-between creating a load of unnecessary dependencies. I believe context may solve this, but I've not really tried it yet. I'm currently experimenting with stores which seem similar to a pub/sub system I once wrote to solve this problem. I've also used (non-svelte) events to communicate over long component distances.\n- Absolutely. To balance I restrict the use of top-to-bottom communication to only the absolutely necessary and infrequently updated. Most component communication should be between a parent and an immediate child and there's no need to pass that from the top to all and sundry. Only things that are truly global (or nearly so) in consumption. I've only briefly glanced at context but at first glance it looks somewhat complicated. It's not the first time it's been suggested.","metadata":{"transformedAt":"2026-08-18T18:33:40.680Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":145,"estimatedTokens":1477}}267{"id":"stack-77161375","source":"stackoverflow","questionId":77161375,"title":"How to change +layout.svelte component on page navigation in svelte?","tags":["svelte","sveltekit"],"text":"Title: How to change +layout.svelte component on page navigation in svelte?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am new to svelte so I cannot figure this out how to solve this after many tries. Imagine I have a component `Navbar.svelte` in the `$lib/component`. As usual I will add this component to my `+layout.svelte` file. What I am trying to do is make this Navbar dynamic so that the content of the Navbar changes according to my page.\n\nThe idea comes from **Dynamic Island (Apple iPhone) and I want a navbar that is always stays on top and responsive like that**.\n\n(This is one of the reasons why I put my `` in +layout.svelte because I will be using page transitions and I don't want the navbar to be a part of the page transition, it will stay on top always visible) Here is an example taken from my project.\n\nFile: Navbar.svelte\n\n```\n \n \n Another Page \n \n\n### This is navbar for home\n\n \n \nFile: +layout.svelte\n\n```\n // imports \n \n \n\n```\n\nFile: +page.svelte\n\n```\n\n### This is a Home page\n\n```\n\nHow can I change the navbar when I click on the `/another-page` link so that in /another-page my navbar will contain only these:\n\n```\nHome \n\n### This is navbar for Another Page\n\n```\n\nI tried named slots but it seems like +layout.svelte only accepts one slot.\n\n========================================\n\nCode:\n```text\n<nav> \n <slot> \n <a href=\"/another-page\"> Another Page </a> \n <h1> This is navbar for home </h1> \n </slot> \n</nav\n```\n\n```text\n<script> // imports </script> \n<Navbar/> \n<slot/> \n<Footer/>\n```\n\n```text\n<h1> This is a Home page </h1>\n```\n\n```text\n<a href=\"/\"> Home </a> \n<h1> This is navbar for Another Page </h1>\n```\n\n```text\nNavbar.svelte\n```\n\n```text\n$lib/component\n```\n\n```text\n+layout.svelte\n```\n\n```text\n<Navbar/>\n```\n\n```text\n/another-page\n```\n\n```html\n<script>\n import './global.css';\n import currentNavBar from '../stores/currentNavBar.js';\n</script>\n\n<!-- UPDATE 2024-07-04: Wrap with an IF block in case no navbar is needed. -->\n{#if $currentNavBar}\n <svelte:component this={$currentNavBar} />\n{/if}\n\n<slot />\n```\n\n```html\nimport { writable } from 'svelte/store';\n\nexport default writable(undefined);\n```\n\n```html\n<script>\n import HomeNavBar from '$lib/NavBars/HomeNavBar.svelte';\n import currentNavbar from '../stores/currentNavBar.js';\n\n export let data;\n\n $currentNavbar = HomeNavBar;\n</script>\n```\n\n```html\n<script>\n import AnotherPageNavBar from '$lib/NavBars/AnotherPageNavBar.svelte';\n import currentNavBar from '../../stores/currentNavBar.js';\n\n $currentNavBar = AnotherPageNavBar;\n</script>\n\n<h1>This is Another Page</h1>\n```\n\n```text\n<svelte:component>\n```\n\n```text\nroutes/+layout.svelte\n```\n\n```text\ncurrentNavBar\n```\n\n```text\nHomeNavBar\n```\n\n```text\nAnotherPageNavBar\n```\n\n```text\nroutes/+page.svelte\n```\n\n```text\nHomeNavBar\n```\n\n```text\nroutes/anotherpage/+page.svelte\n```\n\n```text\nroutes/+layout.svelte\n```\n\n```text\nstores/currentNavBar.js\n```\n\n```text\nroutes/+page.svelte\n```\n\n```text\nroutes/anotherpage/+page.svelte\n```\n\n========================================\n\nComments:\n- Couple of notes: - I have to initialize store without **undefined** value - in a way: `export default writable()`, otherwise I got error 'Type 'typeof HomeNavBar__SvelteComponent_' is not assignable to type 'undefined'' when `$currentNavbar = HomeNavBar;` - when I go to any page that not suppose to have navbar, I ough to clean it, otherwise there will be ...PageNavBar from last navigated component that suppose to have one Me also new to svelte, and notes above makes me think if @José solution is cleanest and properest one. But at leest it's best I found yet, so huge thanks anyway\n- @BankAngle just wrap the `` element around an IF so you don't get an error. I'll update the answer.\n- now we nave `` is deprecated in runes mode — components are dynamic by default svelte.dev/docs/svelte/…. If I got it correctly, we could now just use , but that's not work, or at least I cannot figure out what I'm doing wrong\n- @bankangle camel-case variables are treated as custom elements, if I recall correctly. Use `CurrentNavBar`. A Pascal-cased variable should work.","metadata":{"transformedAt":"2026-08-18T18:33:40.680Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":25,"totalLines":196,"estimatedTokens":1042}}268{"id":"stack-63653518","source":"stackoverflow","questionId":63653518,"title":"Passing data between sibling components in Svelte","tags":["svelte","svelte-component","svelte-store","routify"],"text":"Title: Passing data between sibling components in Svelte\nTags: svelte, svelte-component, svelte-store, routify\nSource: Stack Overflow\n\nQuestion:\nHow to pass data (ex: Navbar Title) to a component used in the parent element?\n\n```\n\n import Nav from \"../components/Nav.svelte\";\n let navTitle = \"MyApp\";\n\n```\n\n```\n\n export let navTitle = \"\";\n\n### {navTitle}\n\n```\n\n```\n\nHow to pass navTitle value from here to Nav.svelte?\n```\n\nTo clarify, this needs to be scalable and to work on page load/transition for all routes of an SPA using Routify, preferably providing a default value and be able to have HTML value:\n\n```\n\n```\n\n```\n\nnavTitle is 'My Account'\n```\n\n```\n\n```\n\n========================================\n\nTop Answer:\nYou can pass a function to `Login.svelte` component\n\n```\n\n import Nav from \"./Nav.svelte\";\n import Login from \"./Login.svelte\"\n let navTitle = \"MyApp\";\n const onlogin= (v)=>navTitle = v\n\n```\n\nAnd call the passed function in the `Login.svelte`\n\n```\n\nexport let onlogin\n\nonlogin(\"Logged in\")}>\n click me to login\n\n```\n\nHere is the REPL: https://svelte.dev/repl/f1c8777df93f414ab26734013f2c4789?version=3\n\nThere are other (better) ways to do this like:\n\n- Custom events with `createEventDispatcher`\n\n- Stores\n\n- Context (`setContext`, `getContext`)\n\n- Multiple Redux-adaptations for svelte\n\n========================================\n\nCode:\n```text\n<!-- _layout.svelte -->\n<script>\n import Nav from \"../components/Nav.svelte\";\n let navTitle = \"MyApp\";\n</script>\n\n<Nav {navTitle}/>\n<slot />\n```\n\n```text\n<!-- Nav.svelte -->\n<script>\n export let navTitle = \"\";\n</script>\n<h1>{navTitle}</h1>\n```\n\n```text\n<!-- Login.svelte -->\nHow to pass navTitle value from here to Nav.svelte?\n```\n\n```text\n<!-- Article.svelte -->\n```\n\n```text\n<!-- User.svelte -->\nnavTitle is '<a href=\"/user\">My Account </a>'\n```\n\n```text\n<!-- Comment.svelte -->\n```\n\n```html\n<!-- Nav.svelte -->\n<script>\n import { navTitle } from './store.js'\n</script>\n<h1>{$navTitle}</h1>\n```\n\n```html\n<!-- Login.svelte -->\n<script>\n import { navTitle } from './store.js'\n\n navTitle.set('...')\n</script>\n```\n\n```js\n<!-- store.js -->\nimport { writable } from 'svelte/store'\n\nexport const navTitle = writable('')\n```\n\n```text\n<script>\n import Nav from \"./Nav.svelte\";\n import Login from \"./Login.svelte\"\n let navTitle = \"MyApp\";\n const onlogin= (v)=>navTitle = v\n</script>\n<Login {onlogin}/>\n<Nav {navTitle}/>\n```\n\n```text\n<script>\nexport let onlogin\n</script>\n\n<p on:click={()=>onlogin(\"Logged in\")}>\n click me to login\n</p>\n```\n\n```text\nLogin.svelte\n```\n\n```text\nLogin.svelte\n```\n\n```text\ncreateEventDispatcher\n```\n\n```text\nsetContext\n```\n\n```text\ngetContext\n```\n\n========================================\n\nComments:\n- You can use also two-way binding for this, but it should be avoided (you’ll mess your dataflow pretty quickly). In App.svelte `` and in Login.svelte `export let navTitle` and `navTitle=(\"Logged in\")}>` Key-word is `bind:`, which makes two-way binding to `navTitle` variable ie. when variable changes in one place, it’ll change also other places.\n- Thank you for the answer, @stephane. I updated the question to clarify scalability and default values issues. Would you make any updates to your suggestion? For example, Routify allows to set metatag.title on pages by simply using `$: metatags.title = \"Log in\";`\n- You can import *navTitle* wherever in your app you want to be able to set it and then set it similar to how you set it in Routify\n- $navTitle seems to be escaping HTML and only showing text. Is there a way to pass HTML to it?\n- Svelte automatically escapes texts, if you want to override this you can use `{@html $navTitle}` but when doing that you have to make sure it is always safe to do so (outputting unescaped html can be a source for XSS)","metadata":{"transformedAt":"2026-08-18T18:33:40.680Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":192,"estimatedTokens":938}}269{"id":"stack-52063652","source":"stackoverflow","questionId":52063652,"title":"Importing local json in main.js in Svelte","tags":["json","svelte"],"text":"Title: Importing local json in main.js in Svelte\nTags: json, svelte\nSource: Stack Overflow\n\nQuestion:\nWhat is the pattern for importing JSON into Svelte's main.js file?\n\nI'm trying:\n\n```\nimport App from './App.html';\nconst dataset = require('./../posts.json');\n\nconsole.log(dataset);\n\nconst app = new App({\n target: document.body,\n data: dataset\n});\n\nexport default app;\n```\n\nBut this does not resolve as JSON cannot be imported as an es6 module.\n\n========================================\n\nCode:\n```text\nimport App from './App.html';\nconst dataset = require('./../posts.json');\n\nconsole.log(dataset);\n\nconst app = new App({\n target: document.body,\n data: dataset\n});\n\nexport default app;\n```\n\n========================================\n\nComments:\n- moved to @rollup/plugin-json\n- I use SvelteKit and import `.json` to `svelte.config.js` I get type error, unknown file extension `.json` How to fix?","metadata":{"transformedAt":"2026-08-18T18:33:40.680Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":47,"estimatedTokens":225}}270{"id":"stack-60734783","source":"stackoverflow","questionId":60734783,"title":"Use svelte css class in @html","tags":["svelte"],"text":"Title: Use svelte css class in @html\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI have an api that returns html with classes, I want to know how I can use svelte style definition for those.\n\nApp.Svelte\n\n```\n\n let string = `ok`;\n\n{@html string}\n\n .status {\n color: red\n }\n\n... \n\n{@html marked}\n```\n\nReturns\n`Unused CSS selector (8:1)`\n\n========================================\n\nTop Answer:\nI was trying to do this with the h2 tag, since I am integrating tincyMCE in a svelte app that is using 'flowbite-svelte'. What worked for me was:\n\n```\n:global(.content h2) {\n font-size: 1.5em;\n }\n```\n\nWhere 'content' was my div class.\n\n========================================\n\nCode:\n```text\n<script>\n let string = `<span class=\"status\">ok</span>`;\n</script>\n\n<p>{@html string}</p>\n\n<style>\n .status {\n color: red\n }\n</style>\n... \n\n{@html marked}\n```\n\n```text\nUnused CSS selector (8:1)\n```\n\n```html\n<style>\n .wrapper > :global(.status) {\n }\n</style>\n\n<div class=\"wrapper\">\n {@html marked}\n</div>\n```\n\n```text\nstatus\n```\n\n```text\n:global(.status) { }\n```\n\n```text\n:global(.content h2) {\n font-size: 1.5em;\n }\n```\n\n```text\nroutes/app\n +layout.svelte\n /subpages\n /portal\n +layout.svelte\n /subpages\n /marketing\n +layout.svelte\n /subpages\n```\n\n```text\n<script>\n import \"../styles/marketing.styl\"\n</script>\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.680Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":106,"estimatedTokens":344}}271{"id":"stack-56403072","source":"stackoverflow","questionId":56403072,"title":"How do you create routes with optional parameters in Sapper?","tags":["svelte","sapper"],"text":"Title: How do you create routes with optional parameters in Sapper?\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nLet's say I have a `/foo` route. But sometimes people hit `/foo` with a language parameter: `/fr/foo`. And other times they might hit it with a language and a country: `/ca/fr/foo` \n\nSo I need a routing table like \n\n```\n[country]/[language]/foo \n[language]/foo \n/foo\n```\n\nThat all direct to the same page. \n\nShould I create a tree like this?\n\n```\nsrc/routes\n└── [country]\n └── [language]\n └── foo.svelte\n```\n\nIf that's the answer then how do I direct `[language]/foo` to `[country]/[language]/foo`? \n\nI don't see any optional params in the docs\n\n========================================\n\nTop Answer:\nIn my case I needed /dashboard/reset/TOKEN/ID route. I made it worked with the following structure:\n\n```\n[acool@localhost cool-sapper-project]$ tree src/routes/\nsrc/routes/\n├── dashboard\n│ ├── reset\n│ │ └── [...parts].svelte\n```\n\nThe above will make TOKEN and ID parameters available in `params` in your page:\n\n```\n\n export async function preload({ params }, session) {\n console.log(JSON.stringify(params));\n}\n\n```\n\nOutput:\n\n```\n{\"parts\":[\"2fd4e1c67a2d28fced849ee1bb76e7391b93eb12\",\"1\"]}\n```\n\nGood Luck!\n\n========================================\n\nCode:\n```text\n[country]/[language]/foo \n[language]/foo \n/foo\n```\n\n```text\nsrc/routes\n└── [country]\n └── [language]\n └── foo.svelte\n```\n\n```text\n/foo\n```\n\n```text\n/foo\n```\n\n```text\n/fr/foo\n```\n\n```text\n/ca/fr/foo\n```\n\n```text\n[language]/foo\n```\n\n```text\n[country]/[language]/foo\n```\n\n```text\nroutes/[...parts]/foo.svelte\n```\n\n```text\nfoo.svelte\n```\n\n```text\npage.params.parts\n```\n\n```text\n/foo\n```\n\n```text\n[acool@localhost cool-sapper-project]$ tree src/routes/\nsrc/routes/\n├── dashboard\n│ ├── reset\n│ │ └── [...parts].svelte\n```\n\n```text\n<script context=\"module\">\n export async function preload({ params }, session) {\n console.log(JSON.stringify(params));\n}\n</script>\n```\n\n```text\n{\"parts\":[\"2fd4e1c67a2d28fced849ee1bb76e7391b93eb12\",\"1\"]}\n```\n\n```text\nparams\n```\n\n```text\nsrc/routes\n└── [country]\n └── [[language]]\n └── foo.svelte\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.680Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":147,"estimatedTokens":535}}272{"id":"stack-67873142","source":"stackoverflow","questionId":67873142,"title":"How to listen the state changes in svelte like useEffect","tags":["state","use-effect","svelte"],"text":"Title: How to listen the state changes in svelte like useEffect\nTags: state, use-effect, svelte\nSource: Stack Overflow\n\nQuestion:\nI have read some article about state change listener, As I am a very beginner to the svelte environment I can't figure out what is the most efficient way to listen to the state change.\n\nLet us take state variable as `X` and `Y`\n\n### Method 1:\n\n```\n$: if (X||Y) {\n console.log(\"yes\");\n}\n```\n\n### Method 2:\n\nUse a combination of `afterUpdate` and `onDestroy`\n\nREPL: https://svelte.dev/repl/300c16ee38af49e98261eef02a9b04a8?version=3.38.2\n\n```\nimport { afterUpdate, onDestroy } from 'svelte';\n\nexport function useEffect(cb, deps) {\n let cleanup;\n \n function apply() {\n if (cleanup) cleanup();\n cleanup = cb();\n }\n \n if (deps) {\n let values = [];\n afterUpdate(() => {\n const new_values = deps();\n if (new_values.some((value, i) => value !== values[i])) {\n apply();\n values = new_values;\n }\n });\n } else {\n // no deps = always run\n afterUpdate(apply);\n }\n \n onDestroy(() => {\n if (cleanup) cleanup();\n });\n}\n```\n\n### Method 3:\n\nUse `writable` and `subscribe`\n\n```\n\nimport { writable } from 'svelte/store';\nconst X = writable(0);\nconst Y = writable(0);\n\nX.subscribe(value => {\n console.log(\"X was changed\", value);\n});\n\nY.subscribe(value => {\n console.log(\"Y was changed\", value);\n});\n\n{\n X.update((val)=>val++)\n}}>Change X\n{\n Y.update((val)=>val++)\n}}>Change Y\n```\n\n========================================\n\nTop Answer:\nHow about this?\n\n```\n\n let count = 0;\n \n $: doubled = (() => {\n return count * 2\n })()\n\n function handleClick() {\n count += 1;\n }\n\n Clicked {count} {count === 1 ? 'time' : 'times'}\n\n{count} doubled is {doubled}\n\n```\n\n========================================\n\nCode:\n```js\n$: if (X||Y) {\n console.log(\"yes\");\n}\n```\n\n```js\nimport { afterUpdate, onDestroy } from 'svelte';\n\nexport function useEffect(cb, deps) {\n let cleanup;\n \n function apply() {\n if (cleanup) cleanup();\n cleanup = cb();\n }\n \n if (deps) {\n let values = [];\n afterUpdate(() => {\n const new_values = deps();\n if (new_values.some((value, i) => value !== values[i])) {\n apply();\n values = new_values;\n }\n });\n } else {\n // no deps = always run\n afterUpdate(apply);\n }\n \n onDestroy(() => {\n if (cleanup) cleanup();\n });\n}\n```\n\n```html\n<script>\nimport { writable } from 'svelte/store';\nconst X = writable(0);\nconst Y = writable(0);\n\n\nX.subscribe(value => {\n console.log(\"X was changed\", value);\n});\n\n\nY.subscribe(value => {\n console.log(\"Y was changed\", value);\n});\n\n</script>\n\n<button on:click={(e)=>{\n X.update((val)=>val++)\n}}>Change X</button>\n<button on:click={(e)=>{\n Y.update((val)=>val++)\n}}>Change Y</button>\n```\n\n```text\nX\n```\n\n```text\nY\n```\n\n```text\nafterUpdate\n```\n\n```text\nonDestroy\n```\n\n```text\nwritable\n```\n\n```text\nsubscribe\n```\n\n```text\n// Svelte\n// doubled will always be twice of single. If single updates, doubled will run again.\n$: doubled = single * 2\n\n// equivalent to this React\n\nlet single = 0\nconst [doubled, setDoubled] = useState(single * 2)\n\nuseEffect(() => {\n setDoubled(single * 2)\n}, [single])\n```\n\n```text\n<script>\n let value = ''\n $: console.log(value)\n</script>\n\n<input type='text' name='name' bind:value />\n```\n\n```text\n$: if(x || y) console.log('yes')\n```\n\n```text\n<script>\n let count = 1;\n $: console.log(count)\n</script>\n\n<input type=\"number\" bind:value={count}>\n```\n\n```text\n<script>\n let x = 0\n let y = 0\n\n $: console.log('x was changed', x)\n $: console.log('y was changed', y)\n</script>\n\n<button on:click={() => x++}>Change x</button>\n<button on:click={() => y++}>Change x</button>\n```\n\n```text\nx\n```\n\n```text\ny\n```\n\n```text\nuseEffect\n```\n\n```text\ncontext\n```\n\n```text\nuseEffect\n```\n\n```text\ncontext\n```\n\n```text\nstores\n```\n\n```text\n<script>\n let count = 0;\n \n $: doubled = (() => {\n return count * 2\n })()\n\n function handleClick() {\n count += 1;\n }\n</script>\n\n<button on:click={handleClick}>\n Clicked {count} {count === 1 ? 'time' : 'times'}\n</button>\n\n<p>{count} doubled is {doubled}</p>\n```\n\n========================================\n\nComments:\n- What is most efficient depends on your use case. There isn't a one-size-fits-all solution to this.\n- The common way is method 1, why make it more complicated ?\n- When I try to use Method 1, it doesn't fire always. svelte.dev/repl/3cb4c229c334488883db49383656ec26?version=3.3‌​8.2\n- The code you link has an error as it uses the undefined variable `name`\n- yes and it always fires doesn't it ?\n- Yes, it works fine. But JSHeap memory keeps getting increasing. imgur.com/BrsbTjN\n- I don't see anything suspicious in that graph. Garbage collection runs from time to time, not immediately when the space is no longer needed. Also keep in mind that you are running this code inside the REPL, this cannot be compared to running the code in your own app.\n- Yeah understood\n- The first method could be `$: x, y, console.log('yes')`. It might be less readable but it eliminates the subtle bug you mentioned. svelte.dev/repl/319aac5e49714b72b5119fd6480d9c64\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:40.680Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":304,"estimatedTokens":1353}}273{"id":"stack-74915712","source":"stackoverflow","questionId":74915712,"title":"SvelteKit: cookies.set() In Form Action Not Working","tags":["javascript","cookies","jwt","svelte","sveltekit"],"text":"Title: SvelteKit: cookies.set() In Form Action Not Working\nTags: javascript, cookies, jwt, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement JWT-based user sessions with SvelteKit, and have mostly been following the explanation for form actions given on their website: https://kit.svelte.dev/docs/form-actions\n\n+page.svelte\n\n```\n\n \n \n Submit\n\n```\n\n+page.server.svelte\n\n```\nimport { fail, redirect } from \"@sveltejs/kit\";\nimport { signIn } from \"$lib/server/database\";\n\nexport const actions = {\n signIn: async ({ cookies, request }) => {\n const data = await request.formData();\n\n const name = data.get(\"name\");\n const password = data.get(\"password\");\n\n if (!name || !password) {\n return fail(400);\n }\n\n try {\n cookies.set(\"jwt\", await signIn(name, password));\n } catch (error) {\n return fail(400);\n }\n\n throw redirect(303, \"/\");\n },\n};\n```\n\nI have tested my `signIn` method which I import and use here, and it does return a token when called with the correct credentials. So far, so good. However, I noticed that I don't see any cookies in my developer tools. It seems like the `cookies.set()` call simply does nothing. I'd like to set the returned JWT as a cookie so that I can authenticate my users, so what am I doing wrong?\n\n========================================\n\nCode:\n```js\n<form method=\"POST\" action=\"?/signIn\">\n <input type=\"text\" name=\"name\" />\n <input type=\"password\" name=\"password\" />\n <button type=\"submit\">Submit</button>\n</form>\n```\n\n```js\nimport { fail, redirect } from \"@sveltejs/kit\";\nimport { signIn } from \"$lib/server/database\";\n\nexport const actions = {\n signIn: async ({ cookies, request }) => {\n const data = await request.formData();\n\n const name = data.get(\"name\");\n const password = data.get(\"password\");\n\n if (!name || !password) {\n return fail(400);\n }\n\n try {\n cookies.set(\"jwt\", await signIn(name, password));\n } catch (error) {\n return fail(400);\n }\n\n throw redirect(303, \"/\");\n },\n};\n```\n\n```text\nsignIn\n```\n\n```text\ncookies.set()\n```\n\n```text\nsecure\n```\n\n========================================\n\nComments:\n- Have you tried setting the cookie for the root path? `cookies.set(\"jwt\", await signIn(name, password), { path: \"/\" });`\n- I just tried that, there are still no cookies in sight.\n- Shoot, that's frustrating. Have you tried cloning the `realworld` example and checked if that sets a cookie for you? If it does, you could compare that code to yours. If it does not, maybe you have disabled cookies in your browser in some way.\n- Thanks, that actually helped me find the problem: Apparently, I just can't set cookies in this browser. Which confuses me, because I just did today, but that was with another framework. But the realworld example also doesn't work for me, so it's my browser. I'm just going to try and find the setting for that and change it.\n- You might want to specify a cookie options object in your `cookies.set` call. By default, SvelteKit sets the `httpOnly` and `secure` flags to `true` (`secure` is set to `false` if running on `localhost`) which might interfere with your ability to transmit to, and read the cookie back on the client side. See kit.svelte.dev/docs/types#public-types-cookies.\n- Sorry for my late response, but these options shouldn't prevent the cookie from being *set* in the first place, right? Because I'm just using my dev tools to check for the cookie, and it's simply not there. Even with these options set, it should show up, shouldn't it?\n- I tried around a little, and noticed that while the cookies are not set when I use Safari (which is my normal browser), they are set when using Chrome. However, on my phone, Chrome doesn't work, Safari doesn't work, and Firefox also doesn't work. So I get the impression that this `cookies.set` method doesn't work in most browsers...\n- I had this problem too, but in Firefox on Linux.","metadata":{"transformedAt":"2026-08-18T18:33:40.680Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":107,"estimatedTokens":973}}274{"id":"stack-69500584","source":"stackoverflow","questionId":69500584,"title":"Svelte: How to handle the custom writable store's async init's promise in the component?","tags":["svelte","svelte-3","svelte-component","svelte-store"],"text":"Title: Svelte: How to handle the custom writable store's async init's promise in the component?\nTags: svelte, svelte-3, svelte-component, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI have several Svelte components and a custom writable store. The store has an `init` function which is `async` and which fills the store's value with some REST API's db's table's data. My components must all subscribe to this store by using autosubscription. At subscription, `init` must be called. The global idea is to implement CRUD operations on the db with CRUD operations on the store (useful to show the store's value, *i.e.* the db's table, with reactivity).\n\nAs `init` is `async` and, thus, returns a promise, I need to `await` it in my components. But since I use autosubscription (by prefixing the store name with `$`), how can I do that?\n\nFor example: `App.svelte` (the component):\n\n```\n\n import { restaurant_store } from './Restaurant.js'\n export let name\n\n \n\n \n {#each $restaurant_store as restaurant}\n \n {restaurant.name}\n \n {/each}\n\n```\n\n`Restaurant.js` (the store):\n\n```\nimport { writable } from 'svelte/store'\n \nexport function createRestaurantsStore() {\n const { subscribe, update } = writable({ collection: [] })\n \n return {\n subscribe,\n init: async () => {\n const response = await fetch('http://localhost:1337/restaurants')\n \n if(response.ok) {\n const json_response = await response.json()\n set({ collection: json_response })\n return json_response\n }\n throw Error(response.statusText)\n },\n insert: async (restaurant) => {\n const response = await fetch('http://localhost:1337/restaurants', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(restaurant)\n })\n \n if(response.ok) {\n const json_response = await response.json()\n update(store_state => store_state.collection.push(json_response))\n return json_response\n }\n throw Error(response.statusText)\n },\n \n update: async (restaurant, id) => {\n const response = await fetch('http://localhost:1337/restaurants/' + id, {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(restaurant)\n })\n \n if(response.ok) {\n const json_response = await response.json()\n update(store_state => {\n const current_id = store_state.collection.findIndex(e => e.id === id)\n store_state.collection.splice(current_id, 1, json_response)\n })\n return json_response\n }\n throw Error(response.statusText)\n }\n }\n}\n \nexport const restaurant_store = createRestaurantsStore()\n```\n\n========================================\n\nCode:\n```js\n<script>\n import { restaurant_store } from './Restaurant.js'\n export let name\n</script>\n \n<main>\n <!--- I need to handle the promise and rejection here -->\n {#each $restaurant_store as restaurant}\n <li>\n {restaurant.name}\n </li>\n {/each}\n</main>\n```\n\n```js\nimport { writable } from 'svelte/store'\n \nexport function createRestaurantsStore() {\n const { subscribe, update } = writable({ collection: [] })\n \n return {\n subscribe,\n init: async () => {\n const response = await fetch('http://localhost:1337/restaurants')\n \n if(response.ok) {\n const json_response = await response.json()\n set({ collection: json_response })\n return json_response\n }\n throw Error(response.statusText)\n },\n insert: async (restaurant) => {\n const response = await fetch('http://localhost:1337/restaurants', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(restaurant)\n })\n \n if(response.ok) {\n const json_response = await response.json()\n update(store_state => store_state.collection.push(json_response))\n return json_response\n }\n throw Error(response.statusText)\n },\n \n update: async (restaurant, id) => {\n const response = await fetch('http://localhost:1337/restaurants/' + id, {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(restaurant)\n })\n \n if(response.ok) {\n const json_response = await response.json()\n update(store_state => {\n const current_id = store_state.collection.findIndex(e => e.id === id)\n store_state.collection.splice(current_id, 1, json_response)\n })\n return json_response\n }\n throw Error(response.statusText)\n }\n }\n}\n \nexport const restaurant_store = createRestaurantsStore()\n```\n\n```text\ninit\n```\n\n```text\nasync\n```\n\n```text\ninit\n```\n\n```text\ninit\n```\n\n```text\nasync\n```\n\n```text\nawait\n```\n\n```text\n$\n```\n\n```text\nApp.svelte\n```\n\n```text\nRestaurant.js\n```\n\n```html\n<main>\n {#await restaurant_store.init()}\n <p>waiting for the promise to resolve...</p>\n {:then}\n {#each $restaurant_store as restaurant}\n <li>\n {restaurant.name}\n </li>\n {/each}\n {:catch error}\n <p>Something went wrong: {error.message}</p>\n {/await}\n</main>\n```\n\n========================================\n\nComments:\n- Ah ok I didn't understand `init` function would not be called automatically by the store when defined. Thank you!\n- That REPL isn't actually working. It should also be noted that if you set/update on $restaurant_store, with that example the contents of the #await block will not be shown again. Here is a REPL that will re-show the contents of the #await block any time you update the store svelte.dev/repl/d78d7327830442ab87cc47bcee1033f9?version=3.4‌​3.1","metadata":{"transformedAt":"2026-08-18T18:33:40.681Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":225,"estimatedTokens":1459}}275{"id":"stack-67255874","source":"stackoverflow","questionId":67255874,"title":"Where should I refresh my JWT in SvelteKit","tags":["javascript","jwt","svelte","sveltekit"],"text":"Title: Where should I refresh my JWT in SvelteKit\nTags: javascript, jwt, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implement JWT authentication in a SvelteKit-app and I'm having trouble with where in the code I should refresh my accesstoken on site-reload.\nAccording to what I have found I should store the JWT in memory and then have a refresh-token that is stored as a HTTP-only cookie. When the page is reloaded or opened in a new tab, I need to call my backend to see if the refresh-token is valid or not, if it is, I will generate a new JWT and return it to the client.\n\nWhere is a good idea to make this call? I was thinking that the `getSession`-hook would be a good place but I'm not able to use `fetch` from there.\n\n========================================\n\nCode:\n```text\ngetSession\n```\n\n```text\nfetch\n```\n\n```text\nSet-Cookie\n```\n\n```text\nhandle()\n```\n\n```text\ngetSession()\n```\n\n```text\ncontext\n```\n\n```text\nhandle()\n```\n\n```text\ngetContext()\n```\n\n```text\nhandle()\n```\n\n```text\nhandle()\n```\n\n```text\nhandle()\n```\n\n```text\nrequest.context\n```\n\n```text\nfetch\n```\n\n```text\nnode-fetch\n```\n\n```text\npackage.json\n```\n\n```text\nSet-Cookie\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.681Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":76,"estimatedTokens":292}}276{"id":"stack-70980379","source":"stackoverflow","questionId":70980379,"title":"SvelteKit(ViteJS) + TailwindCSS not hot reloading components","tags":["tailwind-css","svelte","vite","sveltekit"],"text":"Title: SvelteKit(ViteJS) + TailwindCSS not hot reloading components\nTags: tailwind-css, svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm trying to code an app using TailwindCSS and SvelteKit, which uses ViteJS under the hood, and while coding I realized that my *Header* component that is inside `./src/components/common/Header.svelte` was not **hot reloading** on changes. No matter how big or small the change to the component, Svelte would not display them until I terminated script in the console and re-ran `npm run dev`.\n\nThe normal behaviour would be that the whole page updated **WITH** changes to the components other than pages.\n\n*Note that adding and removing changes to any routes the changes are instantly visible but the components stay the same.*\n\nThis issue got quite annoying after some time and I tried finding the fix in TailwindCSS and in the `svelte.config.js` (Not a .cjs file in Svelte-Kit) file.\n\nAfter searching for a ton of answers I could not find anything that worked.\n\nThis behaviour is quite weird since in the other projects that I work on that use this same architecture of TailwindCSS and Svelte-kit the HMR works like a charm.\n\nHere is the code for my `Header.svelte` file and the `__layout.svelte`\n\n***Header.svelte***\n\n```\n\n \n \n \n \n \n- Home\n \n- About\n \n- Contact\n \n \n- Random Change\n \n \n\n```\n\n**__layout.svelte**\n\n```\n\n import '../css/tailwind.css';\n import Header from '../components/common/Header.svelte';\n\n```\n\nalso my config files:\n\n***tailwind.config.cjs***\n\n```\nmodule.exports = {\n content: ['./src/**/*.svelte', './src/app.html'],\n plugins: []\n};\n```\n\n***svelte.config.js***\n\n```\nimport preprocess from 'svelte-preprocess';\nimport path from 'path';\n\n// @type {import('@sveltejs/kit').Config\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: preprocess(),\n\n kit: {\n vite: {\n resolve: {\n alias: {\n '@components': path.resolve('./src/components'),\n '@routes': path.resolve('./src/routes'),\n '@utils': path.resolve('./src/utils'),\n '@data': path.resolve('./src/data')\n }\n }\n }\n }\n};\n\nexport default config;\n```\n\n========================================\n\nCode:\n```html\n<script>\n</script>\n\n<header>\n <!-- TEST HEADER -->\n <nav>\n <ul class=\"flex gap-5 bg-red-500\">\n <!--These classes are tests and won't change the appearance of the Header unless I restart the script-->\n <li><a href=\"/\">Home</a></li>\n <li><a href=\"/about\">About</a></li>\n <li><a href=\"/contact\">Contact</a></li>\n <!--Other random change that won't update-->\n <li>Random Change</li>\n </ul>\n </nav>\n</header>\n```\n\n```html\n<script>\n import '../css/tailwind.css';\n import Header from '../components/common/Header.svelte';\n</script>\n\n<Header />\n<slot />\n```\n\n```js\nmodule.exports = {\n content: ['./src/**/*.svelte', './src/app.html'],\n plugins: []\n};\n```\n\n```js\nimport preprocess from 'svelte-preprocess';\nimport path from 'path';\n\n\n// @type {import('@sveltejs/kit').Config\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: preprocess(),\n\n kit: {\n vite: {\n resolve: {\n alias: {\n '@components': path.resolve('./src/components'),\n '@routes': path.resolve('./src/routes'),\n '@utils': path.resolve('./src/utils'),\n '@data': path.resolve('./src/data')\n }\n }\n }\n }\n};\n\nexport default config;\n```\n\n```text\n./src/components/common/Header.svelte\n```\n\n```text\nnpm run dev\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nHeader.svelte\n```\n\n```text\n__layout.svelte\n```\n\n========================================\n\nComments:\n- I know this is unhelpful, but I put all this code into a SvelteKit project with Tailwind configured and HMR worked fine in `Header.svelte`. Perhaps you could isolate the offending code by starting with a fresh SvelteKit project and seeing if HMR works, then install Tailwind, then make the changes in `svelte.config.js`—something is not right but I don't think it is included in what you posted here.\n- Yeah seems to work. That's odd. I'll have to take a look at my dependencies.\n- I have the same problem. I work with Svelte (not SvelteKit), Tailwind and Vite. Right now I force a restart with \"vite-plugin-restart\"\n- Do you have any updates on that problem? I was not able to solve this. Somewhere else here on Stackoverflow I saw that movin the svelte plugin in the vite config to end helps and it does, but not fully.\n- @Woww Unfortunately I still haven't found the cause of this problem. I solved it by simply creating a new SvelteKit skeleton project and starting from there.\n- I found it happens when the component is outside the routes folder. Probably Vite is not tracking folders outside routes folder.\n- This issue is still valid with the current version of SvelteKit. All of my components are inside the routes folder, none of my import paths use uppercase letters, and I'm not even using a layout file yet.\n- Amazingly, I can also reproduce this with `SvelteKit v1.0.0-next.350`. If the case is not correct in the import path, the module will load and display but the hot reloading does not work. Good catch!","metadata":{"transformedAt":"2026-08-18T18:33:40.681Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":188,"estimatedTokens":1341}}277{"id":"stack-70714461","source":"stackoverflow","questionId":70714461,"title":"SvelteKit Rendering a Random Prop is different between server and client","tags":["javascript","server-side-rendering","svelte","sveltekit"],"text":"Title: SvelteKit Rendering a Random Prop is different between server and client\nTags: javascript, server-side-rendering, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI would like to make a component in SvelteKit which has a randomized parameter. The problem is that the value this parameter takes is different for when the page is rendered server-side versus when that page becomes hydrated.\n\nFor example, consider this component:\n\n```\n\n export let t = Math.random() * 90\n export let l = Math.random() * 90\n\n .box {\n position: fixed;\n top: var(--t); left: var(--l);\n width: 10vw; height: 10vh;\n background-color: black;\n transition: all 1s;\n }\n\n```\n\nWhen the page is rendered on the server, `t` and `l` take on some random value, and the result is returned to the browser as HTML. However, once the page becomes hydrated, `t` and `l` take on different values. As a result, the box moves.\n\nI don't want the box to move; rather, **I want the random value returned by the server to be used by the client as well** so there isn't a flash of changing style. Everything's fine if the page is navigated via the in-page router; it's when the page is server-rendered that the box moves.\n\nThe result is the same if I export a `load` function. Is there a way with SvelteKit for the server and client to agree on a random value?\n\n========================================\n\nTop Answer:\nYou can use a `.server.js`/`.server.ts` file to create `t` and `l` only on the server side.\n\nYou have a file `mypage.server.ts`:\n\n```\nexport const load = async () => {\n return { t: Math.random() * 90, l: Math.random() * 90};\n};\n```\n\nAnd then in `mypage.svelte`:\n\n```\n\n export let data;\n let { t, l } = data;\n\n...\n```\n\nSee also :\n\n- Section in Svelte tutorial\n\n- My commit fixing the same problem on my site\n\n========================================\n\nCode:\n```html\n<script>\n export let t = Math.random() * 90\n export let l = Math.random() * 90\n</script>\n\n<div class=\"box\" style=\"--t: {t}vh; --l: {l}vw;\"></div>\n\n<style>\n .box {\n position: fixed;\n top: var(--t); left: var(--l);\n width: 10vw; height: 10vh;\n background-color: black;\n transition: all 1s;\n }\n</style>\n```\n\n```text\nt\n```\n\n```text\nl\n```\n\n```text\nt\n```\n\n```text\nl\n```\n\n```text\nload\n```\n\n```svelte\n<script>\n import { onMount } from 'svelte';\n\n let t, l;\n\n onMount(() => {\n t = Math.random() * 90;\n l = Math.random() * 90;\n })\n</script>\n\n{#if t && l }\n<div class=\"box\" style=\"--t: {t}vh; --l: {l}vw;\"></div>\n{/if}\n\n<style>\n .box {\n position: fixed;\n top: var(--t); left: var(--l);\n width: 10vw; height: 10vh;\n background-color: black;\n transition: all 1s;\n }\n</style>\n```\n\n```js\n// random.json.js\nexport async function get() {\n return {\n body: {\n t: Math.random() * 90,\n l: Math.random() * 90,\n },\n };\n}\n```\n\n```svelte\n<!-- index.svelte -->\n<script context=\"module\">\n export async function load({ fetch }) {\n // this will be cached, so it will be the same on client & server\n const result = await fetch('/random.json');\n const { t, l } = await result.json();\n return {\n props: {\n t, l\n }\n }\n }\n</script>\n\n<script>\n export let t;\n export let l;\n</script>\n\n<div class=\"box\" style=\"--t: {t}vh; --l: {l}vw;\"></div>\n\n<style>\n .box {\n position: fixed;\n top: var(--t); left: var(--l);\n width: 10vw; height: 10vh;\n background-color: black;\n transition: all 1s;\n }\n</style>\n```\n\n```text\nexport const load = async () => {\n return { t: Math.random() * 90, l: Math.random() * 90};\n};\n```\n\n```text\n<script>\n export let data;\n let { t, l } = data;\n</script>\n...\n```\n\n```text\n.server.js\n```\n\n```text\n.server.ts\n```\n\n```text\nt\n```\n\n```text\nl\n```\n\n```text\nmypage.server.ts\n```\n\n```text\nmypage.svelte\n```\n\n========================================\n\nComments:\n- I believe trying to reconcile server- and client-side values will be difficult if possible at all. I would instead prevent one or the other. You could set the values inside `onMount` to prevent server-side computation, or you could turn hydration off for the page (it *has* to be a page however, not merely a component) to use server-side values (you'd have to also verify this doesn't negatively impact your client-side navigation behavior, though).\n- Nice, I didn't realize load worked that way, but now that I think about it it makes sense. Learned something new today ^^\n- Nice! I believe should be the accepted answer, as it's less convoluted and works just as well.","metadata":{"transformedAt":"2026-08-18T18:33:40.681Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":217,"estimatedTokens":1139}}278{"id":"stack-70531875","source":"stackoverflow","questionId":70531875,"title":"Svelte crossfade transition between pages","tags":["svelte","sveltekit"],"text":"Title: Svelte crossfade transition between pages\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm trying to transition between two pages in sveltekit but this doesn't seem to work, how can I do this?\n\n```\n\n import { crossfade } from 'svelte/transition'\n const [send, receive] = crossfade({ })\n\nGo to foo\n```\n\n```\n\n import { crossfade } from 'svelte/transition'\n const [send, receive] = crossfade({})\n\nGo to asdf\n```\n\n========================================\n\nCode:\n```text\n<!-- src/routes/asdf.svelte -->\n<script>\n import { crossfade } from 'svelte/transition'\n const [send, receive] = crossfade({ })\n</script>\n\n<a href=\"/foo\" in:receive={{ key: 'asdf' }} out:send={{ key: 'asdf' }}>Go to foo</a>\n```\n\n```text\n<!-- src/routes/foo.svelte -->\n<script>\n import { crossfade } from 'svelte/transition'\n const [send, receive] = crossfade({})\n</script>\n\n<a href=\"/asdf\" in:receive={{ key: 'asdf' }} out:send={{ key: 'asdf' }} style=\"background: crimson\">Go to asdf</a>\n```\n\n```text\n<script>\n import {crossfade} from './crossfade'\n const [send, receive] = crossfade\n</script>\n\n<a out:send=\"{{key: 'a'}}\" in:receive=\"{{key: 'a'}}\" style=\"border: 1px solid crimson; padding: 20px; margin-top: 20px; display: block\" href=\"/foo\">Go to foo</a>\n```\n\n```text\n<script>\n import {crossfade} from './crossfade'\n const [send, receive] = crossfade\n</script>\n\n<a out:send=\"{{key: 'a'}}\" in:receive=\"{{key: 'a'}}\" style=\"border: 10px solid crimson; padding: 60px; margin-top: 20px; display: block\" href=\"/\">Go to /</a>\n```\n\n```text\nimport { crossfade as svelteCrossfade } from 'svelte/transition';\n\nexport const crossfade = svelteCrossfade({});\n```\n\n========================================\n\nComments:\n- Your key is identical on both pages. It should be something unique to the element so Svelte knows which one's which. Try changing the key in \"foo.svelte\" to \"foo\" instead of \"asdf\" and see if that changes anything. If it still doesn't work, try setting the properties of the object you're passing to the crossfade function. An example is given in the svelte tutorial: svelte.dev/tutorial/deferred-transitions\n- I've seen that tutorial but it's not across components\n- Also shouldn't be the same since they are the same element - I want to crossfade between the two?\n- There is a blog post that suggests the trick is to create the crossfade transition in its own file and import it into both pages. I will be trying this as soon as I can, I just can't right now. You're right about the key naming. They contain something different but are the same conceptual object being replaced so they should have the same key name. dev.to/buhrmi/svelte-component-transitions-5ie\n- Hmmm I swear I tried that... Will have to give it another go\n- Is there any documentation about this in the docs?\n- There is nothing in the docs about it, but there should, this is the correct solution\n- I am trying to use this method utilizing route Paramus and the transition is not working. $page.Paramus.id. I can confirm the id’s match up.","metadata":{"transformedAt":"2026-08-18T18:33:40.681Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":81,"estimatedTokens":755}}279{"id":"stack-67913876","source":"stackoverflow","questionId":67913876,"title":"Know if there's a click event handler in my custom Svelte component","tags":["svelte"],"text":"Title: Know if there's a click event handler in my custom Svelte component\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nIs there a way to know if a click handler is set on my custom component? I want to add a CSS class to it that would add the `cursor: pointer;` style, but only if something is going to happen on click.\n\nTo illustrate, here is what could be the custom component:\n\n```\n\n $: magic = ? // this is what I'm after\n\n I might be clickable!\n\n .pointer {\n cursor: pointer;\n }\n\n```\n\n========================================\n\nTop Answer:\nI think you should handle on click event in parent element then pass `magic` variable from the parent to your custom element via prop\n\nor you can handle click event in your custom component then dispatch event to it's parent with event forwarding\n\n========================================\n\nCode:\n```text\n<script>\n $: magic = ? // this is what I'm after\n</script>\n\n<div on:click\n class:pointer={magic}\n>\n I might be clickable!\n</div>\n\n<style>\n .pointer {\n cursor: pointer;\n }\n</style>\n```\n\n```text\ncursor: pointer;\n```\n\n```html\n<script>\nexport let onClick = () => {}\n</script>\n\n<button on:click={onClick}>Hello</button>\n```\n\n```text\nmagic\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.681Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":64,"estimatedTokens":300}}280{"id":"stack-70472978","source":"stackoverflow","questionId":70472978,"title":"Sveltekit proxy api to avoid cors","tags":["cors","svelte","sveltekit"],"text":"Title: Sveltekit proxy api to avoid cors\nTags: cors, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm actually building a basic svelkit app.\nI need to fetch to a weather api but impossible to fetch I have cors errors :\nhttps://i.sstatic.net/VTFY5.png\n\nI guess I need to setup a proxy for `https://www.metaweather.com` is there any way to do it with svelte kit ?\n\n========================================\n\nCode:\n```text\nhttps://www.metaweather.com\n```\n\n```js\n// src/routes/api/weather/[city].json.js\nexport async function get({ params }) {\n const { city } = params;\n\n const res = await fetch(`https://www.metaweather.com/api/location/search/?query=${city}`);\n const weather = await res.json();\n\n return { body: weather }; \n}\n```\n\n```js\nfetch(`http://localhost:3000/api/weather/${city}.json`);\n```\n\n```js\n// src/routes/api/weather/[city].json/+server.js\nexport function GET({ params }) { // note the capitalized method name\n const { city } = params;\n\n // we can now simply pass on the original 3rd-party api response promise\n return fetch(`https://www.metaweather.com/api/location/search/?query=${city}`);\n}\n```\n\n```text\nsrc/routes/api/weather/[city].json/+server.js\n```\n\n========================================\n\nComments:\n- See stackoverflow.com/questions/72753092/… for how to use Vite's proxy feature, or the SvelteKit FAQ: kit.svelte.dev/docs/…\n- I've looked at so many tutorials and SvelteKit's official documentation. Only your answer helped me.\n- @NetOperatorWibby Glad I could help! Your comment also reminded me to update the answer with a change in the name & location of the endpoint file to reflect changes in SvelteKit's routing convention in its more recent releases :)\n- Further updated to conform to SvelteKit 1.0's endpoint handler format\n- is it possible to provide help regarding setting a custom node server? It seems the team behind adapter-node abondened the community and no longer answering questions regarding the adapter. stackoverflow.com/questions/76733107/… also my git is here github.com/fxmt2009/kitcustomserver how to make the build aware of my server and use it for the output/build instead of the vite during dev?\n- Docs don't mention you can pass fetch in this way! Anyone know if it's possible to adjust headers/cookies on the proxied fetch call? Also does anyone know if it pipes the response or does the svelte server download the whole response and then send?","metadata":{"transformedAt":"2026-08-18T18:33:40.681Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":57,"estimatedTokens":613}}281{"id":"stack-72791061","source":"stackoverflow","questionId":72791061,"title":"How do I add modules to build.rollupOptions.external?","tags":["node.js","svelte","algolia","rollupjs"],"text":"Title: How do I add modules to build.rollupOptions.external?\nTags: node.js, svelte, algolia, rollupjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to get Algolia InstantSearch.js working with my Svelte website. I get the following error when I try to deploy this on Netlify, I get the following error:\n\n```\n9:27:35 PM: [vite]: Rollup failed to resolve import \"instantsearch.js/es/widgets.js\" from \"src/components/Search/SearchSection.svelte\".\n9:27:35 PM: This is most likely unintended because it can break your application at runtime.\n9:27:35 PM: If you do want to externalize this module explicitly add it to\n9:27:35 PM: `build.rollupOptions.external`\n9:27:35 PM: > [vite]: Rollup failed to resolve import \"instantsearch.js/es/widgets.js\" from \"src/components/Search/SearchSection.svelte\".\n9:27:35 PM: This is most likely unintended because it can break your application at runtime.\n9:27:35 PM: If you do want to externalize this module explicitly add it to\n9:27:35 PM: `build.rollupOptions.external`\n```\n\nThis is how I import those modules in my component:\n\n```\nimport algoliasearch from 'algoliasearch/lite.js';\nimport instantsearch from 'instantsearch.js';\nimport { searchBox, hits, index } from 'instantsearch.js/es/widgets.js';\n```\n\nThis is my `svelte.config.js`:\n\n```\nimport fs from \"fs\";\nimport path from \"path\";\nimport adapterStatic from \"@sveltejs/adapter-static\";\nimport svg from \"vite-plugin-svgstring\";\nimport dsv from \"@rollup/plugin-dsv\";\nimport sveltePreprocess from \"svelte-preprocess\";\nimport autoprefixer from \"autoprefixer\";\nimport { indexAlgolia } from 'svelte-algolia/server-side'\nimport 'dotenv/config' // optional\n\nconst { thedivtagguy } = JSON.parse(fs.readFileSync(\"package.json\", \"utf8\"));\nconst dev = process.env.NODE_ENV === \"development\";\nconst dir = thedivtagguy ? thedivtagguy.subdirectory : \"\";\nconst prefix = dir.startsWith(\"/\") ? \"\" : \"/\";\nconst base = dev || !dir ? \"\" : `${prefix}${dir}`;\n\nconst preprocess = sveltePreprocess({\n postcss: {\n plugins: [autoprefixer]\n }\n});\n\nconst config = {\n preprocess,\n kit: {\n adapter: adapterStatic(),\n target: \"#svelte\",\n vite: {\n resolve: {\n alias: {\n $actions: path.resolve(\"./src/actions\"),\n $components: path.resolve(\"./src/components\"),\n $data: path.resolve(\"./src/data\"),\n $stores: path.resolve(\"./src/stores\"),\n $styles: path.resolve(\"./src/styles\"),\n $svg: path.resolve(\"./src/svg\"),\n $utils: path.resolve(\"./src/utils\")\n }\n },\n plugins: [dsv(), svg()],\n },\n paths: {\n base\n }\n }\n};\n\nexport default config;\n```\n\nThis is `rollup.config.js`:\n\n```\nimport sveltePreprocess from \"svelte-preprocess\";\nimport svelte from \"rollup-plugin-svelte\";\nimport geojson from 'rollup-plugin-geojson';\nimport { mdsvex } from \"mdsvex\";\nconst production = !process.env.ROLLUP_WATCH;\n\npreprocess: sveltePreprocess({\n sourceMap: !production,\n postcss: {\n plugins: [require(\"tailwindcss\"), require(\"autoprefixer\")]\n }\n});\n\nexport default {\n plugins: [\n svelte({\n // tell svelte to handle mdsvex files\n extensions: [\".svelte\", \".svx\"],\n preprocess: mdsvex()\n }),\n geojson()\n ],\n};\n```\n\nHow and where exactly do I \"externalize this module explicitly\"? I can't find any good documentation for this.\n\n========================================\n\nCode:\n```js\n9:27:35 PM: [vite]: Rollup failed to resolve import \"instantsearch.js/es/widgets.js\" from \"src/components/Search/SearchSection.svelte\".\n9:27:35 PM: This is most likely unintended because it can break your application at runtime.\n9:27:35 PM: If you do want to externalize this module explicitly add it to\n9:27:35 PM: `build.rollupOptions.external`\n9:27:35 PM: > [vite]: Rollup failed to resolve import \"instantsearch.js/es/widgets.js\" from \"src/components/Search/SearchSection.svelte\".\n9:27:35 PM: This is most likely unintended because it can break your application at runtime.\n9:27:35 PM: If you do want to externalize this module explicitly add it to\n9:27:35 PM: `build.rollupOptions.external`\n```\n\n```js\nimport algoliasearch from 'algoliasearch/lite.js';\nimport instantsearch from 'instantsearch.js';\nimport { searchBox, hits, index } from 'instantsearch.js/es/widgets.js';\n```\n\n```js\nimport fs from \"fs\";\nimport path from \"path\";\nimport adapterStatic from \"@sveltejs/adapter-static\";\nimport svg from \"vite-plugin-svgstring\";\nimport dsv from \"@rollup/plugin-dsv\";\nimport sveltePreprocess from \"svelte-preprocess\";\nimport autoprefixer from \"autoprefixer\";\nimport { indexAlgolia } from 'svelte-algolia/server-side'\nimport 'dotenv/config' // optional\n\nconst { thedivtagguy } = JSON.parse(fs.readFileSync(\"package.json\", \"utf8\"));\nconst dev = process.env.NODE_ENV === \"development\";\nconst dir = thedivtagguy ? thedivtagguy.subdirectory : \"\";\nconst prefix = dir.startsWith(\"/\") ? \"\" : \"/\";\nconst base = dev || !dir ? \"\" : `${prefix}${dir}`;\n\nconst preprocess = sveltePreprocess({\n postcss: {\n plugins: [autoprefixer]\n }\n});\n\nconst config = {\n preprocess,\n kit: {\n adapter: adapterStatic(),\n target: \"#svelte\",\n vite: {\n resolve: {\n alias: {\n $actions: path.resolve(\"./src/actions\"),\n $components: path.resolve(\"./src/components\"),\n $data: path.resolve(\"./src/data\"),\n $stores: path.resolve(\"./src/stores\"),\n $styles: path.resolve(\"./src/styles\"),\n $svg: path.resolve(\"./src/svg\"),\n $utils: path.resolve(\"./src/utils\")\n }\n },\n plugins: [dsv(), svg()],\n },\n paths: {\n base\n }\n }\n};\n\nexport default config;\n```\n\n```js\nimport sveltePreprocess from \"svelte-preprocess\";\nimport svelte from \"rollup-plugin-svelte\";\nimport geojson from 'rollup-plugin-geojson';\nimport { mdsvex } from \"mdsvex\";\nconst production = !process.env.ROLLUP_WATCH;\n\npreprocess: sveltePreprocess({\n sourceMap: !production,\n postcss: {\n plugins: [require(\"tailwindcss\"), require(\"autoprefixer\")]\n }\n});\n\nexport default {\n plugins: [\n svelte({\n // tell svelte to handle mdsvex files\n extensions: [\".svelte\", \".svx\"],\n preprocess: mdsvex()\n }),\n geojson()\n ],\n};\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nrollup.config.js\n```\n\n```js\nconst config = {\n preprocess,\n kit: {\n // other options ....\n vite: {\n // other options ....\n optimizeDeps:{\n exclude: ['instantsearch.js']\n },\n // in case you want to interact with rollup you can use\n build:{\n rollupOptions:{\n \n }\n }\n }\n }\n};\n```\n\n```text\nkit.vite.optimizeDeps.exclude\n```\n\n```text\nsvelte.config.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.681Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":242,"estimatedTokens":1619}}282{"id":"stack-71552572","source":"stackoverflow","questionId":71552572,"title":"How to enable support for SvelteKit's $lib alias in WebStorm (and PhpStorm, etc)?","tags":["webstorm","svelte","jetbrains-ide","sveltekit"],"text":"Title: How to enable support for SvelteKit's $lib alias in WebStorm (and PhpStorm, etc)?\nTags: webstorm, svelte, jetbrains-ide, sveltekit\nSource: Stack Overflow\n\nQuestion:\nIs it possible to define a special mapping that enables PhpStorm (or other WebStorm based IDEs) to have the ability to find files located in SvelteKit's special `$lib` directory alias?\n\nFor example, in PhpStorm, I'm importing global styles like so:\n\n```\n\n import '$lib/global-styles.scss';\n\n```\n\nHowever, the IDE unfortunately displays \"Cannot find declaration to go to\" when attempting to navigate to that particular file:\n\nhttps://i.sstatic.net/HidaD.png\n\n========================================\n\nTop Answer:\nI had this issue but resolved it (since I am using Typescript) by adding a paths entry in my `./tsconfig.json` at the root of my project.\n\n```\n{\n // ...\n \"compilerOptions\": {\n \"paths\": {\n \"$lib/*\": [\"src/lib/*\"],\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\n<script context=\"module\">\n import '$lib/global-styles.scss';\n</script>\n```\n\n```text\n$lib\n```\n\n```js\n// eslint-disable\nSystem.config({\n \"paths\": {\n \"$lib/*\": \"./src/lib/*\",\n }\n});\n```\n\n```text\n.webstorm.js\n```\n\n```text\n$lib/*\n```\n\n```text\nSystem.config()\n```\n\n```text\n{\n\"extends\": \"./.svelte-kit/tsconfig.json\",\n\"compilerOptions\": {\n ...\n \"baseUrl\": \"./src\"\n}\n```\n\n```text\nbaseUrl\n```\n\n```text\n{\n // ...\n \"compilerOptions\": {\n \"paths\": {\n \"$lib/*\": [\"src/lib/*\"],\n }\n }\n}\n```\n\n```text\n./tsconfig.json\n```\n\n========================================\n\nComments:\n- For me, it doesn't work\n- @polRk Can you provide more details about what IDE you're using, what you tried and what is happening?\n- Did not work for me either (using Webstorm)\n- Worked on PHPStorm with .phpstorm.js file\n- That's great, thanks Tyrone. That works for me in PhpStorm as well. I'll drop this into my answer and credit you!\n- p.s. Thanks for editing, my intent was to call attention to your answer. 😊 Updating it to actually link to your answer as well.","metadata":{"transformedAt":"2026-08-18T18:33:40.681Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":106,"estimatedTokens":509}}283{"id":"stack-64957437","source":"stackoverflow","questionId":64957437,"title":"External Dependencies not working in Nav.svelte","tags":["javascript","svelte","svelte-3","sapper"],"text":"Title: External Dependencies not working in Nav.svelte\nTags: javascript, svelte, svelte-3, sapper\nSource: Stack Overflow\n\nQuestion:\nI am trying to load sv-bootstrap-dropdown module in nav.svelte component but I am getting the error ` is not a valid SSR component. You may need to review your build config to ensure that dependencies are compiled, rather than imported as pre-compiled modules`. After that I tried to install that as devDependency but than I was getting the error that `Cannot read property remove of undefined`. This gets generated itself in the server js file under the **sapper** folder\n\n========================================\n\nCode:\n```text\n<Dropdown> is not a valid SSR component. You may need to review your build config to ensure that dependencies are compiled, rather than imported as pre-compiled modules\n```\n\n```text\nCannot read property remove of undefined\n```\n\n```text\nimport {\n Carousel,\n CarouselControl,\n CarouselIndicators,\n CarouselItem,\n CarouselCaption\n } from 'sveltestrap/src';\n```\n\n```text\nsrc\n```\n\n========================================\n\nComments:\n- I haven't had any luck getting this working either - any help would be appreciated!","metadata":{"transformedAt":"2026-08-18T18:33:40.681Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":36,"estimatedTokens":301}}284{"id":"stack-77121064","source":"stackoverflow","questionId":77121064,"title":"RollupError: \"ENV_VAR_NAME\" is not exported by \"$env/static/private\", imported by \"src/hooks.server.js\". - SvelteKit","tags":["import","svelte","vercel","sveltekit"],"text":"Title: RollupError: \"ENV_VAR_NAME\" is not exported by \"$env/static/private\", imported by \"src/hooks.server.js\". - SvelteKit\nTags: import, svelte, vercel, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am creating a SvelteKit project, and have declared environment variables that I need to access.\n\n**.env**\n\n```\nENV_VAR_NAME='random123'\n```\n\n**src/hooks.server.js**\n\n```\nimport { ENV_VAR_NAME } from '$env/static/private';\n//rest of my code here\n```\n\nThe above code works in development. However, when I deploy it to Vercel, I get the following error. The issue occurs even when I have declared the environment variable in Vercel.\n\n```\nRollupError: \"ENV_VAR_NAME\" is not exported by \"$env/static/private\", imported by \"src/hooks.server.js\".\n```\n\n========================================\n\nCode:\n```text\nENV_VAR_NAME='random123'\n```\n\n```text\nimport { ENV_VAR_NAME } from '$env/static/private';\n//rest of my code here\n```\n\n```text\nRollupError: \"ENV_VAR_NAME\" is not exported by \"$env/static/private\", imported by \"src/hooks.server.js\".\n```\n\n```text\n$env/dynamic/private\n```\n\n========================================\n\nComments:\n- Try changing the way you import the variable: // src/hooks.server.js // Access environment variable using import.meta.env const ENV_VAR_NAME = import.meta.env.VITE_ENV_VAR_NAME; // rest of your code here\n- I have a similar error and my variable is not set dynamically, at least that is not the intention. Is there anything else I could be missing? Thanks!\n- @thib: There was an issue with environment variables in v2, but that should have be patched. Other than that I do not know.\n- Thank you @brunnerh I used `svelte-kit sync` as suggested in this comment and it worked: github.com/sveltejs/kit/issues/11425#issuecomment-1892349204","metadata":{"transformedAt":"2026-08-18T18:33:40.681Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":53,"estimatedTokens":440}}285{"id":"stack-76580769","source":"stackoverflow","questionId":76580769,"title":"Implementing a loading spinner in sveltekit that is triggered during an action","tags":["javascript","svelte","sveltekit","pocketbase"],"text":"Title: Implementing a loading spinner in sveltekit that is triggered during an action\nTags: javascript, svelte, sveltekit, pocketbase\nSource: Stack Overflow\n\nQuestion:\nI have a simple form having email, password and confirmPassword. I use action to handle this. I want to implement a spinner that will be triggered for the following actions\n\n- Checking if user is currently existing in the db\n\n- If no, then proceed for registration\n\n*I am using pocketbase*\n\nFollowing is my action.\n\n```\nimport { superValidate } from 'sveltekit-superforms/server';\nimport { redirect } from '@sveltejs/kit';\nimport { fail } from '@sveltejs/kit';\n\nimport { loginSchema } from '$lib/schema/zodschema';\nimport { ClientResponseError } from 'pocketbase';\n\nexport const load = async () => {\n const form = await superValidate(loginSchema);\n return { form };\n};\n\nexport const actions = {\n default: async ({ locals, request }) => {\n const form = await superValidate(request, loginSchema);\n\n try {\n\n const { email } = form.data\n const records = await locals.pb.collection('test').getFullList();\n const userRecords = records.filter(value => value.email === form.data.email);\n\n if (userRecords.length > 0) {\n\n const existingUser = userRecords[0]\n\n if (existingUser && existingUser.verified) {\n return {\n\n accountCreated: false,\n message: 'The user records exists. Proceed to login instead',\n isVerified: true,\n\n }\n } else {\n\n return {\n\n accountCreated: false,\n message: 'The user record exists. You have to verify to access',\n isVerified: false,\n\n }\n }\n } else {\n await locals.pb.collection('test').create(form.data);\n\n return {\n\n accountCreated: true,\n message: 'The user record is successfully created',\n isVerified: false,\n }\n }\n\n } catch (error) {\n // Handle the error\n\n if (error instanceof ClientResponseError) {\n return {\n error: error.message,\n isLoading: false\n }\n }\n }\n }\n};\n```\n\nIn the above, I could set a boolean like\n\n```\nlet isLoading = true\n```\n\nThen set it to false at different stages. But the problem is how to access the isLoading status in the client (both initial and updated state).\n\nI tried stores only to find out later that stores cannot be used to the state between the client and server.\n\nIs there an alternative approach to achieve this?\n\nThanks\n\n========================================\n\nTop Answer:\nHave you considered using the `{#await}` block?\n\nWhat you can do is when you fetch the database it triggers the await block and when it's done, you can decide from there if you want to continue login or send to the registration page.\n\nRefer to: https://svelte.dev/tutorial/await-blocks\n\nSo it can looks something like:\n\n```\n\n let data;\n async function formSubmit() {\n data = await fetchData();\n\n ...\n }\n\n{#await data}\n \n{:then receivedData}\n \n \n{:catch}\n \n{/await}\n```\n\n========================================\n\nCode:\n```text\nimport { superValidate } from 'sveltekit-superforms/server';\nimport { redirect } from '@sveltejs/kit';\nimport { fail } from '@sveltejs/kit';\n\nimport { loginSchema } from '$lib/schema/zodschema';\nimport { ClientResponseError } from 'pocketbase';\n\nexport const load = async () => {\n const form = await superValidate(loginSchema);\n return { form };\n};\n\nexport const actions = {\n default: async ({ locals, request }) => {\n const form = await superValidate(request, loginSchema);\n\n\n try {\n\n const { email } = form.data\n const records = await locals.pb.collection('test').getFullList();\n const userRecords = records.filter(value => value.email === form.data.email);\n\n if (userRecords.length > 0) {\n\n const existingUser = userRecords[0]\n\n if (existingUser && existingUser.verified) {\n return {\n\n accountCreated: false,\n message: 'The user records exists. Proceed to login instead',\n isVerified: true,\n\n }\n } else {\n\n\n return {\n\n accountCreated: false,\n message: 'The user record exists. You have to verify to access',\n isVerified: false,\n\n\n }\n }\n } else {\n await locals.pb.collection('test').create(form.data);\n\n\n\n return {\n\n accountCreated: true,\n message: 'The user record is successfully created',\n isVerified: false,\n }\n }\n\n\n\n } catch (error) {\n // Handle the error\n\n if (error instanceof ClientResponseError) {\n return {\n error: error.message,\n isLoading: false\n }\n }\n }\n }\n};\n```\n\n```text\nlet isLoading = true\n```\n\n```text\n<script>\n import { enhance } from '$app/forms';\n\n /** @type {import('./$types').PageData} */\n export let data;\n\n let formLoading = false;\n</script>\n\n...\n{#if formLoading}\n Loading...\n{/if}\n...\n<form action=\"?/...\" method=\"post\" use:enhance={() => {\n formLoading = true;\n return async ({ update }) => {\n formLoading = false;\n update();\n };\n}}>\n <button>SUBMIT</button>\n</form>\n```\n\n```html\n<script>\n let data;\n async function formSubmit() {\n data = await fetchData();\n\n ...\n }\n</script>\n\n{#await data}\n <Spinner />\n{:then receivedData}\n <!-- Decide to send to registration or not -->\n <!-- you can either use the recievedData or just omit it -->\n{:catch}\n <!-- Handle error -->\n{/await}\n```\n\n```text\n{#await}\n```\n\n```js\nconst formSubmit: SubmitFunction = ({ form, data, action, cancel }) => {\n formLoading = true;\n return async ({ update }) => {\n await update(); // Wait for this to complete\n formLoading = false;\n };\n };\n```\n\n========================================\n\nComments:\n- Apparently OP uses Sveltekit progressive enhancement on form actions so your recommendation although correct is not relevant.\n- Thanks for the response. However, note that I am using form action for handling the data. I don't think you can return a promise in the form action that you can use in the client in the await. But what @Wtower has suggested indeed has worked.\n- It worked mate. This never crossed my mind. Thanks for the comment","metadata":{"transformedAt":"2026-08-18T18:33:40.681Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":279,"estimatedTokens":1581}}286{"id":"stack-57239504","source":"stackoverflow","questionId":57239504,"title":"How to set global style on event in Svelte","tags":["svelte"],"text":"Title: How to set global style on event in Svelte\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI have written an app in Svelte and would like to add a dark mode that anyone could activate after clicking a button. I added a Property called isDarkMode to switch the two cases. If the property is true, I want to change the background color of the body to a dark color, but the background color does not change.\n\n```\n{#if isDarkMode}\n \n :global(body){\n background: #2e3440;\n }\n \n{/if}\n```\n\n========================================\n\nTop Answer:\nIf you are willing to use css variables to manage your themes, you can toggle stylesheets in Svelte using the `` tag :\n\n```\n\n let dark = false;\n const toggleTheme = () => dark = dark === false\n\n {#if dark}\n \n {/if}\n\n### Hello World!\n\n toggle theme\n\n```\n\nIt should make it easier to manage styling across your app, as well as reduce the total bundle size and avoid using the `:global` selector in css.\n\nYou can find the working demo here:\nhttps://svelte.dev/repl/1a121a39eddb4b3682a7701a35ac6824?version=3.6.9\n\n========================================\n\nCode:\n```text\n{#if isDarkMode}\n <style>\n :global(body){\n background: #2e3440;\n }\n </style>\n{/if}\n```\n\n```text\n<script>\nfunction toggle() {\n window.document.body.classList.toggle('dark-mode')\n}\n</script>\n<button on:click={toggle}>Toggle mode</button>\n```\n\n```text\n// App.svelte\n<style>\n :global(body) {\n background-color: #f2eee2;\n color: #0084f6;\n transition: background-color 0.3s\n }\n :global(body.dark-mode) {\n background-color: #1d3040;\n color: #bfc2c7;\n }\n</style>\n// Button.svelte or any other component that adjusts to mode\n<style>\n button {\n background-color: #f76027;\n color: white;\n border: none;\n border-radius: 4px;\n padding: 0.5rem;\n text-transform: uppercase;\n }\n :global(body.dark-mode) button { \n background-color: #0084f6;\n color: white;\n }\n</style>\n```\n\n```text\nbody\n```\n\n```text\nbody\n```\n\n```text\n:global(body.dark-mode)\n```\n\n```text\nbutton\n```\n\n```text\n<script>\n let dark = false;\n const toggleTheme = () => dark = dark === false\n</script>\n\n<svelte:head>\n {#if dark}\n <link rel=\"stylesheet\" href=\"change/this/path/dark-theme.css\">\n {/if}\n</svelte:head>\n\n<h1>Hello World!</h1>\n\n<button on:click={toggleTheme}>\n toggle theme\n</button>\n```\n\n```text\n<svelte:head>\n```\n\n```text\n:global\n```\n\n```css\n<style>\n :global(body) {\n /* this will apply to <body> */\n margin: 0;\n }\n\n div :global(strong) {\n /* this will apply to all <strong> elements, in any\n component, that are inside <div> elements belonging\n to this component */\n color: goldenrod;\n }\n\n p:global(.red) {\n /* this will apply to all <p> elements belonging to this \n component with a class of red, even if class=\"red\" does\n not initially appear in the markup, and is instead \n added at runtime. This is useful when the class \n of the element is dynamically applied, for instance \n when updating the element's classList property directly. */\n }\n</style>\n```\n\n========================================\n\nComments:\n- I would probably take a different approach. If you stick with CSS (as opposed to CSS-in-JS) I would add the theme class name to the body element. So you have a regular body-style and a `body.dark-mode` style. Then you don't need conditionals littered around your application. (assuming that you are styling more than your body)\n- As to why it doesn't change. The style-block as far as I know isn't reative. Once compiled the CSS is extracted \"out\" of the template. How is `isDarkMode` defined?\n- Here is a demo of what I suggest svelte.dev/repl/ed4fef4beceb4b0eb295d1f9fdf3bd62?version=3.6‌​.9\n- could you make official answer with that?\n- @skyboyer I posted an answer now.\n- The example doesn't seem to work anymore. It errors (in the console) with a 404 when trying to load the `dark-theme.css` after clicking the toggle button.\n- Are you sure the path to the CSS file is the right one? A 404 error means it most likely work but the file isn't found.\n- You're right, the example simply seem to miss any additional css files (which may not even be possible on the Svelte REPL). I just had a different expectation of \"working demo\" ;).\n- Fair enough. The demo was working at the time, but it has been 4years so the repl might be different now.","metadata":{"transformedAt":"2026-08-18T18:33:40.681Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":174,"estimatedTokens":1134}}287{"id":"stack-74469661","source":"stackoverflow","questionId":74469661,"title":"SvelteKit PageLoad module not found","tags":["typescript","svelte","vite","sveltekit"],"text":"Title: SvelteKit PageLoad module not found\nTags: typescript, svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a SvelteKit project and for some reason, `./$types` doesn't have the module PageLoad (which other projects do. I'm not sure what I did/didn't do to not have it. This is the error I'm getting:\n\n```\nModule '\"./$types\"' has no exported member 'PageLoad'.ts(2305)\n```\n\nThis is how I'm using it (for testing):\n\n```\nimport { error } from '@sveltejs/kit';\nimport type { PageLoad } from './$types';\n\nexport const load: PageLoad = async ({ params, fetch }) => {\n console.log('props from +page.ts: ', params.db_item)\n // We fetch the post here using a Worker/Lambda\n return params.db_item\n}\n```\n\nHere is my package.json file:\n\n```\n{\n \"name\": \"test\",\n \"version\": \"0.0.1\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"vite dev\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\",\n \"test\": \"playwright test\",\n \"check\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json\",\n \"check:watch\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch\",\n \"lint\": \"prettier --check .\",\n \"format\": \"prettier --write .\",\n \"surge deploy\": \"rollup -c; surge public\"\n },\n \"devDependencies\": {\n \"@playwright/test\": \"^1.25.0\",\n \"@sveltejs/adapter-auto\": \"next\",\n \"@sveltejs/kit\": \"next\",\n \"node-sass\": \"^7.0.3\",\n \"prettier\": \"^2.6.2\",\n \"prettier-plugin-svelte\": \"^2.7.0\",\n \"svelte\": \"^3.44.0\",\n \"svelte-check\": \"^2.7.1\",\n \"svelte-preprocess\": \"^4.10.6\",\n \"tslib\": \"^2.3.1\",\n \"typescript\": \"^4.7.4\",\n \"vite\": \"^3.1.0\"\n },\n \"type\": \"module\",\n \"dependencies\": {\n \"svelte--buttons-component\": \"^1.5.0\"\n }\n}\n```\n\nHere is my svelte.config file:\n\n```\nimport adapter from '@sveltejs/adapter-cloudflare';\nimport preprocess from 'svelte-preprocess';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: preprocess(),\n\n kit: {\n adapter: adapter()\n }\n};\n\nexport default config;\n```\n\n========================================\n\nTop Answer:\nPer the Svelte Blog: Zero-effort type safety\n\nSvelteKit creates a hidden file `$types.d.ts` in every route directory. This file contains route specific types. Because of this, it's no longer even necessary to annotate Svelte-specific file exports (`+page`, `+layout`, `+server`, `hooks`, `params`, etc.).\n\nHowever, when the name of a `.ts/.js` file in a particular route changes, the route's `$types.d.ts` file may loose integrity.\n\nYou can fix the problem by restarting the Svelte language server.\n\nIn VSCode:\n\n- `ctrl+p`\n\n- Enter `>`\n\n- Select \"Svelte: Restart Language Server\"\n\n========================================\n\nCode:\n```text\nModule '\"./$types\"' has no exported member 'PageLoad'.ts(2305)\n```\n\n```text\nimport { error } from '@sveltejs/kit';\nimport type { PageLoad } from './$types';\n\nexport const load: PageLoad = async ({ params, fetch }) => {\n console.log('props from +page.ts: ', params.db_item)\n // We fetch the post here using a Worker/Lambda\n return params.db_item\n}\n```\n\n```text\n{\n \"name\": \"test\",\n \"version\": \"0.0.1\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"vite dev\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\",\n \"test\": \"playwright test\",\n \"check\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json\",\n \"check:watch\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch\",\n \"lint\": \"prettier --check .\",\n \"format\": \"prettier --write .\",\n \"surge deploy\": \"rollup -c; surge public\"\n },\n \"devDependencies\": {\n \"@playwright/test\": \"^1.25.0\",\n \"@sveltejs/adapter-auto\": \"next\",\n \"@sveltejs/kit\": \"next\",\n \"node-sass\": \"^7.0.3\",\n \"prettier\": \"^2.6.2\",\n \"prettier-plugin-svelte\": \"^2.7.0\",\n \"svelte\": \"^3.44.0\",\n \"svelte-check\": \"^2.7.1\",\n \"svelte-preprocess\": \"^4.10.6\",\n \"tslib\": \"^2.3.1\",\n \"typescript\": \"^4.7.4\",\n \"vite\": \"^3.1.0\"\n },\n \"type\": \"module\",\n \"dependencies\": {\n \"svelte-share-buttons-component\": \"^1.5.0\"\n }\n}\n```\n\n```text\nimport adapter from '@sveltejs/adapter-cloudflare';\nimport preprocess from 'svelte-preprocess';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: preprocess(),\n\n kit: {\n adapter: adapter()\n }\n};\n\nexport default config;\n```\n\n```text\n./$types\n```\n\n```text\n+page.js\n```\n\n```text\n.ts\n```\n\n```text\n$types\n```\n\n```text\n$types.d.ts\n```\n\n```text\n+page\n```\n\n```text\n+layout\n```\n\n```text\n+server\n```\n\n```text\nhooks\n```\n\n```text\nparams\n```\n\n```text\n.ts/.js\n```\n\n```text\n$types.d.ts\n```\n\n```text\nctrl+p\n```\n\n```text\n>\n```\n\n```text\n$types.d.ts\n```\n\n```js\nmodule.exports = {\n // ...\n extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier'],\n plugins: ['svelte3', '@typescript-eslint'],\n ignorePatterns: ['*.cjs'],\n overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }],\n settings: {\n 'svelte3/typescript': () => require('typescript'),\n },\n // ...\n}\n```\n\n```js\nmodule.exports = {\n root: true,\n extends: [\n 'eslint:recommended',\n 'plugin:@typescript-eslint/recommended',\n 'plugin:svelte/recommended',\n 'prettier',\n ],\n parser: '@typescript-eslint/parser',\n plugins: ['@typescript-eslint'],\n parserOptions: {\n sourceType: 'module',\n ecmaVersion: 2020,\n extraFileExtensions: ['.svelte'],\n },\n env: {\n browser: true,\n es2017: true,\n node: true,\n },\n overrides: [\n {\n files: ['*.svelte'],\n parser: 'svelte-eslint-parser',\n parserOptions: {\n parser: '@typescript-eslint/parser',\n },\n },\n ],\n};\n```\n\n```text\n.eslintrc.cjs\n```\n\n```text\nsvelte3\n```\n\n```text\n.eslintrc.js\n```\n\n```text\nnpm create svelte@latest my-app\n```\n\n```text\n.svelte-kit\n```\n\n```text\nnpx svelte-kit sync\n```\n\n========================================\n\nComments:\n- Does this answer your question? SvelteKit, import type LayoutServerLoad/PageLoad\n- You should tell the sveltekit team about this. Thanks for the finding.\n- I did. That's where I found the fix. :)\n- For future googlers, I just found out that I was trying to call `PageLoad` inside a `+layout.ts` file, which is a wrong thing to do. We can only call `PageLoad` if we have a `+page.ts` and `ServerLoad` for `+layout.ts`.\n- @JoelHager - would you mind linking to the GitHub issue or wherever else you found the fix? I have been looking for it but unable to find it\n- There wasn't a specific 'fix' for it. It's some common knowledge thing about how Svelte builds types. You either have to force a type rebuild (I think npm run check would do it) but I ended up deleting the file after copying, and just creating a new file with the .ts extension. I wish I could be of more help. :/\n- I tried restarting the language server, and it did not work for me. I had to delete the file and create it under .ts extension rather than rename it from .js to .ts. Maybe it was a one-off bug, but recreating the file is what fixed it for me.\n- `Yup, that was it!","metadata":{"transformedAt":"2026-08-18T18:33:40.682Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":317,"estimatedTokens":1823}}288{"id":"stack-59810747","source":"stackoverflow","questionId":59810747,"title":"how to bind svelte dynamic components values","tags":["svelte","svelte-component"],"text":"Title: how to bind svelte dynamic components values\nTags: svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nLet's say I have this main App:\n\n```\n\n import Field from '../components/Field.svelte';\n\n const components = {};\n const fields = [\n {\n id: 'Check',\n type: 'CheckBox',\n value: false,\n },\n {\n id: 'Text',\n },\n ];\n\n $: console.log(components);\n\n {#each fields as item}\n \n {/each}\n\n```\n\nAnd I have two components, `CheckBox` and `TextArea`, both just implement HTML\ninputs, and the Field Component is implemented like this:\n\n```\n\n import CheckBox from './CheckBox.svelte';\n import TextArea from './TextArea.svelte';\n\n export let attributes = {};\n export let type = 'TextArea';\n export let value = '';\n export let id;\n export let bind;\n\n const fieldComponents = {\n CheckBox: CheckBox,\n TextArea: TextArea,\n };\n\n```\n\nThat way I'm creating a dynamic form that has a checkbox and a textarea.\n\nWhat I want is the \"bind\" attribute to be accessible from within the component,\nand to be able to bind the another component, That way i'll be able to achieve\nsomething like this:\n\n```\n\n```\n\nwhich means that if the textarea will have text, the checkbox would be checked,\nif it's empty, the checkbox would be unchecked.\n\nafter all the components render i'm able to access them using the `components`\nobject because i'm binding them like this `bind:this={components[item.id]}`\n\nbut before they render I can't access them, is there a way to make it so one\ncomponent can dynamically bind to the other?.\n\nI demonstrated using only 2 component, it might as well be a large set of\ncomponents.\n\nThe way I want to determine the binding is using a `bind` property inside the\n`fields` array that matches the `id` of another field.\n\n========================================\n\nCode:\n```html\n<script>\n import Field from '../components/Field.svelte';\n\n const components = {};\n const fields = [\n {\n id: 'Check',\n type: 'CheckBox',\n value: false,\n },\n {\n id: 'Text',\n },\n ];\n\n $: console.log(components);\n</script>\n\n<form>\n {#each fields as item}\n <Field {...item} bind:bind={components[item.bind]} bind:this={components[item.id]} />\n {/each}\n</form>\n```\n\n```text\n<script>\n import CheckBox from './CheckBox.svelte';\n import TextArea from './TextArea.svelte';\n\n export let attributes = {};\n export let type = 'TextArea';\n export let value = '';\n export let id;\n export let bind;\n\n const fieldComponents = {\n CheckBox: CheckBox,\n TextArea: TextArea,\n };\n</script>\n\n<svelte:component this={fieldComponents[type]} {bind} {id} {value} {attributes} />\n```\n\n```html\n<input type=\"checkbox\" bind:checked={bind.value}>\n```\n\n```text\nCheckBox\n```\n\n```text\nTextArea\n```\n\n```text\ncomponents\n```\n\n```text\nbind:this={components[item.id]}\n```\n\n```text\nbind\n```\n\n```text\nfields\n```\n\n```text\nid\n```\n\n```text\n<script>\n/*\n@abstract This app is used to demonstrate one way to track form state with Svelte.\nWe use the 'store' to save an object that will contain our form field configurations\nand field values. A JSON string formatted configuration is used as opposed to a purely javascipt object so that we can for instance pull in our form configuration from a back-end database to dynmaically build our form (in this example we are simply hard-coding the JSON into the app, but for production you might want to pull from an server-side API).\n*/\nimport Field from './Field.svelte'; // used to build our form fields\nimport Box from './Box.svelte'; // just for show\nimport { storeFE } from './store.js'; // store our form state\nlet objForm; // @testing - used to listen for changes in our form state\n\n// @testing - keep up to date on the form object\nconst unsubscribe = storeFE.subscribe(value => {\n objForm = value;\n});\n\n// opting for JSON string config (which is what we would want if we are pulling this config from say a server data API)\n// the 'fIndex' value is used within our form components know which form element object to work with within our main 'storeFE' object store. the 'fType' value tells the Field.svelte component which form element to build\nlet objFormConfig = JSON.parse(`{\n \"formElements\": [\n {\n \"fIndex\":0,\n \"fId\":\"cc2\",\n \"fType\": \"CheckBox\",\n \"fValue\": \"true\",\n \"fDisable\":\"ct1.fValue==''\"\n },\n {\n \"fIndex\":1,\n \"fId\":\"ct1\",\n \"fType\": \"TextArea\",\n \"fValue\": \"textee area\",\n \"fChangeEvent\":\"cc2 disable\",\n \"fDisable\":\"cc2 checked is false\"\n }\n ]\n}`);\n// @testing: let us know when the form values have changed (the storeFE object has updated)\n$: {\n console.log('objForm:');\n console.log(objForm);\n}\n$storeFE = objFormConfig; // save the initial form configuration to the store\n</script>\n<form>\n{#each objFormConfig.formElements as item}\n <Box>\n <Field objAttributes={item}></Field>\n </Box>\n{/each}\n</form>\n```\n\n```text\n<script>\nimport CheckBox from './CheckBox.svelte';\nimport TextArea from './TextArea.svelte';\n\nexport let objAttributes = {};\n\nconst fieldComponents = {\n 'CheckBox': CheckBox,\n 'TextArea': TextArea\n};\n</script>\n<div>\n <svelte:component this={fieldComponents[objAttributes.fType]} {objAttributes} />\n</div>\n```\n\n```text\n<script>\n/* Here we want to get the store index */\nimport { storeFE } from './store.js';\nexport let objAttributes = {};\nconst fIndex = objAttributes.fIndex;\nconst strDisable = objAttributes.fDisable;\nfunction fDisable() {\n if (strDisable) {\n console.log('do some stuff like check: '+strDisable);\n }\n}\nconsole.log(\"checkbox here, showing you my field attributes:\");\nconsole.log(objAttributes);\n</script>\n<h2>\n My checkbox\n</h2>\n<input id={objAttributes.fId} type=checkbox bind:checked={$storeFE.formElements[fIndex].fValue} on:change={fDisable}>\n```\n\n```text\n<script>\nimport { storeFE } from './store.js';\nexport let objAttributes = {};\nconst fIndex = objAttributes.fIndex;\n\n\nconsole.log(\"textarea here, showing you my field attributes:\");\nconsole.log(objAttributes);\n</script>\n<h2>\n My text\n</h2>\n<textarea bind:value={$storeFE.formElements[fIndex].fValue}></textarea>\n```\n\n```text\nimport { writable } from 'svelte/store';\nexport let storeFE = writable({});\n```\n\n```text\n<style>\n .box {\n width: 300px;\n border: 1px solid #aaa;\n border-radius: 2px;\n box-shadow: 2px 2px 8px rgba(0,0,0,0.1);\n padding: 1em;\n margin: 0 0 1em 0;\n }\n</style>\n\n<div class=\"box\">\n <slot></slot>\n</div>\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.682Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":287,"estimatedTokens":1642}}289{"id":"stack-69107569","source":"stackoverflow","questionId":69107569,"title":"Use Svelte i18n in service / simple JS file","tags":["svelte","svelte-component"],"text":"Title: Use Svelte i18n in service / simple JS file\nTags: svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI use Svelte i18n for my project, it works perfectly in my Svelte components.\n\nBut I have some JS files (for constants for example), I want to use i18n to translate some keys, like (in `/services/constants.js`) :\n\n```\nimport { _ } from 'svelte-i18n'\n\nexport const STATUS_OK = 1;\nexport const STATUS_PENDING = 2;\nexport const STATUS_ERROR = 3;\nexport const STATUS_INACTIVE = 4;\nexport const STATUS_PRICE_NOT_FOUND = 5;\n\nexport const STATUTES = {\n [STATUS_OK]: {\n text: _('urls.statutes.ok'),\n class: 'text-green-500',\n },\n```\n\nBut I got an error, can I use `_` function in a JS file ? Or should I create kind of svelte component to handle my constants ?\n\n========================================\n\nTop Answer:\nAnswer from Stephane Vanraes is right, but there is a solution from svelte-i18n\n\n```\nimport { unwrapFunctionStore, format, formatNumber } from 'svelte-i18n';\n\nconst $formatNumber = unwrapFunctionStore(formatNumber);\nconst $format = unwrapFunctionStore(format);\n```\n\nSee FAQ: https://github.com/kaisermann/svelte-i18n/blob/main/docs/FAQ.md#can-i-use-the-formatter-functions-outside-of-a-svelte-component\n\n========================================\n\nCode:\n```text\nimport { _ } from 'svelte-i18n'\n\nexport const STATUS_OK = 1;\nexport const STATUS_PENDING = 2;\nexport const STATUS_ERROR = 3;\nexport const STATUS_INACTIVE = 4;\nexport const STATUS_PRICE_NOT_FOUND = 5;\n\nexport const STATUTES = {\n [STATUS_OK]: {\n text: _('urls.statutes.ok'),\n class: 'text-green-500',\n },\n```\n\n```text\n/services/constants.js\n```\n\n```text\n_\n```\n\n```html\n<p>{$_('urls.statuses.ok')}</p>\n```\n\n```text\ntext: get(_)('urls.statuses.ok')\n```\n\n```text\ntext: _ => _('urls.statuses.ok')\n```\n\n```text\n<p>{STATUTES.STATUS_OK($_)}</p>\n```\n\n```text\nsvelte-i18n\n```\n\n```text\n_\n```\n\n```text\n$\n```\n\n```text\n_('urls.statuses.ok')\n```\n\n```text\n$\n```\n\n```text\nimport { get } from 'svelte/store'\n```\n\n```text\nget\n```\n\n```text\ntext\n```\n\n```text\nget\n```\n\n```text\nimport { unwrapFunctionStore, format, formatNumber } from 'svelte-i18n';\n\nconst $formatNumber = unwrapFunctionStore(formatNumber);\nconst $format = unwrapFunctionStore(format);\n```\n\n========================================\n\nComments:\n- Heck yeah! This is really the canonical answer. But, since the only way to learn it is by reading the *very* last question in the FAQ, I'm sure it's not very widely known. :)","metadata":{"transformedAt":"2026-08-18T18:33:40.682Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":131,"estimatedTokens":614}}290{"id":"stack-50300176","source":"stackoverflow","questionId":50300176,"title":"Is it possible to dynamically load a Svelte template at runtime?","tags":["svelte"],"text":"Title: Is it possible to dynamically load a Svelte template at runtime?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI have looked at the documentation for `[]` (here), but that looks like I would have had to `import` all of the possible templates at compile time.\n\nIs it possible in Svelte to load any number of arbitrary templates from something like a `fetch()` call based on a user action? Then inject data into it?\n\nWould it be inefficient to use `` for something like this, if I plan on updating it after the initial load?\n\n========================================\n\nCode:\n```text\n[<svelte:component>]\n```\n\n```text\nimport\n```\n\n```text\nfetch()\n```\n\n```text\n<slot>\n```\n\n```html\n<button on:click=\"loadChatbox()\">\n chat to a customer service representative\n</button>\n\n{#if ChatBox}\n <svelte:component this={ChatBox}/>\n{/if}\n\n<script>\n export default {\n methods: {\n async loadChatbox() {\n const { default: Chatbox } = await import('./Chatbox.html');\n this.set({ Chatbox });\n }\n }\n };\n</script>\n```\n\n```text\nexperimentalDynamicImport\n```\n\n```text\nexperimentalCodeSplitting\n```\n\n========================================\n\nComments:\n- What about if dynamic component is specified only as a string? For example 'ChatBox'?\n- Bundlers need the 'x' in `import('x')` at build time so that they can create the necessary code-split chunks. The conventional solution is to have a map of loaders, like `{A: () => import('./A.svelte'), B: () => import('./B.svelte'), ...}`\n- @RichHarris We kinda need something like this to get introspection into the props that a component exposes for documentation (not production). Is there a way to do this? My ideal solution would be a component that wraps another, and then just spits out the child's props nabbed from the slot. Is that a thing, or is that like witchcraft? ;) (For the record: One of the huge problems with building Design Systems in the past, was manually having to edit documentation updates, so we are trying to avoid this, and auto-generate everything we can from the components themselves) Thx in advance!","metadata":{"transformedAt":"2026-08-18T18:33:40.682Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":65,"estimatedTokens":524}}291{"id":"stack-75753497","source":"stackoverflow","questionId":75753497,"title":"What is the type of a Svelte component?","tags":["typescript","svelte","svelte-component"],"text":"Title: What is the type of a Svelte component?\nTags: typescript, svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nWhen you look at this code:\n\n```\n\n import RedThing from \"./RedThing.svelte\";\n import GreenThing from \"./GreenThing.svelte\";\n\n const things: Record = {\n red: RedThing,\n green: GreenThing,\n };\n\n```\n\nThen everything works and is strongly typed. But in my mind it would make more sense to replace `typeof RedThing` with `SvelteComponent` or something similar? But that causes TS errors: `Type 'typeof RedThing__SvelteComponent_' is missing the following properties from type 'SvelteComponentDev': $set, $on, $destroy, $$prop_def, and 5 more.`\n\nSo what is the \"generic\" type for a Svelte component?\n\nOr when looking at ``, what type does `this` accept?\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n import RedThing from \"./RedThing.svelte\";\n import GreenThing from \"./GreenThing.svelte\";\n\n const things: Record<string, typeof RedThing> = {\n red: RedThing,\n green: GreenThing,\n };\n</script>\n```\n\n```text\ntypeof RedThing\n```\n\n```text\nSvelteComponent\n```\n\n```text\nType 'typeof RedThing__SvelteComponent_' is missing the following properties from type 'SvelteComponentDev': $set, $on, $destroy, $$prop_def, and 5 more.\n```\n\n```text\n<svelte:component this={expression}/>\n```\n\n```text\nthis\n```\n\n```text\nComponentType\n```\n\n```text\nComponent\n```\n\n========================================\n\nComments:\n- This no longer seems to work correctly after updating both TypeScript and SvelteKit. `Type 'typeof MyComponentName__SvelteComponent_' is not assignable to type 'ComponentType>'. Types of parameters 'options' and 'options' are incompatible.`\n- If anything that should be an issue on SvelteKit's side or the version of your `svelte` package does not match the version used by SvelteKit/the language tools.\n- It's the update to Svelte 3.58.0 that breaks it\n- This is the actual underlying error: `Type 'Element | ShadowRoot | Document' is not assignable to type 'Element | ShadowRoot'.`\n- It's a type mismatch introduced here, but the `language-tools` have not been updated to account for that.\n- I see you already fixed it (github.com/sveltejs/language-tools/pull/1968). Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:40.682Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":77,"estimatedTokens":558}}292{"id":"stack-51059820","source":"stackoverflow","questionId":51059820,"title":"Svelte/Sapper dynamic client-side routing","tags":["svelte"],"text":"Title: Svelte/Sapper dynamic client-side routing\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI'm using Svelte and Sapper for a web app where I need to proceed to the next page dynamically, i.e. after something happens (a Web Bluetooth connection) - not just from an `` element click.\n\nFor `` links, Sapper intercepts these and performs client-side routing. How can I achieve client-side routing myself, via JavaScript?\n\nIf, for example, I call `location.href = ...` then this is not intercepted and it involves a roundtrip to the server for the next page.\n\nIs there a neat way of doing this? (Something like `router.route('/my-page')`)?\n\n========================================\n\nTop Answer:\nFor **Svelte-3:**\n\n```\nimport { goto } from '@sapper/app'\ngoto('/profiles')\n```\n\n========================================\n\nCode:\n```text\n<a>\n```\n\n```text\n<a>\n```\n\n```text\nlocation.href = ...\n```\n\n```text\nrouter.route('/my-page')\n```\n\n```text\nimport { goto } from 'sapper/runtime.js';\ngoto('/my-page');\n```\n\n```text\nimport { goto } from '@sapper/app'\ngoto('/profiles')\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.682Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":51,"estimatedTokens":267}}293{"id":"stack-69324913","source":"stackoverflow","questionId":69324913,"title":"How svelte-kit build for staging env?","tags":["svelte","sveltekit"],"text":"Title: How svelte-kit build for staging env?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI want to build a svelte app using svelte-kit for staging environments. I did not find a suitable command to take `.env.staging` as its configs.\n\nWhen I execute `svelte-kit build` it always takes `.env.production`\n\nPlease helps me with how to build for staging env.\n\n========================================\n\nTop Answer:\nDavid's answer worked for me until `\"@sveltejs/kit\": \"^1.0.0\"`. Now I use:\n\n```\n\"scripts\": {\n ...\n \"stage\": \"vite build --mode staging\",\n \"prod\": \"vite build --mode production\",\n ...\n```\n\nvia `npm run stage` to build for staging and `npm run prod` to build for production. These commands map to `.env.stage` and `.env.production` files at the root of the project.\n\n========================================\n\nCode:\n```text\n.env.staging\n```\n\n```text\nsvelte-kit build\n```\n\n```text\n.env.production\n```\n\n```text\n\"scripts\": {\n \"build:dev\": \"APP_ENV=development vite build\",\n \"build:prod\": \"APP_ENV=production vite build\",\n}\n```\n\n```text\nconst mode = process.env.APP_ENV // This now exists.\n\nmodule.exports = {\n mode: mode, // This will set the mode, to avoid confusions.\n}\n```\n\n```text\n\"scripts\": {\n \"dev\": \"svelte-kit dev\",\n \"build\": \"svelte-kit build\",\n```\n\n```text\n\"scripts\": {\n \"dev\": \"vite dev\",\n \"build\": \"vite build\",\n```\n\n```text\n\"scripts\": {\n \"dev\": \"vite dev\",\n \"build\": \"vite build\",\n \"staging\": \"npm run dev -- --mode staging\"\n```\n\n```text\n> npm run staging\n```\n\n```text\n1.0.0-next.370\n```\n\n```text\nsvelte-kit\n```\n\n```text\nvite\n```\n\n```text\n.env.staging\n```\n\n```text\n\"scripts\": {\n ...\n \"stage\": \"vite build --mode staging\",\n \"prod\": \"vite build --mode production\",\n ...\n```\n\n```text\n\"@sveltejs/kit\": \"^1.0.0\"\n```\n\n```text\nnpm run stage\n```\n\n```text\nnpm run prod\n```\n\n```text\n.env.stage\n```\n\n```text\n.env.production\n```\n\n========================================\n\nComments:\n- This is no longer working, at least for me. Do you know if there's a newer way to achieve this?\n- For some reason I'm still getting the production environment variables. I tried `npm run build -- --mode development`. Any idea if I'm missing something?\n- Not sure, according vite documentation, `vite build --mode staging` should do.\n- Yeah, weird, I created an issue: github.com/sveltejs/kit/issues/8323 Thanks for your help!","metadata":{"transformedAt":"2026-08-18T18:33:40.682Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":130,"estimatedTokens":590}}294{"id":"stack-59165666","source":"stackoverflow","questionId":59165666,"title":"Should a spread operator be used when updating an object with svelte/store update method?","tags":["svelte","svelte-store"],"text":"Title: Should a spread operator be used when updating an object with svelte/store update method?\nTags: svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI'm creating a store that uses an object to store my data. \n\nI can update the store using the spread operator, but I can also update it without the spread operator.\n\nIs Svelte like React where I should use the spread operator to create a new object prior to updating the state of the object so I'm not mutating the original object? \n\n`withSpreadOperator()` or `withoutSpreadOperator()`... that is the question.\n\n```\n//stores.js\n\nimport { writable } from \"svelte/store\";\n\nexport const counts = writable({ n: 0 });\n```\n\n```\n//App.js\n\n import { count } from \"./stores.js\";\n\n function withSpreadOperator() {\n count.update(o => {\n let x = { ...o };\n x.n++;\n return x;\n });\n }\n\n function withoutSpreadOperator() {\n count.update(o => {\n o.n++;\n return o;\n });\n }\n\n### The count is {$count.n}\n\n+\n+\n```\n\n========================================\n\nCode:\n```text\n//stores.js\n\nimport { writable } from \"svelte/store\";\n\nexport const counts = writable({ n: 0 });\n```\n\n```text\n//App.js\n\n<script>\n import { count } from \"./stores.js\";\n\n function withSpreadOperator() {\n count.update(o => {\n let x = { ...o };\n x.n++;\n return x;\n });\n }\n\n function withoutSpreadOperator() {\n count.update(o => {\n o.n++;\n return o;\n });\n }\n</script>\n\n<h1>The count is {$count.n}</h1>\n<button on:click=\"{withSpreadOperator}\">+</button>\n<button on:click=\"{withoutSpreadOperator}\">+</button>\n```\n\n```text\nwithSpreadOperator()\n```\n\n```text\nwithoutSpreadOperator()\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.682Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":92,"estimatedTokens":407}}295{"id":"stack-58610895","source":"stackoverflow","questionId":58610895,"title":"How to use custom store methods in svelte?","tags":["svelte","svelte-3","svelte-store"],"text":"Title: How to use custom store methods in svelte?\nTags: svelte, svelte-3, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI'm making a modal, with its attributes stored in a store. Rather than open it like this, from an element: `on:click={() => $modal.isOpen = true}`\n\nI want to open it like this:\n`on:click={() => $modal.toggle()}` from an element.\n\nHere is my code:\n\n```\nexport const modal = writable({\n isOpen: false,\n title: 'Title',\n content: 'Content',\n toggle: () => {\n console.log(modal)\n modal.set({ ...modal, isOpen: true });\n }\n});\n```\n\nWhen I log `modal`, it logs just the `set, subscribe, update` methods. Then when I click again, those methods are gone: it properly overwrites them, it just seems that I can never get the modal's initialized state. I've tried to access the current object with `this` or parameters (`(a, b) =>`) but neither return anything.\n\n========================================\n\nCode:\n```text\nexport const modal = writable({\n isOpen: false,\n title: 'Title',\n content: 'Content',\n toggle: () => {\n console.log(modal)\n modal.set({ ...modal, isOpen: true });\n }\n});\n```\n\n```text\non:click={() => $modal.isOpen = true}\n```\n\n```text\non:click={() => $modal.toggle()}\n```\n\n```text\nmodal\n```\n\n```text\nset, subscribe, update\n```\n\n```text\nthis\n```\n\n```text\n(a, b) =>\n```\n\n```js\nconst toggleable = initial => {\n const store = writable(initial);\n\n return {\n ...store,\n toggle: () => store.update(n => !n)\n };\n};\n\nconst modal = toggleable(false);\n```\n\n```text\nwritable\n```\n\n```text\nwritable\n```\n\n========================================\n\nComments:\n- Thanks, Rich! I feel like I'm close but I just cannot seem to import this update method properly. Shown here: svelte.dev/repl/a5457b36d46d48d4bb271852cf6d0c75?version=3 I've tried all manner of things between the two examples shown (and more) but it seems if I ever get update() working, then something else breaks.\n- `store.update` takes a *function*, not a value. The function receives the old value and returns a new one. So it should be `store.update(old => ({ ...old, isOpen: !old.isOpen }))`","metadata":{"transformedAt":"2026-08-18T18:33:40.682Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":91,"estimatedTokens":527}}296{"id":"stack-55957386","source":"stackoverflow","questionId":55957386,"title":"Use reserved word as prop name","tags":["svelte"],"text":"Title: Use reserved word as prop name\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI would like to use `class` as a prop name for my component, but I get the following error:\n\n Unexpected keyword 'class'.\n\n```\n\n export let class = '';\n\n .foo {\n color: red;\n }\n\n \n\n```\n\nIs it possible to use a reserved word as prop name in Svelte?\n\n========================================\n\nCode:\n```html\n<script>\n export let class = '';\n</script>\n\n<style>\n .foo {\n color: red;\n }\n</style>\n\n<div class=\"{class}\">\n <slot />\n</div>\n```\n\n```text\nclass\n```\n\n```html\n<!-- App.svelte -->\n<script>\n import Child from './Child.svelte';\n</script>\n\n<Child class=\"foo\">Bar</Child>\n\n<!-- Child.svelte -->\n<script>\n let classProp = '';\n\n export { classProp as class };\n</script>\n\n<style>\n .foo {\n color: red;\n }\n</style>\n\n<div class=\"{classProp}\">\n <slot />\n</div>\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.682Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":71,"estimatedTokens":214}}297{"id":"stack-61387774","source":"stackoverflow","questionId":61387774,"title":"Svelte - usage of Context API (setContext/getContext) over regular props passing","tags":["javascript","svelte"],"text":"Title: Svelte - usage of Context API (setContext/getContext) over regular props passing\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nHere is a simple example:\n\n```\n\n import Button from './Button.svelte';\n\n let text = 'Click me!';\n let sayHello = () => alert('Hello!');\n\n```\n\nAnd if I get it right, since there can be lots of ``, it'll be nice to omit props passing somehow\n\nAnd here comes **Context API**:\n\n```\n\n import Button from './Button.svelte';\n import { setContext } from 'svelte';\n import { text, sayHello } from './data.js';\n\n setContext(text, 'Click me!');\n setContext(sayHello, () => alert('Hello!'));\n\n```\n\n*And somewhere in `./Button.svelte` there are `getContext()` usage, etc*\n\nSo, is the ability to omit similar props passing is the only reason to use Svelte's **Context API**?\n\n========================================\n\nCode:\n```text\n<script>\n import Button from './Button.svelte';\n\n let text = 'Click me!';\n let sayHello = () => alert('Hello!');\n</script>\n\n<Button {text} {sayHello}/>\n<Button {text} {sayHello}/>\n<Button {text} {sayHello}/>\n```\n\n```text\n<script>\n import Button from './Button.svelte';\n import { setContext } from 'svelte';\n import { text, sayHello } from './data.js';\n\n setContext(text, 'Click me!');\n setContext(sayHello, () => alert('Hello!'));\n</script>\n\n<Button/>\n<Button/>\n<Button/>\n```\n\n```text\n<Button {text} {sayHello}/>\n```\n\n```text\n./Button.svelte\n```\n\n```text\ngetContext()\n```\n\n```html\n<Form>\n <Input />\n</Form>\n```\n\n```js\nexport const key = {name: 'my-context'}\n```\n\n```html\n<script>\n import { setContext } from 'svelte'\n import { key } from './constants.js'\n\n setContext(key, { ... })\n</script>\n\n<slot />\n```\n\n```html\n<script>\n import { getContext } from 'svelte'\n import { key } from './constants.js'\n\n const { ... } = getContext(key)\n</script>\n\n...\n```\n\n```text\nsetContext\n```\n\n```text\nApp\n```\n\n```text\nForm\n```\n\n```text\nInput\n```\n\n```text\nInput\n```\n\n```text\nForm\n```\n\n```text\nForm\n```\n\n```text\nInput\n```\n\n```text\nForm\n```\n\n```text\nimport { setData, getData } from './data-source.js'\n```\n\n```text\nForm\n```\n\n```text\n<Form>\n```\n\n```text\nMap\n```\n\n```text\nconstants.js\n```\n\n```text\nconstants.js\n```\n\n```text\nForm.svelte\n```\n\n```text\nInput.svelte\n```\n\n========================================\n\nComments:\n- Rixo: I thank you for your detailed answer because I'm struggling to understand how to organize a button component clicked and pass props to it. Your answer cleared a lot of confusion. I appreciate it if you take a look and guide me to best practices as I'm focusing my time on svelte/sapper . If you care, here is my question link: stackoverflow.com/questions/62224782/…\n- Thanks for this thorough answer! *\"the Form component can't pass props to the Input component because the Input is not created directly in the Form component\" / \"...or because it is technically impossible (slots).\"* There's a way to do this, the props could be passed to the slot via the `let:directive` in this case svelte.dev/tutorial/slot-props","metadata":{"transformedAt":"2026-08-18T18:33:40.682Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":183,"estimatedTokens":756}}298{"id":"stack-66141626","source":"stackoverflow","questionId":66141626,"title":"Svelte: How to pass action to component?","tags":["javascript","svelte","svelte-3","svelte-component"],"text":"Title: Svelte: How to pass action to component?\nTags: javascript, svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nThere is a similar question asked here but I do not believe the answer applies to my use case.\n\nI'm using Svelte MaterialUI and attempting to extend the DataTable component with the ability to drag and drop rows. I'm using the svelte-dnd-action module to support the drag and drop behaviors.\n\nThe following works just fine. I'm able to drag and drop rows of the table.\n\n\r\n\r\n\n```\n\n ...\n \n ...data\n \n\n```\n\n\r\n\r\n\r\n\nHowever, when attempting to plug the module into a Material UI Component, I receive an error stating \"actions can only be applied to DOM elements, not components.\"\n\n\r\n\r\n\n```\n\n ...\n \n ...Data\n \n\n```\n\n\r\n\r\n\r\n\nThe definition of the `Body` component looks like this:\n\n\r\n\r\n\n```\n\n import {setContext} from 'svelte';\n import {get_current_component} from 'svelte/internal';\n import {forwardEventsBuilder} from '@smui/common/forwardEvents.js';\n import {exclude} from '@smui/common/exclude.js';\n import {useActions} from '@smui/common/useActions.js';\n const forwardEvents = forwardEventsBuilder(get_current_component());\n export let use = [];\n let className = '';\n export {className as class};\n setContext('SMUI:data-table:row:header', false);\n\n```\n\n\r\n\r\n\r\n\nIs there a way to forward my `Action` to this component? Or a better way to handle this use case? Thank you in advance.\n\n========================================\n\nTop Answer:\nAction can only be applied to DOM element. However, it's possible to pass a function by property to a component, and this component can use this property in a \"use\" directive.\n\nAn example:\n\n```\n\n function myAction() {\n ...\n }\n\n```\n\n```\n\n export let action;\n\n```\n\nIf you look at the smui library, you'll see that every component export an 'use' property, and apply the content of this property to a dom element. `use:useActions={use}` inject the action defined in the `use` property as actions.\n\nIn other words, in smui, you can pass actions to components by using the `use` property.\n\n```\n\n```\n\n========================================\n\nCode:\n```html\n<table>\n <thead>...</thead>\n <tbody use:dndzone{...opts}>\n ...data\n <tbody>\n</table>\n```\n\n```html\n<DataTable>\n <Head>...</Head>\n <Body use:dndzone={...opts}>\n ...Data\n </Body>\n</DataTable>\n```\n\n```html\n<tbody\n use:useActions={use}\n use:forwardEvents\n class=\"mdc-data-table__content {className}\"\n {...exclude($$props, ['use', 'class'])}\n><slot></slot></tbody>\n\n<script>\n import {setContext} from 'svelte';\n import {get_current_component} from 'svelte/internal';\n import {forwardEventsBuilder} from '@smui/common/forwardEvents.js';\n import {exclude} from '@smui/common/exclude.js';\n import {useActions} from '@smui/common/useActions.js';\n const forwardEvents = forwardEventsBuilder(get_current_component());\n export let use = [];\n let className = '';\n export {className as class};\n setContext('SMUI:data-table:row:header', false);\n</script>\n```\n\n```text\nBody\n```\n\n```text\nAction\n```\n\n```html\n<Body use={[[dndzone, opts]]}>\n```\n\n```html\n<script>\n function myAction() {\n ...\n }\n</script>\n\n<!-- pass myAction in a property 'action' -->\n<MyComponent action={myAction}/>\n```\n\n```html\n<!-- MyComponent.svelte -->\n<script>\n export let action;\n</script>\n\n<div use:action/>\n```\n\n```html\n<Body use={myAction}/>\n```\n\n```text\nuse:useActions={use}\n```\n\n```text\nuse\n```\n\n```text\nuse\n```\n\n========================================\n\nComments:\n- Thank you. I'm curious, would it be possible that `MyComponent.svelte` accepts an action if passed any, and not, if not. In my case, when I don't pass an action it throws an error\n- FYI, the tag could look like this: ``","metadata":{"transformedAt":"2026-08-18T18:33:40.682Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":196,"estimatedTokens":924}}299{"id":"stack-72843913","source":"stackoverflow","questionId":72843913,"title":"How Do I Add TypeScript to a SvelteKit Handle Function in Hooks?","tags":["typescript","svelte","sveltekit"],"text":"Title: How Do I Add TypeScript to a SvelteKit Handle Function in Hooks?\nTags: typescript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am currently using the following in my `hooks.ts` file in a SvelteKit app:\n\n```\nexport async function handle({ event, resolve }) {\n console.log(event.locals) //I'm trying to figure out how to use types on the `event` and `resolve` parameters. As far as I can tell, `event` works like this:\n\n```\nimport type { RequestEvent } from '@sveltejs/kit'\n\nexport async function handle(event: RequestEvent, resolve: ???){\n ...\n}\n```\n\nBut I can't figure out how to type the `resolve` parameter. The docs here show this:\n\n```\ninterface Handle {\n (input: {\n event: RequestEvent;\n resolve(\n event: RequestEvent,\n opts?: ResolveOptions\n ): MaybePromise;\n }): MaybePromise;\n}\n```\n\nFrom my limited TypeScript knowledge, it looks like `resolve` is a function with two parameters that returns a promise. But how do I write that out in the `handle` function declaration?\n\n========================================\n\nTop Answer:\nAs an alternative to typing the function as a whole, which is convenient in that it types arguments and return type, you can type those separately and retain the `export async function` syntax.\n\nThe argument type does not have a name, though, so you need to extract it manually from `Handle`. Note that there actually is only one argument, which is being destructured. E.g.\n\n```\n// Maybe export this from elsewhere to not repeat it\ntype HandleParams = Parameters[0];\n\nexport async function handle({ event, resolve }: HandleParams) : Promise {\n // ...\n}\n```\n\nThe original return type uses `MaybePromise` to allow synchronous and async returns. You can just only use `Promise` if the function is actually `async`.\n\nThere also is another helper type like `Parameters` that would allow you to extract the return type generically from `Handle`:\n\n```\ntype HandleResult = ReturnType;\n```\n\n========================================\n\nCode:\n```text\nexport async function handle({ event, resolve }) {\n console.log(event.locals) //<-- Works fine\n}\n```\n\n```text\nimport type { RequestEvent } from '@sveltejs/kit'\n\nexport async function handle(event: RequestEvent, resolve: ???){\n ...\n}\n```\n\n```js\ninterface Handle {\n (input: {\n event: RequestEvent;\n resolve(\n event: RequestEvent,\n opts?: ResolveOptions\n ): MaybePromise<Response>;\n }): MaybePromise<Response>;\n}\n```\n\n```text\nhooks.ts\n```\n\n```text\nevent\n```\n\n```text\nresolve\n```\n\n```text\nevent\n```\n\n```text\nresolve\n```\n\n```text\nresolve\n```\n\n```text\nhandle\n```\n\n```text\nexport const handle: Handle = async function ({ event, resolve }) {\n console.log(event.locals);\n}\n```\n\n```text\nHandle\n```\n\n```text\nevent\n```\n\n```text\nresolve\n```\n\n```text\nMaybePromise<Response>\n```\n\n```js\n// Maybe export this from elsewhere to not repeat it\ntype HandleParams = Parameters<Handle>[0];\n\nexport async function handle({ event, resolve }: HandleParams) : Promise<Response> {\n // ...\n}\n```\n\n```js\ntype HandleResult = ReturnType<Handle>;\n```\n\n```text\nexport async function\n```\n\n```text\nHandle\n```\n\n```text\nMaybePromise<T>\n```\n\n```text\nPromise\n```\n\n```text\nasync\n```\n\n```text\nParameters\n```\n\n```text\nHandle\n```\n\n```text\nimport type { Handle } from '@sveltejs/kit';\n\nexport const handle = (async ({ event, resolve }) => {\n if (event.url.pathname.startsWith('/custom')) {\n return new Response('custom response');\n }\n\n const response = await resolve(event);\n return response;\n}) satisfies Handle;\n```\n\n========================================\n\nComments:\n- Your attempt to type the arguments would not work because the function only has one argument with multiple properties. If an argument contains curly braces that means it is immediately being destructured.\n- I thought about suggesting something like this but you have to duplicate the return type anyway\n- Why use `satisfies` instead of just typing it as I suggested in my answer? Side note: try not to start an answer with \"I think\", if you post an answer, you should be fairly confident. \"I think\" is OK for comments.\n- I was giving the example verbatim as found in the SvelteKit documentation. I'll play around with this later and see if there's any benefit to using 'satisfies'. Thanks for your side note, but do you realize your answer starts with \"I think\"?\n- That is pretty funny. However, they are two very different cases of \"I think\". I'm not saying \"I think this will solve your problem\". You are saying you think but you are not sure if your answer is correct. I'm saying \"I think your question is misguided and here's why\". I'm politely rephrasing their question more accurately.\n- I didn't write the example, so I cannot fully speak as why they wrote it as such... but I would guess it's because they wanted to demonstrate that shape needed to match that type, but that it didn't need to necessarily be of that type.\n- I had never seen that button to see the code with typescript, and I was trying hard in my searches on Google and chatpgt Thanks for the photo!!!!!!!","metadata":{"transformedAt":"2026-08-18T18:33:40.682Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":202,"estimatedTokens":1258}}300{"id":"stack-66457961","source":"stackoverflow","questionId":66457961,"title":"Svelte: how to notify a child or sibling component","tags":["javascript","svelte"],"text":"Title: Svelte: how to notify a child or sibling component\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI know svelte is great for automatically updating components when some of its attributes change. But my scenario is slightly different. To simplify, let's say I have a parent Svelte component with two child components:\n\n```\n\n \n \n\n function handleClick() {\n (2)\n }\n\n```\n\nI want that when the user clicks a button inside ``, some function executes inside ``. What can I put in `(1)` and `(2)` to implement this behavior?\n\nAll I can think of is having a counter, incrementing it inside `handleClick` and pass the counter to ``, then use `$:` in `` to catch the change. But this would be a very contrived workaround. And of course I could move the code I want to execute from `` to the parent component, but that is even an uglier workaround, because `` is the one that really knows what to do.\n\n========================================\n\nCode:\n```html\n<div>\n <child1 onButtonClicked={handleClick} />\n <child2 (1) />\n</div>\n<script>\n function handleClick() {\n (2)\n }\n</script>\n```\n\n```text\n<child1>\n```\n\n```text\n<child2>\n```\n\n```text\n(1)\n```\n\n```text\n(2)\n```\n\n```text\nhandleClick\n```\n\n```text\n<child2>\n```\n\n```text\n$:\n```\n\n```text\n<child2>\n```\n\n```text\n<child2>\n```\n\n```text\n<child2>\n```\n\n```text\n<script>\n .....\n export const someFunc = () => console.log('someFunc');\n</script>\n\n....\n```\n\n```text\n<script>\n import Child1 ... \n import Child2 ...\n\n let child2;\n function handleClick() {\n child2.someFunc();\n }\n</script>\n\n<div>\n <Child1 onButtonClicked={handleClick} />\n <Child2 bind:this={child2} />\n</div>\n```\n\n```text\n<script>\n import Child1 ... \n import Child2 ...\n\n let child2;\n</script>\n\n<div>\n <Child1 onButtonClicked={child2.someFunc} />\n <Child2 bind:this={child2} />\n</div>\n```\n\n========================================\n\nComments:\n- Amazing, I didn't know that if I bind a component I get direct access to all its exported members.\n- After implementing it, I see that if the component hierarchy is complex (as is my case), then you end up passing events up and invocations down across all the hierarchy. I assume that Redux-like techniques are the solution to avoid this kind of complexity, is that correct?\n- I'have never used redux. But you can use a reactive Svelte store to pass data around without hierarchy hassle.\n- The only problem I see with using a store is if Child2 will be used in more than one place, but with different data in each place. If this is not the case, then a store isn't necessary either. You can just `export const someFunc ...` in Child 2, then `import {someFunc} from`Child2.svelte` in the parent. Voscausa's answer is the gold star if you specifically need the method from the component instance.","metadata":{"transformedAt":"2026-08-18T18:33:40.682Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":124,"estimatedTokens":694}}301{"id":"stack-66320707","source":"stackoverflow","questionId":66320707,"title":"Accessing svelte store with $ notation causing Reference Error","tags":["store","svelte"],"text":"Title: Accessing svelte store with $ notation causing Reference Error\nTags: store, svelte\nSource: Stack Overflow\n\nQuestion:\nI have a `store.js` file whose content is :\n\n```\nimport { writable } from 'svelte/store';\nexport const generateds = writable(0);\n\nconsole.log(\"generateds\", $generateds)\n```\n\nEach time I try to access $generateds (inside or outside this file) I get this error :\n\n```\nUncaught ReferenceError: $generateds is not defined\n at stores.js:4\n at main.js:6\n```\n\nWhen I use a store in a new project, there is no problem. I can't find what's the problem in my current project.\n\nHere is the list of the npm packages I'm using :\n\n```\n── @fortawesome/free-solid-svg-icons@5.14.0\n├── @material/layout-grid@7.0.0\n├── @mdi/js@5.9.55\n├── @rollup/plugin-commonjs@17.1.0\n├── @rollup/plugin-node-resolve@11.2.0\n├── @smui/button@1.0.0\n├── @smui/card@1.0.0\n├── @smui/drawer@1.0.0\n├── @smui/fab@1.0.0\n├── @smui/icon-button@1.0.0\n├── @smui/list@1.0.0\n├── @smui/select@1.0.0\n├── @smui/textfield@1.0.0\n├── @smui/top-app-bar@1.0.0\n├── @sveltejs/svelte-virtual-list@3.0.1\n├── autoprefixer@9.8.6\n├── dropzone@5.7.2\n├── eslint-plugin-svelte3@2.7.3\n├── eslint@7.9.0\n├── firebase@7.24.0\n├── firestore-export-import@0.10.0\n├── mathlive@0.59.0\n├── node-sass@4.14.1\n├── postcss@8.2.6\n├── query-string@6.13.2\n├── rollup-plugin-analyzer@4.0.0\n├── rollup-plugin-css-only@3.1.0\n├── rollup-plugin-livereload@2.0.0\n├── rollup-plugin-postcss@4.0.0\n├── rollup-plugin-sass@1.2.2\n├── rollup-plugin-svelte@7.1.0\n├── rollup-plugin-terser@7.0.2\n├── rollup@2.39.0\n├── sass@1.32.7\n├── sirv-cli@1.0.11\n├── svelte-fa@2.1.1\n├── svelte-loading-spinners@0.1.1\n├── svelte-materialify@0.3.5\n├── svelte-preprocess@4.6.9\n├── svelte-routing@1.5.0\n├── svelte@3.32.3\n```\n\n========================================\n\nTop Answer:\nYou can use `$generateds` only in `.svelte` components.\n\nIf you'd like to get the value of the store outside of a svelte component you can use `generateds.subscribe()` or `get(generateds)`.\n\nSo you'r example can look like:\n\n```\nimport { writable, get } from 'svelte/store';\nexport const generateds = writable(0);\n\nconsole.log(\"generateds\", get(generateds))\n```\n\n========================================\n\nCode:\n```text\nimport { writable } from 'svelte/store';\nexport const generateds = writable(0);\n\nconsole.log(\"generateds\", $generateds)\n```\n\n```text\nUncaught ReferenceError: $generateds is not defined\n at stores.js:4\n at main.js:6\n```\n\n```text\n── @fortawesome/free-solid-svg-icons@5.14.0\n├── @material/layout-grid@7.0.0\n├── @mdi/js@5.9.55\n├── @rollup/plugin-commonjs@17.1.0\n├── @rollup/plugin-node-resolve@11.2.0\n├── @smui/button@1.0.0\n├── @smui/card@1.0.0\n├── @smui/drawer@1.0.0\n├── @smui/fab@1.0.0\n├── @smui/icon-button@1.0.0\n├── @smui/list@1.0.0\n├── @smui/select@1.0.0\n├── @smui/textfield@1.0.0\n├── @smui/top-app-bar@1.0.0\n├── @sveltejs/svelte-virtual-list@3.0.1\n├── autoprefixer@9.8.6\n├── dropzone@5.7.2\n├── eslint-plugin-svelte3@2.7.3\n├── eslint@7.9.0\n├── firebase@7.24.0\n├── firestore-export-import@0.10.0\n├── mathlive@0.59.0\n├── node-sass@4.14.1\n├── postcss@8.2.6\n├── query-string@6.13.2\n├── rollup-plugin-analyzer@4.0.0\n├── rollup-plugin-css-only@3.1.0\n├── rollup-plugin-livereload@2.0.0\n├── rollup-plugin-postcss@4.0.0\n├── rollup-plugin-sass@1.2.2\n├── rollup-plugin-svelte@7.1.0\n├── rollup-plugin-terser@7.0.2\n├── rollup@2.39.0\n├── sass@1.32.7\n├── sirv-cli@1.0.11\n├── svelte-fa@2.1.1\n├── svelte-loading-spinners@0.1.1\n├── svelte-materialify@0.3.5\n├── svelte-preprocess@4.6.9\n├── svelte-routing@1.5.0\n├── svelte@3.32.3\n```\n\n```text\nstore.js\n```\n\n```js\nimport { generateds } from './store.js';\nimport { get } from 'svelte/store';\n\n// method 1\nconst unsubscribe = generateds.subscribe((val) => { console.log(val); });\nunsubscribe();\n\n// method 2\nconsole.log(get(generateds));\n```\n\n```text\nimport { writable, get } from 'svelte/store';\nexport const generateds = writable(0);\n\nconsole.log(\"generateds\", get(generateds))\n```\n\n```text\n$generateds\n```\n\n```text\n.svelte\n```\n\n```text\ngenerateds.subscribe()\n```\n\n```text\nget(generateds)\n```\n\n```text\nimport { writable } from \"svelte/types/runtime/store\";\n```\n\n```text\nimport { writable } from 'svelte/store';\n```\n\n========================================\n\nComments:\n- what about this then: You're not limited to using $count inside the markup, either — you can use it anywhere in the as well, such as in event handlers or reactive declarations. svelte.dev/tutorial/auto-subscriptions\n- , event handlers, and reactive declarations are all still inside Svelte components (.svelte files). Inside a Svelte component you can use the $ syntax to auto-subscribe to the store; everywhere else (.js or .ts files) you need to manually subscribe.\n- ah I see, I think I missed the fact that the OP was not inside a svelte component when I responded\n- I am getting the same error but I want to set the value instead of get Is there any option or alternative to set writable store outside .svelte component ?\n- Thx, important notice on the get function that it `subscribes to the store to get the value and immediately unsubscribes` which can break your code if you expect that it works like $subsribedVar.","metadata":{"transformedAt":"2026-08-18T18:33:40.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":201,"estimatedTokens":1285}}302{"id":"stack-73397838","source":"stackoverflow","questionId":73397838,"title":"Migrate to SvelteKit's New Routing System","tags":["svelte","sveltekit"],"text":"Title: Migrate to SvelteKit's New Routing System\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nDon't know about you, but I've been hearing about this new routing system in SvelteKit. I first heard about this with the `+error.svelte` file that I found here on the official docs. Not soon enough, I've also seen the other files like the `__layout.svelte` file having a `+` sign in front of it's filename like this: `+layout.svelte` on the docs.\n\nSo I've been wondering:\n\n- **How do I migrate from the SvelteKit's old routing system to this updated routing system?**\nIf possible, how to let SvelteKit do it\nautomatically?\n\n- **What's the importance of this new routing system?**\n\n========================================\n\nTop Answer:\nI am still a beginner at web development so need the exact steps spelled out. Here are the commands I actually ran to migrate my simple project:\n\nUpdate to the version before the routing changes:\n\n```\nnpm install @sveltejs/kit@1.0.0-next.405\n```\n\nBuild your project and fix any issues until it works. My project was simple, so the only changes were to package.json and the project still built and ran fine. Commit those changes.\n\nRun the migrate script:\n\n```\nnpx svelte-migrate routes\n```\n\nThat script will run and then print the following instructions:\n\n```\n1: git commit -m \"svelte-migrate: renamed files\"\n 2: Review the migration guide at https://github.com/sveltejs/kit/discussions/5774\n 3: Search codebase for \"@migration\" and manually complete migration tasks\n 4: git add -A\n 5: git commit -m \"svelte-migrate: updated files\"\n```\n\nAfter running that script my project would build but does not work. My project was too simple to have any \"@migration\" comments. Presumably, you need to make the migration changes following the guide without really knowing if they worked or not.\n\nFinally, install the version with the new routing changes:\n\n```\nnpm install @sveltejs/kit@1.0.0-next.406\n```\n\nWithout any additional changes in my project, my project built and ran successfully. Again, only the package.json changed and I committed it.\n\n========================================\n\nCode:\n```text\n+error.svelte\n```\n\n```text\n__layout.svelte\n```\n\n```text\n+\n```\n\n```text\n+layout.svelte\n```\n\n```text\nnpm install @sveltejs/kit@1.0.0-next.405\n```\n\n```text\nnpx svelte-migrate routes\n```\n\n```text\ny\n```\n\n```text\nnpx svelte-migrate routes\n```\n\n```text\n@sveltejs/kit@next.405\n```\n\n```text\n@migration\n```\n\n```text\nsrc/routes/foo.svelte\n```\n\n```text\nsrc/routes/foo/index.svelte\n```\n\n```text\nindex.svelte\n```\n\n```text\nfoo.svelte\n```\n\n```text\nfoo.svelte\n```\n\n```text\nfoo/index.svelte\n```\n\n```text\nnpm install @sveltejs/kit@1.0.0-next.405\n```\n\n```text\nnpx svelte-migrate routes\n```\n\n```text\n1: git commit -m \"svelte-migrate: renamed files\"\n 2: Review the migration guide at https://github.com/sveltejs/kit/discussions/5774\n 3: Search codebase for \"@migration\" and manually complete migration tasks\n 4: git add -A\n 5: git commit -m \"svelte-migrate: updated files\"\n```\n\n```text\nnpm install @sveltejs/kit@1.0.0-next.406\n```\n\n========================================\n\nComments:\n- For anyone else that also doesn't know how to do the very first step, the command is: `npm install @sveltejs/kit@1.0.0-next.405`","metadata":{"transformedAt":"2026-08-18T18:33:40.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":145,"estimatedTokens":809}}303{"id":"stack-76877498","source":"stackoverflow","questionId":76877498,"title":"How do I import Bootstrap in SvelteKit, Recommended Way?","tags":["javascript","bootstrap-5","svelte","sveltekit"],"text":"Title: How do I import Bootstrap in SvelteKit, Recommended Way?\nTags: javascript, bootstrap-5, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am building a site with SvelteKit. As of now I included Bootstrap 5 in my project by adding it to the app.html file provided by the SvelteKit Skeleton project:\n\n```\n \n\n```\n\nNow when building the site with `npm run build` the bootstrap modules are not loaded anymore.\n\n========================================\n\nTop Answer:\nIMO, I would neither add bootstrap through an import statement or using `svelte-add`. I would use sveltestrap so that you don't need JQuery, Bootstraps JS, & Bootstrap component classes. You still need to import their styles directly though which can be put in `+layout.svelte` as already stated.\n\n========================================\n\nCode:\n```text\n<!-- Bootstrap styles and javascript --> \n<link rel=\"stylesheet\" href=\"/node_modules/bootstrap/dist/css/bootstrap.min.css\">\n<script src=\"/node_modules/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n```\n\n```text\nnpm run build\n```\n\n```html\n<script>\n import 'bootstrap/dist/css/bootstrap.min.css';\n import 'bootstrap/dist/js/bootstrap.bundle.min.js';\n</script>\n<slot />\n```\n\n```js\nimport Alert from 'bootstrap/js/dist/alert';\n\n// or, specify which plugins you need:\nimport { Tooltip, Toast, Popover } from 'bootstrap';\n```\n\n```html\n<script>\n import 'bootstrap/dist/css/bootstrap.css';\n import scriptSrc from 'bootstrap/dist/js/bootstrap.bundle.js?url';\n</script>\n<svelte:head>\n <script src={scriptSrc}></script>\n</svelte:head>\n<slot />\n```\n\n```text\n+layout.svelte\n```\n\n```text\nhead\n```\n\n```text\ndefer\n```\n\n```text\nasync\n```\n\n```bash\nnpx svelte-add@latest bootstrap\n```\n\n```bash\nnpm install\n```\n\n```text\nsvelte-add\n```\n\n```text\nsvelte-add\n```\n\n```text\n+layout.svelte\n```\n\n```html\n<script lang=\"ts\">\n import \"bootstrap/scss/bootstrap.scss\";\n</script>\n```\n\n```text\n+layout.svelte\n```\n\n```text\nnpm run dev\n```\n\n```text\nsass-embedded\n```\n\n========================================\n\nComments:\n- What about using npm getbootstrap.com/docs/3.3/getting-started/#download-npm?\n- There exist libraries like `sveltestrap`, that wrap Bootstrap for Svelte usage by the way.\n- @evolutionxbox I used npm to install bootstrap, my problem is I dont know how to include / import it properly so its still recognized after I build the site\n- @H.B. Unfortunately I found out about this after I finished my site. From what I can tell is that I would have to rewrite the bootstrap components I used in my site which is too much work for me\n- Thank you for your advice. I tried the last one and now use the URL-import and everything seems to be working. Thank you very much :)\n- SASS import is not problem, the JS is problematic, with its \"document\" references which won't work in SSR.\n- This doesn't work with bootstrap JS.","metadata":{"transformedAt":"2026-08-18T18:33:40.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":122,"estimatedTokens":708}}304{"id":"stack-74455559","source":"stackoverflow","questionId":74455559,"title":"How to monitor a variable and run a function every time the variable changes?","tags":["svelte","sveltekit"],"text":"Title: How to monitor a variable and run a function every time the variable changes?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nIt will be like the `on:change` event.\n\nI am not using this event because in some svelte libraries this event is not emitted, and the implication is to use binding and `$`.\n\nHowever, it seems that Svelte doesn't have a clean syntax for it.\n\nI can only think of something like\n\n```\n$: {\n if (variable) {\n doSomething();\n }\n}\n```\n\nwhere every time `variable`'s value changes, `doSomething()` will run.\n\nBut the use of `if` statement is weird.. What if `variable` is a boolean? This way the function won't run when the variable's value is false.\n\nThe idea is to run the function every time the variable's value changes, no matter what the new value actually is.\n\nI also tried\n\n```\n$: doSomething(variable);\n```\n\nIt works, but it is also weird because the function `doSomething` may not need an argument. In this case, the argument is purely for adding the `variable` as a dependency of this `$` syntax...\n\nAlso tried the answer in https://stackoverflow.com/a/56987526/11752443, but this one simply doesn't work. And it is not mentioned in the doc (https://stackoverflow.com/a/56987526/11752443) either.\n\nThanks in advance!\n\n========================================\n\nTop Answer:\n### Svelte 5 Answer\n\n### Best Solution:\n\nJust put this in a file that supports svelte rune magic.\n\n```\n// whatever.svelte.ts\nexport const subscribe = (functionToState: () => T, callback: (v: T) => void) => {\n let value = writable(functionToState());\n value.subscribe(callback);\n\n $effect(() => {\n value.set(functionToState());\n });\n};\n```\n\nAnd you can use it like this:\n\n```\n\n let first_name = $state('');\n subscribe(\n () => first_name,\n (v) => {\n console.log('first_name = ', v);\n }\n );\n\n```\n\n**NOTE**: Why you couldn't make it like:\n\n```\nsubscribe(\n first_name, // change with before is here\n (v) => {\n console.log('first_name = ', v);\n }\n);\n```\n\nBecause it is actually passing just a string to the subscribe function in this case but if you wrap it in a function, it passes the reference to that state. (svelte magic)\n\n### Second Solution (With a Component)\n\nYou could come up with a component like this:\n\n```\n\n interface Props {\n value: T;\n onchanged: (value: T) => void;\n }\n\n let { value, onchanged = $bindable() }: Props = $props();\n\n $effect(() => onchanged(value));\n\n```\n\nThen you can use it in your code:\n\n```\n\n let first_name = $state(\"\")\n\n {\n console.log('first_name changed to: ', v);\n }}\n/>\n```\n\nJust to come up with a little bit explanation for the `Observer` component, in the component you don't need to check for value changes by hand because it is already done by `$effect`. But still you could have some questions. like:\n\nWhy not something like this then:\n\n```\n\n let first_name = $state(\"\")\n\n const onchanged = (v: string) => {console.log(`new variable change: ${v}`)}\n $effect(() => onchanged(value));\n\n```\n\nThis example is completely valid but... Another problem appear when you add another reactive state into the `onchanged` function. example:\n\n```\n\n let first_name = $state(\"\")\n let last_name = $state(\"\")\n\n const onchanged = (v: string) => {console.log(`new variable change: ${v} ${last_name}`)}\n $effect(() => onchanged(value));\n\n```\n\nNow `onchanged` function also runs every time the `last_name` state changes too. (This doesn't happen in svelte 4)\nI fixed it with having the function call happen from another component. And it works.\n\nStill recommend the first solution, but if you are happy with component approach, it is ok.\n\n========================================\n\nCode:\n```text\n$: {\n if (variable) {\n doSomething();\n }\n}\n```\n\n```text\n$: doSomething(variable);\n```\n\n```text\non:change\n```\n\n```text\n$\n```\n\n```text\nvariable\n```\n\n```text\ndoSomething()\n```\n\n```text\nif\n```\n\n```text\nvariable\n```\n\n```text\ndoSomething\n```\n\n```text\nvariable\n```\n\n```text\n$\n```\n\n```text\n$: variable, doSomething()\n```\n\n```js\n// whatever.svelte.ts\nexport const subscribe = <T>(functionToState: () => T, callback: (v: T) => void) => {\n let value = writable<T>(functionToState());\n value.subscribe(callback);\n\n $effect(() => {\n value.set(functionToState());\n });\n};\n```\n\n```html\n<script lang=\"ts\">\n let first_name = $state('');\n subscribe(\n () => first_name,\n (v) => {\n console.log('first_name = ', v);\n }\n );\n</script>\n```\n\n```js\nsubscribe(\n first_name, // change with before is here\n (v) => {\n console.log('first_name = ', v);\n }\n);\n```\n\n```html\n<!-- Observer.svelte -->\n<script lang=\"ts\" generics=\"T\">\n interface Props {\n value: T;\n onchanged: (value: T) => void;\n }\n\n let { value, onchanged = $bindable() }: Props = $props();\n\n $effect(() => onchanged(value));\n</script>\n```\n\n```html\n<script lang=\"ts\">\n let first_name = $state(\"\")\n</script>\n\n<Observer\n value={first_name}\n onchanged={(v) => {\n console.log('first_name changed to: ', v);\n }}\n/>\n```\n\n```html\n<script lang=\"ts\">\n let first_name = $state(\"\")\n\n const onchanged = (v: string) => {console.log(`new variable change: ${v}`)}\n $effect(() => onchanged(value));\n</script>\n```\n\n```html\n<script lang=\"ts\">\n let first_name = $state(\"\")\n let last_name = $state(\"\")\n\n const onchanged = (v: string) => {console.log(`new variable change: ${v} ${last_name}`)}\n $effect(() => onchanged(value));\n</script>\n```\n\n```text\nObserver\n```\n\n```text\n$effect\n```\n\n```text\nonchanged\n```\n\n```text\nonchanged\n```\n\n```text\nlast_name\n```\n\n========================================\n\nComments:\n- Ah.. You are right. It wasn't working because I used anonymous function like `$: name, () => {console.log(new Date())}`. This form doesn't work and there is no error, so I thought the approach didn't work as a whole. Thanks for correcting me.\n- Note that the function also runs on initial load, not only after variable change. Sometimes this behaviour in undesirable\n- @pumbo what would be the correct workaround for when the function runs on load?","metadata":{"transformedAt":"2026-08-18T18:33:40.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":306,"estimatedTokens":1513}}305{"id":"stack-74390842","source":"stackoverflow","questionId":74390842,"title":"Can you stop a page from reloading on form submit without preventDefault with svelte kit?","tags":["javascript","svelte","sveltekit"],"text":"Title: Can you stop a page from reloading on form submit without preventDefault with svelte kit?\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI want to display a toast for a few seconds whenever a user does something, eg. when they log in to the app. I am using a form on `/login/+page.svelte` to login, with the database interaction in `/login/page.server.js`. And I am using a `writable store` to store toasts.\n\nOn form submit, the page refreshes, so my store is cleared and the toast is lost. It seems the event flow is:\n\n- submit form to `/login/page.server.js`\n\n- `page.server.js` does some stuff\n\n- `page.server.js` sends back the full page and the browser reloads to the new full page.\n\nI understand you can use `preventdefault` to prevent all those steps, but I only want to prevent the reloading. Preventing everything does not seem optimal (there are probably some other stuff I don't even know I'm preventing).\n\nIs there a nicer way of interacting between a `page.svelte` and a `page.server.js` without reload (and thus clearing, probably all, stores) than preventdefault + using a manual fetch?\n\nREPL I was playing around with that demonstrates the toast staying full 3 seconds generally, but immediately disappearing on normal form submit.\nhttps://svelte.dev/repl/8b61434332ca471b83cbf039bf1f3fc9?version=3.22.0\n\n========================================\n\nCode:\n```text\n/login/+page.svelte\n```\n\n```text\n/login/page.server.js\n```\n\n```text\nwritable store\n```\n\n```text\n/login/page.server.js\n```\n\n```text\npage.server.js\n```\n\n```text\npage.server.js\n```\n\n```text\npreventdefault\n```\n\n```text\npage.svelte\n```\n\n```text\npage.server.js\n```\n\n```text\nenhance\n```\n\n========================================\n\nComments:\n- Are there any examples?\n- @ramory-l: See the linked docs.","metadata":{"transformedAt":"2026-08-18T18:33:40.683Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":70,"estimatedTokens":450}}306{"id":"stack-63696841","source":"stackoverflow","questionId":63696841,"title":"Svelte: How to pass data or props from a child component to the parent?","tags":["javascript","svelte","svelte-3","svelte-component"],"text":"Title: Svelte: How to pass data or props from a child component to the parent?\nTags: javascript, svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI'll try to be brief.\nI'm having the main component app.svelte. Inside it I'm using a child component called Course.svelte. I'm using an {#each} block to repeat the same component many times. The thing is I want the app.svelte to know whenever a single component is on:clicked.\nRight now I'm handling the on:click event in the Course.svelte component. And like this, App.svelte won't ever know about it.\nWhat should I do?\n\nA snippet of Course.svelte and how I'm handling the on:click event:\n\n```\n\n function handleClick() {\n if (state == courseStates.CLOSED) {\n //Handle closed course\n } else {\n if (state === courseStates.READY) {\n passCourse();\n } else if (state === courseStates.PASS) {\n failCourse();\n }\n }\n }\n function passCourse() {\n state = courseStates.PASS;\n }\n function failCourse() {\n state = courseStates.READY;\n }\n\n \n\n### {name}\n\n \n\n### {code} - {credit} Credit Hours - Term {term}\n\n```\n\nA snippet of App.svelte where I want to maintain the state of each course as it changes over time by clicking the course:\n\n```\n\n {#each courses as course}\n {#if course.term == term}\n \n {/if}\n {/each}\n \n```\n\n========================================\n\nCode:\n```text\n<script>\n function handleClick() {\n if (state == courseStates.CLOSED) {\n //Handle closed course\n } else {\n if (state === courseStates.READY) {\n passCourse();\n } else if (state === courseStates.PASS) {\n failCourse();\n }\n }\n }\n function passCourse() {\n state = courseStates.PASS;\n }\n function failCourse() {\n state = courseStates.READY;\n }\n</script>\n\n<div on:click={handleClick} class=\"text-center course btn {buttonClass}\">\n <h1>{name}</h1>\n <h4>{code} - {credit} Credit Hours - Term {term}</h4>\n</div>\n```\n\n```text\n<div class=\"row\">\n {#each courses as course}\n {#if course.term == term}\n <Course\n state={course.state}\n name={course.name}\n credit={course.credit}\n term={course.term}\n code={course.code}\n on:removecourse={removeCourse} />\n {/if}\n {/each}\n </div>\n```\n\n```text\nbind:state={course.state}\n```\n\n```text\nstore\n```\n\n```text\ncreateEventDispatcher\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.683Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":111,"estimatedTokens":581}}307{"id":"stack-55895384","source":"stackoverflow","questionId":55895384,"title":"How to tell if a Svelte component is entirely static content?","tags":["javascript","svelte"],"text":"Title: How to tell if a Svelte component is entirely static content?\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm working on a static site generator where I'd like to be able to support both reactive JavaScript interaction and standard load-a-fresh-page-into-the-browser hyperlinks. It occurred to me that something like Svelte might be a good fit for this; I could use the server-side rendering support to generate HTML for all my pages, and then I could compile and ship JavaScript components with `hydratable: true` to support the dynamic features.\n\nOne issue I thought of with this approach is that most of my project's components will be entirely static content: just HTML and hyperlinks, without any state or event handlers, and I won't change the props except when I generate a new HTML file for a different page. If I naively generate JavaScript to hydrate all those components at page load time, I could end up with a much larger bundle (and more work done at runtime) than I actually need.\n\nDoes Svelte offer any way to optimize this situation? Can I somehow check if a component is a pure function of its props so I can avoid hydrating it if I don't need to? Or is the compiler smart enough to do that for me?\n\n========================================\n\nCode:\n```text\nhydratable: true\n```\n\n```html\n<script>\n export let name;\n</script>\n\n<h1>Hello {name}!</h1>\n```\n\n```html\n<Greeting name=\"world\"/>\n```\n\n```text\nsvelte.compile(...)\n```\n\n```text\nvars\n```\n\n```text\nname\n```\n\n```text\n<Greeting>\n```\n\n```text\nname\n```\n\n```text\n{name}\n```\n\n```text\nworld\n```\n\n```text\nvars\n```\n\n```text\nsvelte.compile(...)\n```\n\n```text\nast\n```\n\n========================================\n\nComments:\n- Hi! I think such a feature would be a massive improvement that can really differentiate svelte from other frameworks or libs. You will not only get a smaller bundle, if you need to hydrate the app at the client, it would be great to strip the non used properties from the initial data object. If your site is SEO focused and it is mainly static content but sign up forms or similar interactive stuff, this is ideal. Is there any roadmap for Svelte to see the upcoming features or possibilities to contribute according to it?","metadata":{"transformedAt":"2026-08-18T18:33:40.683Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":74,"estimatedTokens":557}}308{"id":"stack-67758422","source":"stackoverflow","questionId":67758422,"title":"\"Semicolon or block is expected\" error when using tailwind responsive classes in svelte-kit style tags","tags":["svelte","tailwind-css","sveltekit"],"text":"Title: \"Semicolon or block is expected\" error when using tailwind responsive classes in svelte-kit style tags\nTags: svelte, tailwind-css, sveltekit\nSource: Stack Overflow\n\nQuestion:\nWhen using tailwind responsive classes (ex: `md:my-auto`, `focus:ring-0`, `focus:outline-none`) in svelte kit component style tags, I get the following error:\n\n```\n500\n\nSemicolon or block is expected\n\nParseError: Semicolon or block is expected\n at error (/var/www/html/node_modules/svelte/compiler.js:16752:20)\n at Parser$1.error (/var/www/html/node_modules/svelte/compiler.js:16828:10)\n at Object.read_style [as read] (/var/www/html/node_modules/svelte/compiler.js:13141:21)\n at tag (/var/www/html/node_modules/svelte/compiler.js:15887:34)\n at new Parser$1 (/var/www/html/node_modules/svelte/compiler.js:16787:22)\n at parse$3 (/var/www/html/node_modules/svelte/compiler.js:16919:21)\n at compile (/var/www/html/node_modules/svelte/compiler.js:30012:18)\n at compileSvelte (/var/www/html/node_modules/@sveltejs/vite-plugin-svelte/dist/index.js:244:48)\n at async TransformContext.transform (/var/www/html/node_modules/@sveltejs/vite-plugin-svelte/dist/index.js:837:27)\n at async Object.transform (/var/www/html/node_modules/vite/dist/node/chunks/dep-6b5f3ba8.js:44285:30)\n```\n\nHere is the code for my component:\n\n```\n\n export let switched = false;\n\n{switched = !switched}}>\n **\n **\n\n .switch-button {\n @apply border-none appearance-none md:my-auto my-2 font-bold text-center rounded-full h-12 w-12 bg-red-500 text-white;\n }\n .switch-button:focus{\n @apply outline-none;\n }\n .switch-button:active{\n @apply bg-red-300;\n }\n\n```\n\nI'm unsure what's causing this issue in particular. I have a feeling it might just be a svelte-kit bug. I know there are work arounds like using vanilla css for responsiveness instead of tailwind classes, or using an external css files, but I would rather not use those options as I very much like the tailwind classes.\n\nPlease let me know if you know what's happening here, or if you need more information regarding my projects environment, please let me know. Thanks in advance!\n\nLink to my projects source code: https://github.com/DriedSponge/GorillianCurrencyConversion\n\nVersion information:\n\n- svelte-kit: `1.0.0-next.109`\n\n- tailwindcss: `2.1.2`\n\n- vite: `2.3.4`\n\n(I do have jit enabled on tailwind)\n\n========================================\n\nTop Answer:\nFaced the same error. Had everything set up exactly like @person_v1.32 described, the build was working fine, but `VSCode` gave me the error.\nTurned out for me it was caused by using a `monorepo` where svelte was used in a module/package only.\n\nFix ? Specifying the `postcss/tailwind configs` with `absolute path`.\n\n- `svelte.config.js`:\n\n```\nimport sveltePreprocess from 'svelte-preprocess';\nimport { vitePreprocess } from '@sveltejs/vite-plugin-svelte';\n\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst postcssConfig = path.join(__dirname, 'postcss.config.cjs');\n\nexport default {\n preprocess: [\n vitePreprocess(),\n sveltePreprocess({\n postcss: {\n configFilePath: postcssConfig\n }\n })\n ]\n};\n```\n\n- `postcss.config.cjs`\n\n```\nconst tailwindcss = require('tailwindcss');\nconst autoprefixer = require('autoprefixer');\n\nconst path = require('path');\nconst tailwindConfig = path.join(__dirname, 'tailwind.config.cjs');\n\nconst config = {\n plugins: [\n //Some plugins, like tailwindcss/nesting, need to run before Tailwind,\n tailwindcss({ config: tailwindConfig }),\n //But others, like autoprefixer, need to run after,\n autoprefixer\n ]\n};\n\nmodule.exports = config;\n```\n\n========================================\n\nCode:\n```text\n500\n\nSemicolon or block is expected\n\nParseError: Semicolon or block is expected\n at error (/var/www/html/node_modules/svelte/compiler.js:16752:20)\n at Parser$1.error (/var/www/html/node_modules/svelte/compiler.js:16828:10)\n at Object.read_style [as read] (/var/www/html/node_modules/svelte/compiler.js:13141:21)\n at tag (/var/www/html/node_modules/svelte/compiler.js:15887:34)\n at new Parser$1 (/var/www/html/node_modules/svelte/compiler.js:16787:22)\n at parse$3 (/var/www/html/node_modules/svelte/compiler.js:16919:21)\n at compile (/var/www/html/node_modules/svelte/compiler.js:30012:18)\n at compileSvelte (/var/www/html/node_modules/@sveltejs/vite-plugin-svelte/dist/index.js:244:48)\n at async TransformContext.transform (/var/www/html/node_modules/@sveltejs/vite-plugin-svelte/dist/index.js:837:27)\n at async Object.transform (/var/www/html/node_modules/vite/dist/node/chunks/dep-6b5f3ba8.js:44285:30)\n```\n\n```html\n<script>\n export let switched = false;\n</script>\n<button class=\"switch-button transition-transform transform ease-in-out duration-300\" class:-rotate-180={switched}\n on:click={()=>{switched = !switched}}>\n <span class=\"text-2xl md:hidden\"><i class=\"fas fa-arrow-down\"></i></span>\n <span class=\"text-xl hidden md:inline\"><i class=\"fas fa-arrow-right\"></i></span>\n</button>\n<style lang=\"postcss\" type=\"text/postcss\">\n .switch-button {\n @apply border-none appearance-none md:my-auto my-2 font-bold text-center rounded-full h-12 w-12 bg-red-500 text-white;\n }\n .switch-button:focus{\n @apply outline-none;\n }\n .switch-button:active{\n @apply bg-red-300;\n }\n</style>\n```\n\n```text\nmd:my-auto\n```\n\n```text\nfocus:ring-0\n```\n\n```text\nfocus:outline-none\n```\n\n```text\n1.0.0-next.109\n```\n\n```text\n2.1.2\n```\n\n```text\n2.3.4\n```\n\n```text\nnpm install --save-dev postcss-load-config\n```\n\n```js\nimport adapter from '@sveltejs/adapter-static'\n// import the preprocessor\nimport preprocess from 'svelte-preprocess'\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // added these lines:\n preprocess: [\n preprocess({\n postcss: true,\n }),\n ],\n\n kit: {\n // hydrate the <div id=\"svelte\"> element in src/app.html\n target: '#svelte',\n adapter: adapter({\n // default options are shown\n pages: 'build',\n assets: 'build',\n fallback: null,\n }),\n },\n}\n\nexport default config\n```\n\n```html\n<script>\n import '../app.postcss'\n</script>\n<main>\n<-- rest of your layout -->\n</main>\n<style lang=\"postcss\">\n @import url('...');\n :global(body) {\n background-color: #0E1013;\n font-family: Roboto, sans-serif;\n }\n</style>\n```\n\n```text\nsvelte-preprocess\n```\n\n```text\npackage.json\n```\n\n```text\npostcss-load-config\n```\n\n```text\nsvelte-preprocess\n```\n\n```text\npostcss.config.js\n```\n\n```text\npostcss-load-config\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nsvelte-preprocess\n```\n\n```text\nsvelte.config.js\n```\n\n```text\n@tailwind\n```\n\n```text\n__layout.svelte\n```\n\n```text\napp.postcss\n```\n\n```text\napp.html\n```\n\n```text\n/src/src\n```\n\n```text\n__layout.svelte\n```\n\n```text\nsvelte-add\n```\n\n```text\n\"files.associations\": {\"*.svelte\": \"html\" }\n```\n\n```js\nimport sveltePreprocess from 'svelte-preprocess';\nimport { vitePreprocess } from '@sveltejs/vite-plugin-svelte';\n\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst postcssConfig = path.join(__dirname, 'postcss.config.cjs');\n\nexport default {\n preprocess: [\n vitePreprocess(),\n sveltePreprocess({\n postcss: {\n configFilePath: postcssConfig\n }\n })\n ]\n};\n```\n\n```js\nconst tailwindcss = require('tailwindcss');\nconst autoprefixer = require('autoprefixer');\n\nconst path = require('path');\nconst tailwindConfig = path.join(__dirname, 'tailwind.config.cjs');\n\nconst config = {\n plugins: [\n //Some plugins, like tailwindcss/nesting, need to run before Tailwind,\n tailwindcss({ config: tailwindConfig }),\n //But others, like autoprefixer, need to run after,\n autoprefixer\n ]\n};\n\nmodule.exports = config;\n```\n\n```text\nVSCode\n```\n\n```text\nmonorepo\n```\n\n```text\npostcss/tailwind configs\n```\n\n```text\nabsolute path\n```\n\n```text\nsvelte.config.js\n```\n\n```text\npostcss.config.cjs\n```\n\n========================================\n\nComments:\n- I have the same issue but only when running tests with jest. Have you managed to make it work with the tests ? here is my issue: stackoverflow.com/questions/68827337/…\n- This is not recommended anymore. See marketplace.visualstudio.com/… : If you added \"files.associations\": {\"*.svelte\": \"html\" } to your VSCode settings, remove it.","metadata":{"transformedAt":"2026-08-18T18:33:40.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":36,"totalLines":370,"estimatedTokens":2088}}309{"id":"stack-68050948","source":"stackoverflow","questionId":68050948,"title":"How do I import a Material Web Component in SvelteKit?","tags":["svelte","sveltekit"],"text":"Title: How do I import a Material Web Component in SvelteKit?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI followed the standard tutorial in sveltkit to create a Typescript Project for a basic template.\n\nI wanted to use Material Web Component Button.\n\nI `npm install @material/mwc-button`.\n\nThen I simply add the following to `routes/index.svelte`\n\n```\n\n import \"@material/mwc-button\";\n\n```\n\nTo which I get `SyntaxError: Cannot use import statement outside a module`.\n\nThis is driving me crazy as it's step one of my requirement and this is week 3 of being stuck. I don't know even where to start. Is this a vite problem, sveltekit problem, mwc problem? Any advice would be amazing.\n\n========================================\n\nCode:\n```text\n<script>\n import \"@material/mwc-button\";\n</script>\n```\n\n```text\nnpm install @material/mwc-button\n```\n\n```text\nroutes/index.svelte\n```\n\n```text\nSyntaxError: Cannot use import statement outside a module\n```\n\n```html\n<script>\n import { onMount} from 'svelte';\n onMount(async () => {\n await import('@material/mwc-button');\n })\n</script>\n\n<mwc-button>Button</mwc-button>\n```\n\n```text\nError when evaluating SSR module /node_modules/lit-html/lib/template-result.js: ReferenceError: window is not defined\n```\n\n```text\nwindow\n```\n\n```text\nmwc-button\n```\n\n========================================\n\nComments:\n- This is a similar solution I came to when I faced this issue, one problem though that I am experiencing is that there is a significant delay between the page loading and the web components loading. Because although the page returns from the server fully hydrated, the web components won't import until the code gets to this point on the client side. Is there a way to include the import in the header maybe?","metadata":{"transformedAt":"2026-08-18T18:33:40.683Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":71,"estimatedTokens":446}}310{"id":"stack-59218304","source":"stackoverflow","questionId":59218304,"title":"How to animate array values in svelte with tweened store?","tags":["svelte","svelte-3","svelte-component","svelte-store"],"text":"Title: How to animate array values in svelte with tweened store?\nTags: svelte, svelte-3, svelte-component, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI have a writable store with following data \n\n```\nlet array= writable({\n skills: [{\n id: 1,\n name: \"Wordpress\",\n knowledge: 0.9\n }, \n {\n id: 2,\n name: \"Js\",\n knowledge: 0.8\n } ]\n })\n```\n\nI want to animate progress bar according to KNOWLEDGE, im accessing knowledge in {#each } loop, but bar is not animated, beacause i have to pass tweened store object and set it value. So how to animate bar ? how to pass knowledge value in to tweened object set() method in loop ?\n\n========================================\n\nTop Answer:\nJust to add on to the answer by joshnuss above.\n\nSkillProgress.svelte needs one change:\n\nprogress.set(value)\n*should be*\n$: progress.set(value)\n\n========================================\n\nCode:\n```text\nlet array= writable({\n skills: [{\n id: 1,\n name: \"Wordpress\",\n knowledge: 0.9\n }, \n {\n id: 2,\n name: \"Js\",\n knowledge: 0.8\n } ]\n })\n```\n\n```html\n<!-- SkillProgress.svelte -->\n<script>\n import {tweened} from 'svelte/motion'\n\n export let value = 0\n\n const progress = tweened(0)\n\n progress.set(value)\n</script>\n\n<progress value={$progress}/>\n```\n\n```html\n<!-- App.svelte -->\n<script>\n import SkillProgress from './SkillProgress.svelte'\n import {writable} from 'svelte/store'\n\n const skills = writable([{\n id: 1,\n name: \"Wordpress\",\n knowledge: 0.9\n }, \n {\n id: 2,\n name: \"Js\",\n knowledge: 0.8\n }])\n</script>\n\n<ul>\n {#each $array.skills as skill}\n <li>\n {skill.name}\n <SkillProgress value={skill.knowledge}/>\n </li>\n {/each}\n</ul>\n```\n\n```text\ntweened()\n```\n\n```text\n<progress/>\n```\n\n```text\ntweened()\n```\n\n```text\nApp.svelte\n```\n\n```text\n<SkillProgress/>\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":115,"estimatedTokens":559}}311{"id":"stack-66945320","source":"stackoverflow","questionId":66945320,"title":"How to get user agent on load function in SvelteKit","tags":["svelte","svelte-component","sveltekit"],"text":"Title: How to get user agent on load function in SvelteKit\nTags: svelte, svelte-component, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI want to get the `user agent` on the `load function` to choose whether to perform server-side rendering or not depending on the visitor is `googlebot` or not.\n\nHow can I access it inside the `load function`?\n\nI'm using the latest version of SvelteKit which is 1.0.0.\n\n========================================\n\nTop Answer:\nNot allowed to comment yet but load({ request }) worked for me:\n\n```\n/** @type {import('./$types').PageLoad} */\nexport async function load({ request }) {\n const headers = request.headers;\n const userAgent = headers.get('user-agent');\n console.log('User agent:', userAgent);\n}\n```\n\nJSDoc import makes it typescript-friendly, for Oliver Dixon\n\n========================================\n\nCode:\n```text\nuser agent\n```\n\n```text\nload function\n```\n\n```text\ngooglebot\n```\n\n```text\nload function\n```\n\n```js\nexport function getSession(request) {\n return {\n userAgent: request.headers['user-agent']\n }\n}\n```\n\n```text\n<script context=\"module\">\n export async function load({ session }) {\n console.log(session.userAgent)\n }\n</script>\n```\n\n```text\nhooks.js\n```\n\n```text\nsrc\n```\n\n```text\nload function\n```\n\n```text\n/** @type {import('./$types').PageLoad} */\nexport async function load({ request }) {\n const headers = request.headers;\n const userAgent = headers.get('user-agent');\n console.log('User agent:', userAgent);\n}\n```\n\n========================================\n\nComments:\n- No need to use hooks for this purpose since request object is available to the load function by default, i.e. you could use load({ request }) instead of session and proceed.\n- Anyway to make this typescript friendly?\n- This is the correct way to do it. Thanks.\n- Note that this only works in +page.server.js, not +page.js","metadata":{"transformedAt":"2026-08-18T18:33:40.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":90,"estimatedTokens":470}}312{"id":"stack-63027877","source":"stackoverflow","questionId":63027877,"title":"Svelte store assignment calls default writable().set and then custom .set?","tags":["svelte","svelte-3","svelte-store"],"text":"Title: Svelte store assignment calls default writable().set and then custom .set?\nTags: svelte, svelte-3, svelte-store\nSource: Stack Overflow\n\nQuestion:\nRelevant REPL\n\nI have a simple writable store with a custom `set` method:\n\n```\nimport { writable } from 'svelte/store';\nfunction createState() {\n const {subscribe, set, update} = writable({a: 0, b: 0});\n return {\n subscribe,\n set: (newState) => {\n console.log(newState);\n // set(newState); // I would expect `state` to be unchanged without this\n }\n };\n};\n\nexport const state = createState();\n```\n\nWhen I call `state.set()`, the new value is logged to the console and the value of `state` does not actually change. This is what I expect.\n\nHowever, if I assign `$state = `, the value of `state` changes, and *then* `set` logs it to the console. Why (and how) does this happen, and is there a way around it without reimplementing `writable`?\n\nThanks!\n\n========================================\n\nTop Answer:\nIn the JS output of your REPL, you can see the following:\n\n```\nfunction instance($$self, $$props, $$invalidate) {\n let $state;\n component_subscribe($$self, state, $$value => $$invalidate(0, $state = $$value));\n set_store_value(state, $state.a = 1, $state); // changes the value of state?!\n set_store_value(state, $state = { d: 0 }); // ''\n state.set({ c: 0 }); // no effect, as expected\n return [$state];\n}\n```\n\nUsing the shorthand reactive assignment `$` compiles into `set_store_value()` calls, which is a svelte internal method defined thusly:\n\n```\nexport function set_store_value(store, ret, value = ret) {\n store.set(value);\n return ret;\n}\n```\n\nSo the assigned value is, in effect, passed on to your store's `set` function, as you would expect.\n\n**However**, you can see in the JS output above that the value ultimately returned is a *local* variable called `$state` (the `$` sign there is *not* a reactive modifier, just part of the name). During those `set_store_value()` calls, you can see that this local variable is assigned the same value that is passed on to your store's `set` method (in fact, the local variable is assigned that value, and then is itself passed on to the `set_store_value()` method):\n\n```\nset_store_value(state, $state.a = 1, $state); // changes the value of state?!\nset_store_value(state, $state = { d: 0 }); // ''\n```\n\nI expect this behavior to be some sort of optimistic look-ahead/resolution.\n\nPerhaps it is implied in the Svelte store contract that a value passed to a store's `set` method *must* in fact modify the store accordingly, in which case the optimistic resolution approach would always yield coherent results?\n\nHopefully Rich Harris (or another Svelte contributor) will see your question and provide a more definitive answer.\n\n========================================\n\nCode:\n```text\nimport { writable } from 'svelte/store';\nfunction createState() {\n const {subscribe, set, update} = writable({a: 0, b: 0});\n return {\n subscribe,\n set: (newState) => {\n console.log(newState);\n // set(newState); // I would expect `state` to be unchanged without this\n }\n };\n};\n\nexport const state = createState();\n```\n\n```text\nset\n```\n\n```text\nstate.set(<some new value>)\n```\n\n```text\nstate\n```\n\n```text\n$state = <some new value>\n```\n\n```text\nstate\n```\n\n```text\nset\n```\n\n```text\nwritable\n```\n\n```html\n<script>\n // import { state } from \"./stores.js\";\n\n let pojo = { a: 0, b: 0 };\n pojo.a = 1;\n pojo = {d: 0};\n\n //state.set({c: 0}); // no effect, as expected\n</script>\n\n<h1>state: {JSON.stringify(pojo)}</h1>\n```\n\n```text\nstate.set\n```\n\n```text\nstate: {\"d\":0}\n```\n\n```text\npojo\n```\n\n```text\n$state\n```\n\n```text\nstate.set\n```\n\n```text\n$state\n```\n\n```js\nfunction instance($$self, $$props, $$invalidate) {\n let $state;\n component_subscribe($$self, state, $$value => $$invalidate(0, $state = $$value));\n set_store_value(state, $state.a = 1, $state); // changes the value of state?!\n set_store_value(state, $state = { d: 0 }); // ''\n state.set({ c: 0 }); // no effect, as expected\n return [$state];\n}\n```\n\n```js\nexport function set_store_value(store, ret, value = ret) {\n store.set(value);\n return ret;\n}\n```\n\n```js\nset_store_value(state, $state.a = 1, $state); // changes the value of state?!\nset_store_value(state, $state = { d: 0 }); // ''\n```\n\n```text\n$<store>\n```\n\n```text\nset_store_value()\n```\n\n```text\nset\n```\n\n```text\n$state\n```\n\n```text\n$\n```\n\n```text\nset_store_value()\n```\n\n```text\nset\n```\n\n```text\nset_store_value()\n```\n\n```text\nset\n```\n\n```text\nset_store_value(state, $state.a = 1, $state);\n```\n\n```text\n$state.a = 1\n```\n\n```text\nset\n```\n\n```text\nupdate\n```\n\n========================================\n\nComments:\n- Thanks very much for the explanation! I've accepted this answer because it explains *why* this is the behavior. If anyone comes across this question and wants to know more about *what* is happening, Thomas and Andreas provided some excellent insight there as well. (Incidentally, I originally asked this question because I wanted updating my store to have side effects instead of/before assignment. It seems like that would not be Svelteish, and so I've restructured my app so that logic is moved elsewhere.)\n- The explanation turns out to be a lot simpler than I expected, and yet very logical. Thanks Rich!","metadata":{"transformedAt":"2026-08-18T18:33:40.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":236,"estimatedTokens":1326}}313{"id":"stack-70115545","source":"stackoverflow","questionId":70115545,"title":"Svelte passing number as prop","tags":["typescript","svelte"],"text":"Title: Svelte passing number as prop\nTags: typescript, svelte\nSource: Stack Overflow\n\nQuestion:\nI am new to Svelte and I am trying to pass a number value as prop. Here is the code below.\n\n```\n\n import Infobox from \"./Infobox.svelte\";\n\n```\n\n```\n\n export let taskCount: number;\n export let classCount: number;\n\n {taskCount} Tasks\n Class {classCount}\n\n```\n\nI am unable to pass the prop as a number and it is accepting only string like\n``.\n\nI am using typescript as well in this project.\n\nThanks in advance :)\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n import Infobox from \"./Infobox.svelte\";\n</script>\n\n<Infobox classCount=2 taskCount=6 />\n\n<style></style>\n```\n\n```text\n<script lang=\"ts\">\n export let taskCount: number;\n export let classCount: number;\n</script>\n\n<section>\n <div>{taskCount} Tasks</div>\n <div>Class {classCount}</div>\n</section>\n\n<style></style>\n```\n\n```text\n<Infobox classCount=\"2\" taskCount=\"6\" />\n```\n\n```text\n<Infobox classCount={2} taskCount={6} />\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.683Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":64,"estimatedTokens":253}}314{"id":"stack-73234052","source":"stackoverflow","questionId":73234052,"title":"How load() is supposed to be used","tags":["svelte","sveltekit"],"text":"Title: How load() is supposed to be used\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm trying to understand how SvelteKit renders my web app in different scenarios, and I'm a bit puzzled by `load()`.\n\nI created a page with a load function which calls an external API and uses the response as prop for the component. In `.svelte-kit/output/prerendered/pages/mypage.html` I can see that it has fetched the data during the build step, and prerendered my html using the response.\n\nWhen I then navigate to that page in my web app, the network tab tells me that it calls the external API before rendering it. So, what was the point of prerendering then?\n\nThe SvelteKit docs says:\n\nA component that defines a page or a layout can export a load function that runs before the component is created. This function runs both during server-side rendering and in the client, and allows you to fetch and manipulate data before the page is rendered, thus preventing loading spinners.\n\nI don't understand this. How can I prevent the loading spinner if its calling the API every time I navigate to the page? When is it supposed to use the prerendered html?\n\nThe whole concept of rendering both in the client and server doesn't make sense to me. The way I see it, I would want to prerender on the server if the data is static, but if it changes then I would want to call the API every time I go to the page (maybe with caching). But why would I want to do both??\n\n========================================\n\nTop Answer:\nDon't know if this is still relevant, but I had the same problem. As someone already mentioned `load` function is made to run on both server and client, **if you use +page.ts**, but, if you're using prerendering (SSG in Next.js terms), you can write your data fetching logic inside a `load` function in `+page.server.ts`. This file can have the same structure as your `+page.ts`, but will run **only** on the server: meaning if you use SSR, it will run on each request, but the server will do the heavy lifting and if you use SSG, it will run only at build time.\nThis way when you use client side routing, you will only receive the `_data.json` generated at build time and use that to populate the page component with required data (kinda like Next.js does it).\n\n========================================\n\nCode:\n```text\nload()\n```\n\n```text\n.svelte-kit/output/prerendered/pages/mypage.html\n```\n\n```text\nload\n```\n\n```text\nload\n```\n\n```text\nload\n```\n\n```text\n+page.server.ts/js\n```\n\n```text\nGET\n```\n\n```text\nload\n```\n\n```text\nload\n```\n\n```text\n+page.server.ts\n```\n\n```text\n+page.ts\n```\n\n```text\n_data.json\n```\n\n========================================\n\nComments:\n- But the page with the load function calls the external API the first time I navigate to it, so the prerendered version is not being used...? And as you said, components are loaded as needed, and this load function is called before this specific component is rendered ... which will call the external API! It still doesn't make sense...\n- What do you mean by \"navigate\"? Are you accessing the URL of the given page directly or does client-side routing happen before that?\n- It's an SPA, so I mean client side routing. I'm navigating to the home page first, and then clicking on a link which routes me (client side) to the component with the load function\n- As I said, the pre-rendered version will only ever be used on first load of the page, unless the application is deployed as a collection of completely static files without routing. If there is any navigation beforehand, by default the pre-rendered file will *not* be used.\n- I have updated my answer to hopefully be more precise and offer a solution if you just want to prevent those additional API calls.\n- Thanks for the clarification! My page depends on getting fresh data, so I suppose it doesn't make sense to prerender it then? I understand that if the data is static, then yeah it makes sense to prerender it to reduce load time. But it still doesn't make sense to me to do both. If I need fresh data from the API, then why would I want to fetch and cache the response during build time? Sorry if I'm slow and just not \"getting it\".\n- You probably wouldn't. Doing that only makes sense if the load speed is more important than getting stale data. I doubt that there are many scenarios where people would opt for that. Server-side rendering usually makes sense, but pre-rendering has fewer, very specific use cases (e.g. blog articles or documentation, anything more document than application).","metadata":{"transformedAt":"2026-08-18T18:33:40.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":86,"estimatedTokens":1133}}315{"id":"stack-63491647","source":"stackoverflow","questionId":63491647,"title":"How to use `slot` in svelte storybook","tags":["components","svelte","storybook"],"text":"Title: How to use `slot` in svelte storybook\nTags: components, svelte, storybook\nSource: Stack Overflow\n\nQuestion:\nHow can I add a svelte storybook story for the following component with the slot.\n\nButton.svelte\n\n```\n\n \n\n```\n\nWhich I can use as\n\n```\n\n import Button from './Button.svelte';\n\nHello World\n```\n\nHow can I create a story for such components which has **slots** in it?\n\n========================================\n\nTop Answer:\nI used **npx sb init** command in order to add storybook to my svelte component lib. Below story definiton works for my SuccessLabel component:\n\n```\n\n \n\n div {\n position: relative;\n color: white;\n background-color: #28a745;\n border-color: #28a745;\n margin-top: -3px;\n padding: 10px;\n border-radius: 5px;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n font-size: 12px;\n }\n\n import { Meta, Story } from \"@storybook/addon-svelte-csf\";\n import SuccessLabel from \"../src/components/labels/SuccessLabel.svelte\";\n\n This message should be shown\n\n```\n\n========================================\n\nCode:\n```text\n<button>\n <slot />\n</button>\n```\n\n```text\n<script>\n import Button from './Button.svelte';\n</script>\n\n<Button>Hello World</Button>\n```\n\n```html\n<div class=\"flex-col\">\n <slot><!-- optional fallback --></slot>\n </div>\n```\n\n```html\n<script lang=\"ts\">\n import Stack from './Stack.svelte'\n\n</script>\n\n<Stack>\n <p>Slot 1</p>\n <p>Slot 2</p>\n <p>Slot 3</p>\n</Stack>\n```\n\n```js\nimport Stack from './StackView.svelte';\n\nexport default {\n title: 'Stack',\n component: Stack,\n};\n\n\nconst Template = ({ ...args }) => ({\n Component: Stack,\n props: args,\n\n});\n\nexport const Regular = Template.bind({});\n```\n\n```text\n<!--SuccessLabel.svelte-->\n<div>\n <slot />\n</div>\n\n<style>\n div {\n position: relative;\n color: white;\n background-color: #28a745;\n border-color: #28a745;\n margin-top: -3px;\n padding: 10px;\n border-radius: 5px;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n font-size: 12px;\n }\n</style>\n\n\n<!--SuccessLabel.stories.svelte-->\n<script>\n import { Meta, Story } from \"@storybook/addon-svelte-csf\";\n import SuccessLabel from \"../src/components/labels/SuccessLabel.svelte\";\n</script>\n\n<Meta title=\"Labels/SuccessLabel\" component={SuccessLabel} />\n\n<Story name=\"Default\">\n <SuccessLabel>This message should be shown</SuccessLabel>\n</Story>\n```\n\n========================================\n\nComments:\n- Solved using default value inside slot. Like `{default}`.\n- I think the advice to simply use Svelte template syntax was valuable\n- This requires to add to Storybook the add-on `addon-svelte-csf` following the steps here.","metadata":{"transformedAt":"2026-08-18T18:33:40.684Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":150,"estimatedTokens":655}}316{"id":"stack-65127914","source":"stackoverflow","questionId":65127914,"title":"displaying file content in svelte","tags":["file","svelte","read-eval-print-loop"],"text":"Title: displaying file content in svelte\nTags: file, svelte, read-eval-print-loop\nSource: Stack Overflow\n\nQuestion:\nI am using this code to upload a file. And I want to display the content of the file but all I get is [object file] and nothing else. is there a way to display the file content in svelte?\n\nfile text2.txt:\n\n```\n1 2 3 4 5 6\n7 8 9 10 11 1\n```\n\nTest.svelte:\n\n```\n\n import { onMount } from \"svelte\"\n // d3.csv(' http://127.0.0.1:8081/test.csv').then(function(data) {\n // console.log(data[0])})\n \n let files;\n $: if (files) {\n console.log(files);\n for (const file of files) {\n console.log(`${file.name}: ${file.size} bytes`);\n }\n }\n \n \n \n ...from test\n\n \n \n \n {#if files}\n \n\n### Selected files:\n\n {#each Array.from(files) as file,i}\n {file.name} ({file.size} bytes)\n\n e: {file} i: {i}\n\n {/each}\n files length: {files.length}\n\n {/if}\n```\n\nTo reproduce this, just paste it into a svelte REPL.\n\n========================================\n\nCode:\n```text\n1 2 3 4 5 6\n7 8 9 10 11 1\n```\n\n```text\n<script>\n import { onMount } from \"svelte\"\n // d3.csv(' http://127.0.0.1:8081/test.csv').then(function(data) {\n // console.log(data[0])})\n \n let files;\n $: if (files) {\n console.log(files);\n for (const file of files) {\n console.log(`${file.name}: ${file.size} bytes`);\n }\n }\n \n </script>\n \n <p>...from test</p>\n \n <input type='file' bind:files>\n \n {#if files}\n <h2>Selected files:</h2>\n {#each Array.from(files) as file,i}\n <p>{file.name} ({file.size} bytes)</p>\n <p>e: {file} i: {i}</p>\n {/each}\n <p>files length: {files.length}</p>\n {/if}\n```\n\n```html\n{#each Array.from(files) as file, i}\n <p>{file.name} {file.size} bytes</p>\n {#await file.text() then text}\n <p>e: {text} i: {i}</p>\n {/await}\n{/each}\n```\n\n```text\nfile.name\n```\n\n```text\nfile.size\n```\n\n```text\n.text()\n```\n\n```text\n#await\n```\n\n========================================\n\nComments:\n- ok, that seems to work. but why is this so hard to find in the docs? this is a simple operation in any other regular language, but here it is almost impossible to find out how.\n- Very useful, as @JonasFredriksson mentioned, this appears to be quite absent from the docs.","metadata":{"transformedAt":"2026-08-18T18:33:40.684Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":123,"estimatedTokens":569}}317{"id":"stack-60911171","source":"stackoverflow","questionId":60911171,"title":"How to pass data from a layout to a page in Sapper?","tags":["svelte","sapper"],"text":"Title: How to pass data from a layout to a page in Sapper?\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nIn Svelte you can pass props to the content in a slot.\n\n```\n\n \n {message}\n \n\n```\n\nWhen Sapper uses a layout to render a route, the route contents are rendered in a slot too. The problem is that since Sapper takes control of this process it doesn't seem possible to pass a slot prop to a route.\n\nThis doesn't work:\n\n```\n// _layout.svelte\n\n```\n\nSo what is the appropriate way of passing data from a layout to a rendered route? For example `segment`.\n\n========================================\n\nCode:\n```text\n<Component let:message=\"Hello!\">\n <div>\n {message}\n </div>\n</Component>\n```\n\n```text\n// _layout.svelte\n<slot message=\"Hello!\"></slot>\n```\n\n```text\nsegment\n```\n\n```html\n<script>\n import { setContext } from 'svelte'\n import { writable } from 'svelte/store'\n\n export let segment;\n\n const segment$ = writable(segment)\n\n // this updates the store's value when `segment` changes\n // syntactic sugar for: segment$.set(segment)\n $: $segment$ = segment\n\n setContext('segment', segment$)\n</script>\n\n<slot />\n```\n\n```html\n<script>\n import { getContext } from 'svelte'\n\n const segment$ = getContext('segment')\n\n $: segment = $segment$\n\n $: console.log(segment)\n</script>\n```\n\n```text\n_layout.svelte\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.684Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":80,"estimatedTokens":334}}318{"id":"stack-71304201","source":"stackoverflow","questionId":71304201,"title":"How to use web components in Svelte?","tags":["javascript","web-component","svelte"],"text":"Title: How to use web components in Svelte?\nTags: javascript, web-component, svelte\nSource: Stack Overflow\n\nQuestion:\nI want to use few web components from https://github.com/microsoft/vscode-webview-ui-toolkit. But I don't know to how to use them in Svelte as svelte treats the web components as svelte components.\n\nWhen I try to use them as,\n\n```\n\nimport { Button } from \"@vscode/webview-ui-toolkit\"\n\n Text\n\n```\n\nI get this error,\n\n```\nElement does not support attributes because type definitions are missing for this Svelte Component or element cannot be used as such.\n\nUnderlying error:\nJSX element class does not support attributes because it does not have a '$$prop_def' property.ts(2607)\n'Button' cannot be used as a JSX component.\n Its instance type 'Button' is not a valid JSX element.\n Property '$$prop_def' is missing in type 'Button' but required in type 'ElementClass'.\n\nPossible causes:\n- You use the instance type of a component where you should use the constructor type\n- Type definitions are missing for this Svelte Component. If you are using Svelte 3.31+, use SvelteComponentTyped to add a definition:\n import type { SvelteComponentTyped } from \"svelte\";\n class ComponentName extends SvelteComponentTyped {}ts(2786)\n```\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\nimport { Button } from \"@vscode/webview-ui-toolkit\"\n</script>\n\n<main>\n <Button appearance=\"primary\">Text</Button>\n</main>\n```\n\n```text\nElement does not support attributes because type definitions are missing for this Svelte Component or element cannot be used as such.\n\nUnderlying error:\nJSX element class does not support attributes because it does not have a '$$prop_def' property.ts(2607)\n'Button' cannot be used as a JSX component.\n Its instance type 'Button' is not a valid JSX element.\n Property '$$prop_def' is missing in type 'Button' but required in type 'ElementClass'.\n\nPossible causes:\n- You use the instance type of a component where you should use the constructor type\n- Type definitions are missing for this Svelte Component. If you are using Svelte 3.31+, use SvelteComponentTyped to add a definition:\n import type { SvelteComponentTyped } from \"svelte\";\n class ComponentName extends SvelteComponentTyped<{propertyName: string;}> {}ts(2786)\n```\n\n```svelte\n<main>\n <vscode-button appearance=\"primary\">Text</vscode-button>\n</main>\n```\n\n```text\nButton\n```\n\n```text\n<vscode-button>\n```\n\n========================================\n\nComments:\n- Have you tried to write a test for you custom button on the svelte component?\n- The rest of the step is documented here: github.com/sveltejs/svelte/issues/7334","metadata":{"transformedAt":"2026-08-18T18:33:40.684Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":83,"estimatedTokens":659}}319{"id":"stack-76577665","source":"stackoverflow","questionId":76577665,"title":"vitest and svelte component's onMount","tags":["javascript","svelte","sveltekit","svelte-component","vitest"],"text":"Title: vitest and svelte component's onMount\nTags: javascript, svelte, sveltekit, svelte-component, vitest\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use Svelte to create a simple reactive component. The component loads data from an api server `onMount` and updates a reactive value (which updates a html element).\n\nI have a simple vitest that renders the component and verifies the value of the html element. However while running under vitest the `onMount` is never called and hence the api call is never made. What am I missing ?\n\n`Component.svelte`:\n\n```\n\n import { onMount } from 'svelte';\n\n export let name = 'world';\n\n onMount(async () => {\n console.log('chat onMount event!');\n const response = await fetch('http://localhost:8081/api');\n // for this example, assume name returned by api is FOO\n name = data.name;\n });\n\n **Hello {name}**\n\n```\n\n`index.test.js`:\n\n```\nimport { expect, test } from 'vitest';\nimport '@testing-library/jest-dom';\nimport { render, screen } from '@testing-library/svelte';\nimport Component from '../src/lib/Component.svelte';\n\ntest('should render', () => {\n render(Component);\n\n const heading = screen.getByText('Hello FOO');\n expect(heading).toBeInTheDocument();\n});\n```\n\n========================================\n\nCode:\n```text\n<script>\n import { onMount } from 'svelte';\n\n export let name = 'world';\n\n onMount(async () => {\n console.log('chat onMount event!');\n const response = await fetch('http://localhost:8081/api');\n // for this example, assume name returned by api is FOO\n name = data.name;\n });\n\n</script>\n\n<div id=\"#element\">\n <b> Hello {name}</b>\n</div>\n```\n\n```text\nimport { expect, test } from 'vitest';\nimport '@testing-library/jest-dom';\nimport { render, screen } from '@testing-library/svelte';\nimport Component from '../src/lib/Component.svelte';\n\ntest('should render', () => {\n render(Component);\n\n const heading = screen.getByText('Hello FOO');\n expect(heading).toBeInTheDocument();\n});\n```\n\n```text\nonMount\n```\n\n```text\nonMount\n```\n\n```text\nComponent.svelte\n```\n\n```text\nindex.test.js\n```\n\n```text\n{\n test: {\n alias: [{ find: /^svelte$/, replacement: 'svelte/internal' }],\n ....\n },\n ....\n}\n```\n\n```text\nonMount\n```\n\n```text\nvite.config.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.684Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":114,"estimatedTokens":571}}320{"id":"stack-58320894","source":"stackoverflow","questionId":58320894,"title":"How to do window.scrollTo(0,0) in Svelte","tags":["javascript","svelte"],"text":"Title: How to do window.scrollTo(0,0) in Svelte\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI am using svelte and svelte-routing to create a website and try to scroll to the top of the page whenever a User navigates around. In other Frameworks like React window.scrollTo(0, 0) works perfectly fine. In Svelte, the following code does nothing unfortunately:\n\n```\nimport { onMount } from \"svelte\";\n\nonMount(() => window.scrollTo(0,0));\n```\n\nSo what is the trick to make this work?\n\n========================================\n\nTop Answer:\nYou can also bind to window properties like scrollX and scrollY using svelte window bind (API doc):\n\n```\n\n```\n\nNow you can read en set the y property.\nSee this Svelte docs REPL.\n\n========================================\n\nCode:\n```text\nimport { onMount } from \"svelte\";\n\nonMount(() => window.scrollTo(0,0));\n```\n\n```text\n<svelte:window bind:scrollY={y}/>\n```\n\n```text\nnpm i svelte-scrollto\n```\n\n```text\n<script>\n import * as animateScroll from \"svelte-scrollto\";\n</script> \n\n<a on:click={() => animateScroll.scrollToBottom()}> Scroll to bottom </a>\n<a on:click={() => animateScroll.scrollToTop()}> Scroll to top </a>\n```\n\n========================================\n\nComments:\n- Please see this REPL, everything is working as expected, no?\n- Yes, it works fine. So I must have some kind of bug in my code. I can't really think of anything.\n- No, I already tried that and the y is always undefined. Maybe there is a problem with the routing packet I use (svelte-routing).","metadata":{"transformedAt":"2026-08-18T18:33:40.684Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":59,"estimatedTokens":379}}321{"id":"stack-74680419","source":"stackoverflow","questionId":74680419,"title":"Dockerized Sveltkit app: Hot reload not working","tags":["docker","docker-compose","svelte","vite","sveltekit"],"text":"Title: Dockerized Sveltkit app: Hot reload not working\nTags: docker, docker-compose, svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nWith the help from SO community I was finally able to dockerize my Sveltekit app and access it from the browser (this was an issue initially). So far so good, but now every time I perform a code change I need to re-build and redeploy my container which obviously is not acceptable. Hot reload is not working, I've been trying multiple things I've found online but none of them have worked so far.\n\nHere's my `Dockerfile`:\n\n```\nFROM node:19-alpine\n\n# Set the Node environment to development to ensure all packages are installed\nENV NODE_ENV development\n\n# Change our current working directory\nWORKDIR /app\n\n# Copy over `package.json` and lock files to optimize the build process\nCOPY package.json package-lock.json ./\n# Install Node modules\nRUN npm install\n\n# Copy over rest of the project files\nCOPY . .\n\n# Perhaps we need to build it for production, but apparently is not needed to run dev script.\n# RUN npm run build\n\n# Expose port 3000 for the SvelteKit app and 24678 for Vite's HMR\nEXPOSE 3333\nEXPOSE 8080\nEXPOSE 24678\n\nCMD [\"npm\", \"run\", \"dev\"]\n```\n\nMy `docker-compose`:\n\n```\nversion: \"3.9\"\n\nservices:\n dmc-web:\n build:\n context: .\n dockerfile: Dockerfile\n container_name: dmc-web\n restart: always\n ports:\n - \"3000:3000\"\n - \"3010:3010\"\n - \"8080:8080\"\n - \"5050:5050\"\n - \"24678:24678\"\n volumes:\n - ./:/var/www/html\n```\n\nthe scripts from my `package.json`:\n\n```\n\"scripts\": {\n \"dev\": \"vite dev --host 0.0.0.0\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\",\n \"test\": \"playwright test\",\n \"lint\": \"prettier --check . && eslint .\",\n \"format\": \"prettier --write .\"\n },\n```\n\nand my `vite.config.js`:\n\n```\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport {defineConfig} from \"vite\";\n\nexport default defineConfig({\n plugins: [sveltekit()],\n server: {\n watch: {\n usePolling: true,\n },\n host: true, // needed for the DC port mapping to work\n strictPort: true,\n port: 8080,\n }\n});\n```\n\nany idea what am I missing? I can reach my app at `http://localhost:8080` but cannot get to reload the app when a code change happens.\n\nThanks.\n\n========================================\n\nTop Answer:\nI had the same problem while trying to use Svelte 5 and Docker Desktop.\n@sungryeol answer was half the way to my solution. After reading the comments, I enabled the usePooling option and now it is working as desired.\n\nHere are my configuration:\n\nDockerfile:\n\n```\nFROM node:23.3-alpine3.19\n \nWORKDIR /app\n \nCOPY package.json package-lock.json ./\nRUN npm install\n```\n\ncompose.yaml\n\n```\nservices:\n seligai_front_app:\n container_name: seligai_front_app\n build:\n context: .\n ports:\n - 5173:5173\n volumes:\n - /app/node_modules\n - .:/app\n command: npm run dev -- --host 0.0.0.0\n```\n\nvite.config.ts\n\n```\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n plugins: [sveltekit()],\n server: {\n watch: {\n usePolling: true,\n },\n },\n});\n```\n\nHope it helps someone.\n\n========================================\n\nCode:\n```text\nFROM node:19-alpine\n\n# Set the Node environment to development to ensure all packages are installed\nENV NODE_ENV development\n\n# Change our current working directory\nWORKDIR /app\n\n# Copy over `package.json` and lock files to optimize the build process\nCOPY package.json package-lock.json ./\n# Install Node modules\nRUN npm install\n\n# Copy over rest of the project files\nCOPY . .\n\n# Perhaps we need to build it for production, but apparently is not needed to run dev script.\n# RUN npm run build\n\n# Expose port 3000 for the SvelteKit app and 24678 for Vite's HMR\nEXPOSE 3333\nEXPOSE 8080\nEXPOSE 24678\n\nCMD [\"npm\", \"run\", \"dev\"]\n```\n\n```text\nversion: \"3.9\"\n\nservices:\n dmc-web:\n build:\n context: .\n dockerfile: Dockerfile\n container_name: dmc-web\n restart: always\n ports:\n - \"3000:3000\"\n - \"3010:3010\"\n - \"8080:8080\"\n - \"5050:5050\"\n - \"24678:24678\"\n volumes:\n - ./:/var/www/html\n```\n\n```text\n\"scripts\": {\n \"dev\": \"vite dev --host 0.0.0.0\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\",\n \"test\": \"playwright test\",\n \"lint\": \"prettier --check . && eslint .\",\n \"format\": \"prettier --write .\"\n },\n```\n\n```text\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport {defineConfig} from \"vite\";\n\nexport default defineConfig({\n plugins: [sveltekit()],\n server: {\n watch: {\n usePolling: true,\n },\n host: true, // needed for the DC port mapping to work\n strictPort: true,\n port: 8080,\n }\n});\n```\n\n```text\nDockerfile\n```\n\n```text\ndocker-compose\n```\n\n```text\npackage.json\n```\n\n```text\nvite.config.js\n```\n\n```text\nhttp://localhost:8080\n```\n\n```yaml\n# 🚨wrong\n volumes:\n - ./:/var/www/html\n# ✅answer\n volumes:\n # it avoids mounting the workspace root\n # because it may cause OS specific node_modules folder\n # or build folder(.svelte-kit) to be mounted.\n # they conflict with the temporary results from docker space.\n # this is why many mono repos utilize ./src folder\n - ./src:/home/node/app/src\n - ./static:/home/node/app/static\n - ./vite.config.js:/home/node/app/vite.config.js\n - ./tsconfig.json:/home/node/app/tsconfig.json\n - ./svelte.config.js:/home/node/app/svelte.config.js\n```\n\n```text\n# dockerfile\n\n# 🚨wrong\nCOPY package.json package-lock.json ./\nRUN npm install\nCOPY . .\n# ...\nCMD [\"npm\", \"run\", \"dev\"]\n\n# ✅answer\nCOPY package*.json ./\nRUN npm install\n# comment out COPY and CMD\n# COPY . .\n# ...\n# CMD [\"npm\", \"run\", \"dev\"]\n```\n\n```yaml\n# docker-compose.yaml\nservices:\n svelte:\n # ...\n command: npm dev\n```\n\n```text\n# docker-compose.yaml\nvolumes:\n - ./src:/$YOUR_APP_DIR/src\n - ./static:/$YOUR_APP_DIR/static\n # ...\n```\n\n```text\nRUN mkdir -p /home/node/app\nWORKDIR /home/node/app\n```\n\n```text\ndocker-compose.yaml\n```\n\n```text\ndockerfile\n```\n\n```text\nsleep infinity\n```\n\n```text\nCOPY\n```\n\n```text\nCMD\n```\n\n```text\ndocker-compose.yaml\n```\n\n```text\nCMD\n```\n\n```text\n/home/node/app\n```\n\n```text\n/home/node\n```\n\n```text\n/home/node/app\n```\n\n```text\ndocker run -p 8080:8080 -v $(pwd):/src node:19-alpine bash\n```\n\n```text\ncd /src\nnpm install\nnpm run dev\n```\n\n```text\nFROM node:23.3-alpine3.19\n \nWORKDIR /app\n \nCOPY package.json package-lock.json ./\nRUN npm install\n```\n\n```yaml\nservices:\n seligai_front_app:\n container_name: seligai_front_app\n build:\n context: .\n ports:\n - 5173:5173\n volumes:\n - /app/node_modules\n - .:/app\n command: npm run dev -- --host 0.0.0.0\n```\n\n```js\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n plugins: [sveltekit()],\n server: {\n watch: {\n usePolling: true,\n },\n },\n});\n```\n\n========================================\n\nComments:\n- Did you try the hot reload locally without docker?\n- Before dockerizing the app the hot reload was working\n- Docker is used to encapsulate a application's environment requirements for portability. If your host computer is windows and your teammate is linux, you want to use docker.\n- I just did this, but when running it I'm getting `Error: Cannot find module '/app/npm dev'`.\n- @MrCujo did you try run my github demo as it is? it sure does work. the answer is proving points by using my own settings. change the volume accordingly\n- thanks a lot @sungryeol!!! It finally worked! only thing was that I had to remove `command: npm dev` from `docker-compose` and leave instead the `CMD` command in my `Dockerfile`, otherwise I'd get an error saying: `node:internal/modules/cjs/loader:1029 throw err; Error: Cannot find module '/app/npm run dev'` Other than that all your suggestions made it work. I appreciate your help. Wanted to grant you the points but the bounty had expired, I even tried to reinstate it again but couldn't do it.\n- Never mind, was able to open the bounty again, although my previous bounty was for 50 and it didn't let me choose 50 again, had to do it for 100, but what the heck, you deserve it for your help. I have to wait 23 hours before being able to grant it though.\n- Unfortunately it seems like using \"Rancher Desktop\" as a \"Docker Desktop\" alternative also causes file updates not to trigger a reload. I've cloned your git repo and it does not work :( I need to use 'usePolling' setting in vite.config.json.\n- @Leon using Rancher is out of scope of this discussion. You should pose a new question.\n- @MrCujo I think it's 'run': `npm run dev`\n- @Leon did you get anywhere with Rancher Desktop? (same problem)\n- Pasting the link to solution with Rancher Desktop in case anyone hits this thread: stackoverflow.com/q/78443707/5695347\n- I'm guessing you're using Windows Home? And you store your project on the hard drive for Windows? Then, even if you mount, file events in Windows (such as when a file is saved) will not be propagated to the Linux container, and you can fall back to polling, as you suggested. But a better solution is to store the project on the hard drive for the Linux instance instead. Then File events will be propagated as expected.","metadata":{"transformedAt":"2026-08-18T18:33:40.684Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":408,"estimatedTokens":2310}}322{"id":"stack-64931403","source":"stackoverflow","questionId":64931403,"title":"running svelte dev on https","tags":["svelte","rollupjs"],"text":"Title: running svelte dev on https\nTags: svelte, rollupjs\nSource: Stack Overflow\n\nQuestion:\nI'm experimenting with svelte using it's template (https://github.com/sveltejs/template/) as starting point.\n\nAnd I wanted to scan qr codes with https://github.com/nimiq/qr-scanner, but on my pc I don't have a webcam and my phone doesn't want to start the qrScanner because the page isn't served from https.\n\nwhen I run `npm run dev` I get:\n\n```\nYour application is ready~! 🚀\n\n - Local: http://0.0.0.0:5000\n - Network: http://192.168.1.13:5000\n\n────────────────── LOGS ──────────────────\n```\n\nmy rollup.config.js:\n\n```\nimport svelte from \"rollup-plugin-svelte\";\nimport resolve from \"@rollup/plugin-node-resolve\";\nimport commonjs from \"@rollup/plugin-commonjs\";\nimport livereload from \"rollup-plugin-livereload\";\nimport { terser } from \"rollup-plugin-terser\";\nimport { string } from \"rollup-plugin-string\";\n\nconst production = !process.env.ROLLUP_WATCH;\n\nfunction serve() {\n let server;\n\n function toExit() {\n if (server) server.kill(0);\n }\n\n return {\n writeBundle() {\n if (server) return;\n server = require(\"child_process\").spawn(\n \"npm\",\n [\"run\", \"start\", \"--\", \"--dev\"],\n {\n stdio: [\"ignore\", \"inherit\", \"inherit\"],\n shell: true,\n }\n );\n\n process.on(\"SIGTERM\", toExit);\n process.on(\"exit\", toExit);\n },\n };\n}\n\nexport default {\n input: \"src/main.js\",\n output: {\n sourcemap: true,\n format: \"iife\",\n name: \"app\",\n file: \"public/build/bundle.js\",\n },\n plugins: [\n svelte({\n // enable run-time checks when not in production\n dev: !production,\n // we'll extract any component CSS out into\n // a separate file - better for performance\n css: (css) => {\n css.write(\"public/build/bundle.css\");\n },\n }),\n string({\n include: \"node_modules/qr-scanner/qr-scanner-worker.min.js\",\n }),\n\n // If you have external dependencies installed from\n // npm, you'll most likely need these plugins. In\n // some cases you'll need additional configuration -\n // consult the documentation for details:\n // https://github.com/rollup/plugins/tree/master/packages/commonjs\n resolve({\n browser: true,\n dedupe: [\"svelte\"],\n }),\n commonjs(),\n\n // In dev mode, call `npm run start` once\n // the bundle has been generated\n !production && serve(),\n\n // Watch the `public` directory and refresh the\n // browser on changes when not in production\n !production && livereload(\"public\"),\n\n // If we're building for production (npm run build\n // instead of npm run dev), minify\n production && terser(),\n ],\n watch: {\n clearScreen: false,\n },\n};\n```\n\nand package json:\n\n```\n{\n \"name\": \"myapp\",\n \"version\": \"0.0.1\",\n \"scripts\": {\n \"build\": \"rollup -c\",\n \"dev\": \"rollup -c -w\",\n \"start\": \"HTTPS=true sirv public --single --host\"\n },\n \"devDependencies\": {\n \"@rollup/plugin-commonjs\": \"^14.0.0\",\n \"@rollup/plugin-node-resolve\": \"^8.0.0\",\n \"rollup\": \"^2.33.2\",\n \"rollup-plugin-livereload\": \"^1.0.0\",\n \"rollup-plugin-string\": \"^3.0.0\",\n \"rollup-plugin-svelte\": \"^6.1.1\",\n \"rollup-plugin-terser\": \"^6.1.0\",\n \"svelte\": \"^3.29.7\"\n },\n \"dependencies\": {\n \"graphql\": \"^15.4.0\",\n \"graphql-request\": \"^3.3.0\",\n \"jshashes\": \"^1.0.8\",\n \"page.js\": \"^4.13.3\",\n \"qr-scanner\": \"^1.2.0\",\n \"sirv-cli\": \"^1.0.8\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nI have encountered this issue before, the solution was to get chrome/firefox to allow camera access through HTTP\n\ntry this answer\n\nalternatively there are tutorial on the web on how to add a certificate for localhost to served on HTTPS\n\n========================================\n\nCode:\n```text\nYour application is ready~! 🚀\n\n - Local: http://0.0.0.0:5000\n - Network: http://192.168.1.13:5000\n\n────────────────── LOGS ──────────────────\n```\n\n```js\nimport svelte from \"rollup-plugin-svelte\";\nimport resolve from \"@rollup/plugin-node-resolve\";\nimport commonjs from \"@rollup/plugin-commonjs\";\nimport livereload from \"rollup-plugin-livereload\";\nimport { terser } from \"rollup-plugin-terser\";\nimport { string } from \"rollup-plugin-string\";\n\nconst production = !process.env.ROLLUP_WATCH;\n\nfunction serve() {\n let server;\n\n function toExit() {\n if (server) server.kill(0);\n }\n\n return {\n writeBundle() {\n if (server) return;\n server = require(\"child_process\").spawn(\n \"npm\",\n [\"run\", \"start\", \"--\", \"--dev\"],\n {\n stdio: [\"ignore\", \"inherit\", \"inherit\"],\n shell: true,\n }\n );\n\n process.on(\"SIGTERM\", toExit);\n process.on(\"exit\", toExit);\n },\n };\n}\n\nexport default {\n input: \"src/main.js\",\n output: {\n sourcemap: true,\n format: \"iife\",\n name: \"app\",\n file: \"public/build/bundle.js\",\n },\n plugins: [\n svelte({\n // enable run-time checks when not in production\n dev: !production,\n // we'll extract any component CSS out into\n // a separate file - better for performance\n css: (css) => {\n css.write(\"public/build/bundle.css\");\n },\n }),\n string({\n include: \"node_modules/qr-scanner/qr-scanner-worker.min.js\",\n }),\n\n // If you have external dependencies installed from\n // npm, you'll most likely need these plugins. In\n // some cases you'll need additional configuration -\n // consult the documentation for details:\n // https://github.com/rollup/plugins/tree/master/packages/commonjs\n resolve({\n browser: true,\n dedupe: [\"svelte\"],\n }),\n commonjs(),\n\n // In dev mode, call `npm run start` once\n // the bundle has been generated\n !production && serve(),\n\n // Watch the `public` directory and refresh the\n // browser on changes when not in production\n !production && livereload(\"public\"),\n\n // If we're building for production (npm run build\n // instead of npm run dev), minify\n production && terser(),\n ],\n watch: {\n clearScreen: false,\n },\n};\n```\n\n```json\n{\n \"name\": \"myapp\",\n \"version\": \"0.0.1\",\n \"scripts\": {\n \"build\": \"rollup -c\",\n \"dev\": \"rollup -c -w\",\n \"start\": \"HTTPS=true sirv public --single --host\"\n },\n \"devDependencies\": {\n \"@rollup/plugin-commonjs\": \"^14.0.0\",\n \"@rollup/plugin-node-resolve\": \"^8.0.0\",\n \"rollup\": \"^2.33.2\",\n \"rollup-plugin-livereload\": \"^1.0.0\",\n \"rollup-plugin-string\": \"^3.0.0\",\n \"rollup-plugin-svelte\": \"^6.1.1\",\n \"rollup-plugin-terser\": \"^6.1.0\",\n \"svelte\": \"^3.29.7\"\n },\n \"dependencies\": {\n \"graphql\": \"^15.4.0\",\n \"graphql-request\": \"^3.3.0\",\n \"jshashes\": \"^1.0.8\",\n \"page.js\": \"^4.13.3\",\n \"qr-scanner\": \"^1.2.0\",\n \"sirv-cli\": \"^1.0.8\"\n }\n}\n```\n\n```text\nnpm run dev\n```\n\n```text\n--http2 --cert cert.pem --key key.pem\n```\n\n```text\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vitest/config';\nimport fs from 'fs';\n\nlet certKey: string|Buffer|undefined;\nlet certCert: string|Buffer|undefined;\n\nif (fs.existsSync('./.cert/key.pem')) {\n certKey = fs.readFileSync('./.cert/key.pem');\n certCert = fs.readFileSync('./.cert/cert.pem');\n} else {\n console.log('Missing HTTPS key/cert. You may need to run: npm run cert');\n}\n\nexport default defineConfig({\n plugins: [sveltekit()],\n server: {\n https: {\n // See https://stackoverflow.com/questions/69417788/vite-https-on-localhost\n key: certKey,\n cert: certCert,\n },\n },\n test: {\n include: ['src/**/*.{test,spec}.{js,ts}'],\n },\n});\n```\n\n```text\nvite.config.ts\n```\n\n========================================\n\nComments:\n- This is fine, but qr-scanner has actually code for https checking. So it doesn't work.","metadata":{"transformedAt":"2026-08-18T18:33:40.684Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":323,"estimatedTokens":1959}}323{"id":"stack-76640121","source":"stackoverflow","questionId":76640121,"title":"Why is my svelte crossfade moving my elements instead of crossfading in place?","tags":["svelte","svelte-transition"],"text":"Title: Why is my svelte crossfade moving my elements instead of crossfading in place?\nTags: svelte, svelte-transition\nSource: Stack Overflow\n\nQuestion:\nI'm trying to fade one element out and another in based on a boolean value. Instead of having a crossfade where the two elements look like they're in the same place, they shift vertically. I'd like to get them to stay where they would sit naturally!\n\nStackblitz\n\n```\n\n import { crossfade } from \"svelte/transition\";\n\n const [send, receive] = crossfade({\n duration: 1500,\n });\n\n let foo = true;\n\n function handleClick() {\n foo=!foo;\n }\n\n### My example\n\nClick me {foo}\n\n {#if foo}\n \n one\n \n {:else}\n \n two\n \n {/if}\n\n```\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n import { crossfade } from \"svelte/transition\";\n\n const [send, receive] = crossfade({\n duration: 1500,\n });\n\n let foo = true;\n\n function handleClick() {\n foo=!foo;\n }\n</script>\n\n<h1>My example</h1>\n<button on:click={handleClick}>Click me {foo}</button>\n<div>\n {#if foo}\n <div in:send={{ key: \"a\" }} out:receive={{ key: \"a\" }}>\n one\n </div>\n {:else}\n <div in:send={{ key: \"a\" }} out:receive={{ key: \"a\" }}>\n two\n </div>\n {/if}\n</div>\n```\n\n```html\n<script lang=\"ts\">\n import { fade } from \"svelte/transition\";\n let show = $state(true);\n</script>\n\n<button onclick={() => show = !show}>\n Fade [{show}]\n</button>\n\n<div class=\"container\">\n {#if show}\n <div transition:fade={{ duration: 1500 }}>one</div>\n {:else}\n <div transition:fade={{ duration: 1500 }}>two</div>\n {/if}\n</div>\n\n<style>\n .container { display: grid; }\n .container > * { grid-area: 1 / 1; }\n</style>\n```\n\n```text\ncrossfade\n```\n\n```text\nfade\n```\n\n```text\nposition: absolute\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.684Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":107,"estimatedTokens":435}}324{"id":"stack-70618289","source":"stackoverflow","questionId":70618289,"title":"Can't go into object defined by rollup plugin-replace","tags":["javascript","svelte","rollupjs","svelte-3"],"text":"Title: Can't go into object defined by rollup plugin-replace\nTags: javascript, svelte, rollupjs, svelte-3\nSource: Stack Overflow\n\nQuestion:\nIn a Svelte component, I'm trying to access an object I set up in my rollup config file.\nMy `rollup.config.js` file looks like this:\n\n```\nimport replace from '@rollup/plugin-replace';\n\n...\nexport default {\n...\n replace({\n foo: JSON.stringify({ bar: 'Hello' }),\n }),\n\n...\n```\n\nIn my Svelte component, a simple `console.log(foo)` works:\n\nhttps://i.sstatic.net/2NnvJ.png\n\nBut when I try to go into that foo object like `console.log(foo.bar)`, I get *foo is not defined*:\n\nhttps://i.sstatic.net/vN2Xr.png\n\n========================================\n\nTop Answer:\nThis section of the document explains your exact problem.\n\nhttps://github.com/rollup/plugins/tree/master/packages/replace#delimiters\n\nThe `delimiters` option controls how the strings will be matched. With the default `delimiters` being `['\\b', '\\b(?!\\.)']`, it would only replace `foo` if it follows a word boundary and is followed by a word boundary that is not a dot. Hence with your `rollup.config.js` the behaviour would be\n\n```\nconsole.log(foo)\n// becomes\nconsole.log({\"bar\":\"Hello\"})\n\nconsole.log(foo.bar)\n// is not replaced by the plugin as `foo` IS followed by a dot\n\nconsole.log(foo['bar'])\nconsole.log(foo .bar) // space after `foo`\n// both satisfy the delimiter check again and print: Hello\n// (horrible coding style in the latter but to illustrate how it works)\n\nconst { bar } = foo\n// also satisfy the delimiter check hence\nconsole.log(bar) // prints: Hello\n```\n\nAs you see, the replace plugin doesn't really parse your code but instead only preforms simple text replacement not too different from the search-and-replace feature of your IDE/editor. Gauss what would it say below?\n\n```\nconsole.log('foo')\n// Guess what?\n// ...\n// ...\n// printed: {\"bar\":\"Hello\"}\n// as if it were\nconsole.log('{\"bar\":\"Hello\"}')\n```\n\nTo conclude, your workaround might be\n\n- `foo['bar']`,\n\n- `const { bar } = foo`,\n\n- avoid object replacement and use keys like `__FOO_BAR__`, `__FOO_BAZ__`, ...\n\n- pass `delimiters: ['\\\\b', '\\\\b']` to allow dots following the key.\n\n(However at the moment of writing, the last one doesn't seem to work yet due to a bugfix waiting to be merged).\n\nhttps://github.com/rollup/plugins/pull/1088\n\nIf you use `delimiters: ['', '']` the earlier caveat requires much higher level of caution. Even a string literal `'food'` or a HTML template tag `` might be changed to gibberish like `'{\"bar\":\"Hello\"}d'` or ``. So name your keys wisely or use some unusual delimiters depending on your usage, like what the old version of the plugin once demonstrated: `delimiters: ['']`.\n\nhttps://github.com/rollup/rollup-plugin-replace\n\nNevertheless since these kind of preprocessing is pretty rudimentary, care is always needed when adding replaced keys and when using them.\n\n========================================\n\nCode:\n```js\nimport replace from '@rollup/plugin-replace';\n\n...\nexport default {\n...\n replace({\n foo: JSON.stringify({ bar: 'Hello' }),\n }),\n\n...\n```\n\n```text\nrollup.config.js\n```\n\n```text\nconsole.log(foo)\n```\n\n```text\nconsole.log(foo.bar)\n```\n\n```js\nconst { bar } = foo;\n\nconsole.log(bar);\n```\n\n```js\nimport { config } from \"dotenv\";\n\n...\nreplace({\n values: {\n foo: JSON.stringify({ bar: \"Hello\", ...config().parsed }),\n },\n }),\n...\n```\n\n```js\nconst { bar, ...rest } = foo;\n console.log(\"bar=>\", bar);\n console.log(\"env=>\", rest);\n```\n\n```text\nfoo\n```\n\n```text\njs\n```\n\n```text\n.svelte\n```\n\n```js\nconsole.log(foo)\n// becomes\nconsole.log({\"bar\":\"Hello\"})\n\nconsole.log(foo.bar)\n// is not replaced by the plugin as `foo` IS followed by a dot\n\nconsole.log(foo['bar'])\nconsole.log(foo .bar) // space after `foo`\n// both satisfy the delimiter check again and print: Hello\n// (horrible coding style in the latter but to illustrate how it works)\n\nconst { bar } = foo\n// also satisfy the delimiter check hence\nconsole.log(bar) // prints: Hello\n```\n\n```js\nconsole.log('foo')\n// Guess what?\n// ...\n// ...\n// printed: {\"bar\":\"Hello\"}\n// as if it were\nconsole.log('{\"bar\":\"Hello\"}')\n```\n\n```text\ndelimiters\n```\n\n```text\ndelimiters\n```\n\n```text\n['\\b', '\\b(?!\\.)']\n```\n\n```text\nfoo\n```\n\n```text\nrollup.config.js\n```\n\n```text\nfoo['bar']\n```\n\n```text\nconst { bar } = foo\n```\n\n```text\n__FOO_BAR__\n```\n\n```text\n__FOO_BAZ__\n```\n\n```text\ndelimiters: ['\\\\b', '\\\\b']\n```\n\n```text\ndelimiters: ['', '']\n```\n\n```text\n'food'\n```\n\n```text\n<footer>\n```\n\n```text\n'{\"bar\":\"Hello\"}d'\n```\n\n```text\n<{\"bar\":\"Hello\"}ter>\n```\n\n```text\ndelimiters: ['<@', '@>']\n```\n\n========================================\n\nComments:\n- It works indeed. Interesting... Although I don't understand why destructing the `foo` object solves the issue.\n- The replace plugin is looking for `foo` and is unable to do so if it is `foo.bar`.","metadata":{"transformedAt":"2026-08-18T18:33:40.684Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":249,"estimatedTokens":1208}}325{"id":"stack-75823249","source":"stackoverflow","questionId":75823249,"title":"What kind of perfomance benefits Svelte gets for having no virtual DOM?","tags":["javascript","svelte","sveltekit"],"text":"Title: What kind of perfomance benefits Svelte gets for having no virtual DOM?\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a question about svelte, if svelte is not adapting Virtual DOM or Shadow DOM mechanism, how is it generating high performance applications, because svelte is just a compiler, which generates the pure javascript build, is this is the only takeaway of svelte, converting to pure javascript code, will yeild you high performance applications?, then why react or angular using the Mechanism like Virtual DOM or Shadow DOM\n\nI know this is not a coding question, but I wanted the answer, so only posted here, please do not delete or devote this post. I want to understand the internals\n\nThanks\n\n========================================\n\nTop Answer:\n- In react.js, browser will load `react library`, `reactDOM` and then it will load the project code. this makes react project larger in size. From here\n\nThe Svelte implementation of TodoMVC weighs 3.6kb zipped. For\ncomparison, React plus ReactDOM without any app code weighs about 45kb\nzipped. It takes about 10x as long for the browser just to evaluate\nReact as it does for Svelte to be up and running with an interactive\nTodoMVC.\n\n- svelte apps have less code. From here:\n\nAll code is buggy. It stands to reason, therefore, that the more code\nyou have to write the buggier your apps will be.\n\nWriting more code also takes more time, leaving less time for other\nthings like optimisation, nice-to-have features, or being outdoors\ninstead of hunched over a laptop.\n\n- Svelte is a compiler. It does not run in the browser. The compiled code will directly modify the DOM without the overhead of the `virtual DOM`. You can read Virtual DOM is pure overhead\n\n========================================\n\nCode:\n```text\nreact library\n```\n\n```text\nreactDOM\n```\n\n```text\nvirtual DOM\n```\n\n========================================\n\nComments:\n- softwareengineering.stackexchange.com might be a better place for this sort of question","metadata":{"transformedAt":"2026-08-18T18:33:40.684Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":52,"estimatedTokens":504}}326{"id":"stack-71134052","source":"stackoverflow","questionId":71134052,"title":"How to Make Relative Href Work in SvelteKit?","tags":["href","svelte","sveltekit"],"text":"Title: How to Make Relative Href Work in SvelteKit?\nTags: href, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI want to build a Web app with SvelteKit with one page listing all items (with potential search query parameters), and then one page for each individual item. If I had to build this the old school way with everything generated in the backend, my paths would be `/items/` for the list of all items, and `/items/123` for item `123`, etc. That is, to go to the page of item `123`, a link will with `href=\"123\"` will work no matter if you are currently at the index (`/items/`) or at the page of one particular item (`/items/[id]`).\n\nWith SvelteKit, if I create files `routes/items/index.svelte` and `routes/items/[id].svelte`, then `routes/items/index.svelte` will have path `/items`, **without** a trailing slash, and as a result a link with `href=\"123\"` will lead to `/123`, resulting in a \"not found\" error.\n\nThis same link will work however from the page of an individual item, say, `/items/456`.\n\nThis is radically different from what you would have in the traditional HTML model, where a link from `/items/` (or `/items/index.html`) would work the same as a link from `/items/[id].html`.\n\nNow in `svelte.config.js` there is a `trailingSlash` option you can set to `always` so that `routes/items/index.svelte` corresponds to path `/items/`, but then `routes/items/[id].svelte` has path `/items/[id]/` and we have the same problem again: one `href` value cannot work from both the index and the page of an individual item.\n\nThe only way I see right now is to use absolute path, but it's not very composable. My guess is that there is something I am doing wrong.\n\n========================================\n\nCode:\n```text\n/items/\n```\n\n```text\n/items/123\n```\n\n```text\n123\n```\n\n```text\n123\n```\n\n```text\nhref=\"123\"\n```\n\n```text\n/items/\n```\n\n```text\n/items/[id]\n```\n\n```text\nroutes/items/index.svelte\n```\n\n```text\nroutes/items/[id].svelte\n```\n\n```text\nroutes/items/index.svelte\n```\n\n```text\n/items\n```\n\n```text\nhref=\"123\"\n```\n\n```text\n/123\n```\n\n```text\n/items/456\n```\n\n```text\n/items/\n```\n\n```text\n/items/index.html\n```\n\n```text\n/items/[id].html\n```\n\n```text\nsvelte.config.js\n```\n\n```text\ntrailingSlash\n```\n\n```text\nalways\n```\n\n```text\nroutes/items/index.svelte\n```\n\n```text\n/items/\n```\n\n```text\nroutes/items/[id].svelte\n```\n\n```text\n/items/[id]/\n```\n\n```text\nhref\n```\n\n```text\ntrailingSlash\n```\n\n========================================\n\nComments:\n- Question: would it help to have the base path for the href as a prop with a default value, and then concatenate the ID to it dynamically inside the component to generate the href? You could then pass in an optional prop to change the base path as needed, but have the most common case set by default.\n- @NikP yes, as long as relative paths cannot work (see accepted answer) I'm going to have to go for something like what you describe\n- October 2023 update: github.com/sveltejs/kit/issues/1405 is now closed after the problem was solved by moving the `trailingSlash` option from the Svelte config file to each individual Svelte page: github.com/sveltejs/kit/pull/7719","metadata":{"transformedAt":"2026-08-18T18:33:40.684Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":130,"estimatedTokens":782}}327{"id":"stack-56742348","source":"stackoverflow","questionId":56742348,"title":"publishing a svelte 3 component: semantics for \"main\" and \"svelte\" fields of package.json?","tags":["svelte","svelte-component"],"text":"Title: publishing a svelte 3 component: semantics for \"main\" and \"svelte\" fields of package.json?\nTags: svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI took the Svelte tutorial and rewrote the keypad in the `component bindings` section with a state machine. That worked lovely.\n\nNow I want to extract the `Machine.svelte` file into a `npm` package and I am not sure how to do that. I could not find any documentation about publishing. For what I saw from svelte-virtual-list, I probably have to configure either the `main` or `svelte` field of my `package.json`:\n\n```\n{\n \"name\": \"@sveltejs/svelte-virtual-list\",\n \"version\": \"3.0.0\",\n \"description\": \"A component for Svelte apps\",\n \"main\": \"VirtualList.svelte\",\n \"svelte\": \"VirtualList.svelte\",\n \"scripts\": {\n \"build\": \"rollup -c\",\n \"dev\": \"rollup -cw\",\n \"prepublishOnly\": \"npm test\",\n \"test\": \"node test/runner.js\",\n \"test:browser\": \"npm run build && serve test/public\",\n \"pretest\": \"npm run build\",\n \"lint\": \"eslint src/VirtualList.svelte\"\n },\n \"devDependencies\": {\n \"eslint\": \"^5.12.1\",\n \"eslint-plugin-svelte3\": \"git+https://github.com/sveltejs/eslint-plugin-svelte3.git\",\n \"port-authority\": \"^1.0.5\",\n \"puppeteer\": \"^1.9.0\",\n \"rollup\": \"^1.1.2\",\n \"rollup-plugin-commonjs\": \"^9.2.0\",\n \"rollup-plugin-node-resolve\": \"^4.0.0\",\n \"rollup-plugin-svelte\": \"^5.0.1\",\n \"sirv\": \"^0.2.2\",\n \"svelte\": \"^3.0.0-beta.2\",\n \"tap-diff\": \"^0.1.1\",\n \"tap-dot\": \"^2.0.0\",\n \"tape-modern\": \"^1.1.1\"\n },\n \"repository\": \"https://github.com/sveltejs/svelte-virtual-list\",\n \"author\": \"Rich Harris\",\n \"license\": \"LIL\",\n \"keywords\": [\n \"svelte\"\n ],\n \"files\": [\n \"src\",\n \"index.mjs\",\n \"index.js\"\n ]\n}\n```\n\nIs that a correct assumption? Additionally I am perplexed by the fact that in the `package.json.files` the `VirtualList.svelte` is not present? How would you go about publishing a svelte component??\n\nEDIT: final gist correctly importing the `Machine` Svelte component\n\n========================================\n\nCode:\n```text\n{\n \"name\": \"@sveltejs/svelte-virtual-list\",\n \"version\": \"3.0.0\",\n \"description\": \"A <VirtualList> component for Svelte apps\",\n \"main\": \"VirtualList.svelte\",\n \"svelte\": \"VirtualList.svelte\",\n \"scripts\": {\n \"build\": \"rollup -c\",\n \"dev\": \"rollup -cw\",\n \"prepublishOnly\": \"npm test\",\n \"test\": \"node test/runner.js\",\n \"test:browser\": \"npm run build && serve test/public\",\n \"pretest\": \"npm run build\",\n \"lint\": \"eslint src/VirtualList.svelte\"\n },\n \"devDependencies\": {\n \"eslint\": \"^5.12.1\",\n \"eslint-plugin-svelte3\": \"git+https://github.com/sveltejs/eslint-plugin-svelte3.git\",\n \"port-authority\": \"^1.0.5\",\n \"puppeteer\": \"^1.9.0\",\n \"rollup\": \"^1.1.2\",\n \"rollup-plugin-commonjs\": \"^9.2.0\",\n \"rollup-plugin-node-resolve\": \"^4.0.0\",\n \"rollup-plugin-svelte\": \"^5.0.1\",\n \"sirv\": \"^0.2.2\",\n \"svelte\": \"^3.0.0-beta.2\",\n \"tap-diff\": \"^0.1.1\",\n \"tap-dot\": \"^2.0.0\",\n \"tape-modern\": \"^1.1.1\"\n },\n \"repository\": \"https://github.com/sveltejs/svelte-virtual-list\",\n \"author\": \"Rich Harris\",\n \"license\": \"LIL\",\n \"keywords\": [\n \"svelte\"\n ],\n \"files\": [\n \"src\",\n \"index.mjs\",\n \"index.js\"\n ]\n}\n```\n\n```text\ncomponent bindings\n```\n\n```text\nMachine.svelte\n```\n\n```text\nnpm\n```\n\n```text\nmain\n```\n\n```text\nsvelte\n```\n\n```text\npackage.json\n```\n\n```text\npackage.json.files\n```\n\n```text\nVirtualList.svelte\n```\n\n```text\nMachine\n```\n\n```text\nsvelte\n```\n\n```text\nmain\n```\n\n```text\nmain\n```\n\n```text\nprepublish\n```\n\n```text\npkg.main\n```\n\n```text\nindex.js\n```\n\n```text\npkg.module\n```\n\n```text\nindex.mjs\n```\n\n```text\npkg.files\n```\n\n```text\npkg.main\n```\n\n```text\npkg.main\n```\n\n```text\nVirtualList.svelte\n```\n\n```text\npkg.files\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.684Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":193,"estimatedTokens":913}}328{"id":"stack-71881253","source":"stackoverflow","questionId":71881253,"title":"Why are Vue DOM changes so slow?","tags":["javascript","reactjs","vue.js","vuejs3","svelte"],"text":"Title: Why are Vue DOM changes so slow?\nTags: javascript, reactjs, vue.js, vuejs3, svelte\nSource: Stack Overflow\n\nQuestion:\nI have a list of 2000 input checkboxes. When selecting them all at once there is noticeable delay (and browser freeze) of about 2 seconds. This seems to be the case for Vue and React, but not for Svelte or jQuery or vanilla.\n\nWith 5k+ checkboxes it becomes a very annoying 3-5 seconds blocker...\n\nWhy is the re-rendering taking so long?\n\nHow can I overcome this update delay with Vue.js?\n\n(The solutions of paginate or lazy-load are not really solving the problem; they are avoiding it.)\n\nBelow is the code in Vue followed by the same example in Svelte.\n\n```\n\nimport { ref } from 'vue'\nconst items = ref(Array.from({length: 2000}, (v, k) => k));\nlet selected = ref([]);\nfunction selectAll() {\n selected.value = items.value.map(i => i);\n}\n\n \n Select all\n \n \n Select none\n \n \n \n {{ n }}\n \n\n label {\n display: block;\n }\n\n```\n\nVue SFC link\n\nSvelte:\n\n```\n\n let items = Array.from({length: 2000}, (v, k) => k);\n let selected = [];\n function selectAll() {\n selected = items.map(i => i);\n }\n\n Select all\n\n selected = []}\">\n Select none\n\n{#each items as n, i}\n\n \n {n}\n\n{/each}\n\n label {\n display: block;\n }\n\n```\n\nSvelte REPL link\n\n========================================\n\nCode:\n```text\n<script setup>\nimport { ref } from 'vue'\nconst items = ref(Array.from({length: 2000}, (v, k) => k));\nlet selected = ref([]);\nfunction selectAll() {\n selected.value = items.value.map(i => i);\n}\n</script>\n\n<template>\n <button @click=\"selectAll\">\n Select all\n </button>\n <button @click=\"selected = []\">\n Select none\n </button>\n <label v-for=\"n in items\">\n <input v-model=\"selected\" type=\"checkbox\" :value=\"n\">\n {{ n }}\n </label>\n</template>\n\n<style>\n label {\n display: block;\n }\n</style>\n```\n\n```text\n<script>\n let items = Array.from({length: 2000}, (v, k) => k);\n let selected = [];\n function selectAll() {\n selected = items.map(i => i);\n }\n</script>\n\n<button on:click={selectAll}>\n Select all\n</button>\n<button on:click=\"{() => selected = []}\">\n Select none\n</button>\n{#each items as n, i}\n<label>\n <input type=checkbox bind:group={selected} value={n}>\n {n}\n</label>\n{/each}\n\n<style>\n label {\n display: block;\n }\n</style>\n```\n\n```html\n<label v-for=\"n in items\">\n <input v-model=\"selected\" type=\"checkbox\" :value=\"n\">\n {{ n }}\n</label>\n```\n\n```html\n<label v-for=\"n in items\">\n <input v-model=\"selected[n]\" type=\"checkbox\" :value=\"n\">\n {{ n }}\n</label>\n```\n\n```js\nfunction selectAll() {\n selected = items.map(i => true);\n}\n```\n\n========================================\n\nComments:\n- Memoization could help.\n- `which is a lot`, but is it? It is not a lot for vanilla or Svelte. In fact, vanilla can easily handle 10K\n- `you put a whole array of 2000 values in the v-model`. That is the recommended way for group of checkboxes vuejs.org/guide/essentials/forms.html#checkbox I agree your way is much faster.\n- With handling not problam, but rendering another thing!\n- If you button clicked, then rendered somesing like that\n- {{ 0 }} {{ 1 }} {{ 2 }} ...\n- Why you wont this?\n- Change `selectAll` to `selected.value = items.value.map(i => true);` to get it run. Works well!","metadata":{"transformedAt":"2026-08-18T18:33:40.684Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":168,"estimatedTokens":812}}329{"id":"stack-68859454","source":"stackoverflow","questionId":68859454,"title":"Rollup says \"[name] is not exported by [file]\" while it clearly is","tags":["typescript","svelte","rollupjs"],"text":"Title: Rollup says \"[name] is not exported by [file]\" while it clearly is\nTags: typescript, svelte, rollupjs\nSource: Stack Overflow\n\nQuestion:\nI am building a Svelte/TypeScript application and all of a sudden it won't compile anymore, with the following error:\n\n```\n[!] Error: 'VoidPromiseCallback' is not exported by src/types.ts, imported by src/TopicEditionFormStack/TopicEditionFormStack.svelte\nhttps://rollupjs.org/guide/en/#error-name-is-not-exported-by-module\nsrc/TopicEditionFormStack/TopicEditionFormStack.svelte (2:18)\n1: \n2: import { Topic, VoidPromiseCallback } from '../types.js';\n ^\n```\n\nHowever if you look at file `src/types.ts` you see at the end:\n\n```\nexport type VoidPromiseCallback = {\n resolve: () => void,\n reject: (reason?: any) => void,\n}\n```\n\nVS Code agrees that `types.ts` does export the name, since if I do *“go to definition”* on the occurrence of `VoidPromiseCallback` Rollup complains about, it navigates to the export quoted above.\n\nAny idea what could cause this? I was thinking maybe Rollup did not invalidate a cache regarding the exports of `types.ts`.\n\n========================================\n\nCode:\n```text\n[!] Error: 'VoidPromiseCallback' is not exported by src/types.ts, imported by src/TopicEditionFormStack/TopicEditionFormStack.svelte\nhttps://rollupjs.org/guide/en/#error-name-is-not-exported-by-module\nsrc/TopicEditionFormStack/TopicEditionFormStack.svelte (2:18)\n1: <script lang=\"ts\">\n2: import { Topic, VoidPromiseCallback } from '../types.js';\n ^\n```\n\n```js\nexport type VoidPromiseCallback = {\n resolve: () => void,\n reject: (reason?: any) => void,\n}\n```\n\n```text\nsrc/types.ts\n```\n\n```text\ntypes.ts\n```\n\n```text\nVoidPromiseCallback\n```\n\n```text\ntypes.ts\n```\n\n```text\nimport { Topic } from '../types.js';\nimport type { VoidPromiseCallback } from '../types.js';\n```\n\n========================================\n\nComments:\n- It worked, thank you so much! I didn't think about that because the other “types” I was importing were actually classes, and the rule seems to be a bit different with classes, you only need `import type` if all the classes are only used as types. Not sure how long I would have spent debugging without your answer!","metadata":{"transformedAt":"2026-08-18T18:33:40.685Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":73,"estimatedTokens":552}}330{"id":"stack-60045404","source":"stackoverflow","questionId":60045404,"title":"svelte read nested store","tags":["javascript","svelte"],"text":"Title: svelte read nested store\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nIn Svelte I can read from store using `$` symbol:\n\n```\n\n export let myStore;\n\n {$myStore}\n\n```\n\nHow do I read from store that is a property of an object? E.g. let's say `foo.store` is a store.\n\nI have tried `$foo.store`, `$(foo.store)` and `foo.$store`, neither working!\n\nI am aware I can do `let foo_store = foo.store` and then `$foo_store`, but I'm looking for a simpler way.\n\n**EDIT** looking for solution for assignments to store too.\n\n========================================\n\nCode:\n```text\n<script>\n export let myStore;\n</script>\n<p>\n {$myStore}\n</p>\n```\n\n```text\n$\n```\n\n```text\nfoo.store\n```\n\n```text\n$foo.store\n```\n\n```text\n$(foo.store)\n```\n\n```text\nfoo.$store\n```\n\n```text\nlet foo_store = foo.store\n```\n\n```text\n$foo_store\n```\n\n```js\nconst { x, y, z } = stores;\n```\n\n========================================\n\nComments:\n- Thanks Rich Harris. Btw, what's the difference between a store and a variable using `$:` assignment?\n- `$:` reactivity applies within a component. Stores are objects that many components can interact with. You can use them in combination.","metadata":{"transformedAt":"2026-08-18T18:33:40.685Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":72,"estimatedTokens":291}}331{"id":"stack-69148302","source":"stackoverflow","questionId":69148302,"title":"How to disable unused style warning in svelte","tags":["svelte","sapper"],"text":"Title: How to disable unused style warning in svelte\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI have a CSS rule which I used for global style, the style worked but my terminal keep show me this warning, how can I disable it?\n\n```\nsrc/components/Navbar.svelte changed. rebuilding...\n• server\nsrc/routes/index.svelte\nModule Warning (from ./node_modules/svelte-loader-hot/index.js):\nUnused CSS selector \"*\" (22:2)\n20: \n21: \n22: * {\n ^\n23: font-family: 'Poppins';\n24: }\n• client\nsrc/routes/index.svelte\nModule Warning (from ./node_modules/svelte-loader-hot/index.js):\nUnused CSS selector \"*\" (22:2)\n20: \n21: \n22: * {\n ^\n23: font-family: 'Poppins';\n24: }\n✔ service worker (73ms)\n```\n\n========================================\n\nTop Answer:\nIn rollup.config.js\n\n```\nexport default {\n plugins: [\n svelte({\n onwarn: (warning, handler) => {\n const { code, frame, filename } = warning\n if (code === \"css-unused-selector\" && filename == 'src/routes/index.svelte') {\n return;\n }\n handler(warning)\n },\n\n }),\n ]\n }\n```\n\n========================================\n\nCode:\n```text\nsrc/components/Navbar.svelte changed. rebuilding...\n• server\nsrc/routes/index.svelte\nModule Warning (from ./node_modules/svelte-loader-hot/index.js):\nUnused CSS selector \"*\" (22:2)\n20: \n21: <style global>\n22: * {\n ^\n23: font-family: 'Poppins';\n24: }\n• client\nsrc/routes/index.svelte\nModule Warning (from ./node_modules/svelte-loader-hot/index.js):\nUnused CSS selector \"*\" (22:2)\n20: \n21: <style global>\n22: * {\n ^\n23: font-family: 'Poppins';\n24: }\n✔ service worker (73ms)\n```\n\n```text\n<style global>\n```\n\n```text\n:global(*)\n```\n\n```text\n*\n```\n\n```text\nglobal.css\n```\n\n```text\n*\n```\n\n```text\nbody\n```\n\n```text\na\n```\n\n```text\n/src/public/global.css\n```\n\n```js\nexport default {\n plugins: [\n svelte({\n onwarn: (warning, handler) => {\n const { code, frame, filename } = warning\n if (code === \"css-unused-selector\" && filename == 'src/routes/index.svelte') {\n return;\n }\n handler(warning)\n },\n\n }),\n ]\n }\n```\n\n========================================\n\nComments:\n- sorry man, honestly I don't remember why i wrote\n- @RobyCigar ahah in this case I guess it's just not svelte valid :)\n- @johannchopin it is not part of Svelte but it is part of Svelte Preprocess github.com/sveltejs/svelte-preprocess#global-style","metadata":{"transformedAt":"2026-08-18T18:33:40.685Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":137,"estimatedTokens":608}}332{"id":"stack-58359531","source":"stackoverflow","questionId":58359531,"title":"Svelte - using select inputs with an on:change event","tags":["drop-down-menu","svelte"],"text":"Title: Svelte - using select inputs with an on:change event\nTags: drop-down-menu, svelte\nSource: Stack Overflow\n\nQuestion:\nStill very new to svelte (but learning more each day!) and need a bit of help.\n\nI am working on a veterinary drug dose calculator that calculates the individual dose of each drug based on the concentration of each drug, the mg/kg dosage of that drug and the weight in kilograms of the patient. I have a weight converter for lbs kgs and my calculations will work if I have just one concentration. The issue is that many drugs have multiple concentrations so I need a select input to allow the user to change the concentration for each drug. \n\nHere is a REPL\n\nHere is my Code:\n\n```\n\n \n \n \n Pounds\n \n setBothFromL(e.target.value)}\" min=\"0\" type=number placeholder=\" lbs\">\n \n \n \n \n \n \n \n Kilogram\n \n setBothFromK(e.target.value)}\" min=\"0\" type=number placeholder=\"kgs\">\n \n \n \n \n\n### Antibiotics\n\n{#each antibiotics as antibiotic, i}\n\n \n {antibiotic.name}\n {#if antibiotic.concSelect.length === 1}\n {antibiotic.concentration} {antibiotic.perml}\n {:else if antibiotic.concSelect.length > 1}\n\n concs = selected}\">\n\n {#each antibiotic.concSelect as concSelect}\n \n {concSelect.name}\n \n {/each}\n\n \n {/if}\n\n \n\n \n\n \n Dose: \n\n {#if antibiotic.dosevalue > antibiotic.dosemax * 1.1 }\n ** Above Range\n {/if}\n\n \n {(k * antibiotic.dosevalue).toFixed(antibiotic.decimal)} {antibiotic.appendose}\n {#if antibiotic.concSelect.length === 1}\n{((k * antibiotic.dosevalue) / antibiotic.concentration).toFixed(antibiotic.decimal)} {antibiotic.appendvol}\n {:else if antibiotic.concSelect.length > 1}\n{((k * antibiotic.dosevalue) / concs).toFixed(antibiotic.decimal)} {antibiotic.appendvol}\n{/if} \n\n{/each}\n\ninput{min-width:120px}\n.vol {\nbackground: rgba(0, 0, 0, .12); padding:5px;}\n.error-message1 {\nfont-size: 10px !important;\nline-height: 11px !important;\nfont-weight: normal;\ncolor: red;\nopacity: 0.5;\nfont-weight: 700;\n}\n.eachdrug {border-top: 1px solid #ccc; margin-top:15px}\n\nimport { fade, fly } from 'svelte/transition';\nlet k = '';\nlet l = '' ;\nlet selected;\nlet concs =\"\";\n\nfunction setBothFromK(value) {\nk = +value;\nl = +( k * 2.2046226218).toFixed(1);\n}\nfunction setBothFromL(value) {\nl = +value;\nk = +( l / 2.2046226218).toFixed(1);\n}\n\nlet antibiotics = [\n { \n \"group\":\"\",\n \"route\":\"IV,IM,SQ BID\",\n \"perml\":\"mg/ml\",\n \"concentration\":\"50\",\n \"concSelect\": [\n { \"conc\": 50, \"name\": \"50 mg/ml\",\"perml\": \"ml\" }\n ],\n \"perkg\":\"mg/kg\",\n \"doseper\":\"10\",\n \"dosemin\":\"10\",\n \"dosemax\":\"30\",\n \"dosestep\":\"1\",\n \"dosevalue\":\"10\",\n \"hide\":\"\",\n \"name\":\"Amikacin\",\n \"calc\":\"Amikacin\",\n \"calcID\":\"Amikacin2\",\n \"decimal\": \"2\",\n \"appendose\": \" mg\",\n \"appendvol\": \" ml\",\n \"multiply\": \"\",\n \"class\": \"drug\",\n \"color\": \"green\"\n},\n{\n\"group\":\"\",\n\"route\":\"BID\",\n\"perml\":\"mg/ml\",\n\"concentration\":\"50\",\n\"concSelect\": [\n{\"id\": 1 , \"conc\": 50, \"name\": \"50 mg/ml\",\"perml\": \"ml\" },\n{\"id\": 2 , \"conc\": 100, \"name\": \"100 mg/ml\",\"perml\": \"\" },\n{\"id\": 3 , \"conc\": 150, \"name\": \"150 mg/ml\",\"perml\": \"\" },\n{\"id\": 4 , \"conc\": 200, \"name\": \"200 mg/ml\",\"perml\": \"\" },\n{\"id\": 5 , \"conc\": 400, \"name\": \"400 mg/ml\",\"perml\": \"\" }\n],\n\"perkg\":\"mg/kg\",\n\"doseper\":\"11\",\n\"dosemin\":\"11\",\n\"dosemax\":\"22\",\n\"dosestep\":\"1\",\n\"dosevalue\":\"11\",\n\"hide\":\"\",\n\"name\":\"Amoxicillin\",\n\"decimal\": \"2\",\n\"appendose\": \" mg\",\n\"appendvol\": \" ml\",\n\"class\": \"drug\"\n},\n{\n\"group\":\"\",\n\"route\":\"BID\",\n\"perml\":\"mg/ml\",\n\"concentration\":\"62.5\",\n\"concSelect\": [\n{\"id\": 1 , \"conc\": 62.5, \"name\": \"62.5\",\"perml\": \"ml\" },\n{\"id\": 2, \"conc\": 125, \"name\": \"125\",\"perml\": \"\" },\n{\"id\":3 , \"conc\": 250, \"name\": \"250\",\"perml\": \"\" },\n{\"id\": 4, \"conc\": 375, \"name\": \"375\",\"perml\": \"\" }\n],\n\"perkg\":\"mg/kg\",\n\"doseper\":\"13.75\",\n\"dosemin\":\"13.75\",\n\"dosemax\":\"25\",\n\"dosestep\":\"1\",\n\"dosevalue\":\"13.75\",\n\"hide\":\"\",\n\"name\":\"Amoxicillin-Clavulanate\",\n\"calc\":\"Amoxicillin-Clavulanate\",\n\"calcID\":\"Amoxicillin-Clavulanate2\",\n\"decimal\": \"2\",\n\"appendose\": \" mg\",\n\"appendvol\": \" ml\",\n\"class\": \"drug\",\n},\n{\n\"group\":\"\",\n\"route\":\"BID\",\n\"perml\":\"mg/ml\",\n\"concentration\":\"100\",\n\"concSelect\": [\n{\"id\": 1 , \"conc\": 100, \"name\": \"100\",\"perml\": \"ml\" },\n{\"id\": 2 , \"conc\": 125, \"name\": \"125\",\"perml\": \"\" },\n{\"id\": 3 , \"conc\": 250, \"name\": \"250\",\"perml\": \"\" },\n{ \"id\": 4 ,\"conc\": 500, \"name\": \"500\",\"perml\": \"\" }\n],\n\"perkg\":\"mg/kg\",\n\"doseper\":\"6.6\",\n\"dosemin\":\"6.6\",\n\"dosemax\":\"22\",\n\"dosestep\":\"1\",\n\"dosevalue\":\"6.6\",\n\"hide\":\"\",\n\"name\":\"Ampicillin\",\n\"calc\":\"Ampicillin\",\n\"calcID\":\"Ampicillin2\",\n\"decimal\": \"2\",\n\"appendose\": \" mg\",\n\"appendvol\": \" ml\",\n\"class\": \"drug\"\n}\n];1\n\n```\n\nThe problems are :\n\nOn page load, the select option value is not initially utilized in the drug dose equation ( I get NaN or Infinity). After selecting, it is.\n\nChanging the select option changes all of the drug concentrations, not just the individual drug concentration.\n\nAny help would be appreciated.\n\n========================================\n\nCode:\n```text\n<div class=\"row no-gap\">\n <div class=\"col-50 tablet-25\">\n <div class=\"item-content item-input item-input-outline item-input-with-value\">\n <div class=\"item-inner\">\n <div class=\"item-title item-label\">Pounds</div>\n <div class=\"item-input-wrap\">\n <input value={l} on:input=\"{e => setBothFromL(e.target.value)}\" min=\"0\" type=number placeholder=\" lbs\">\n </div>\n </div>\n </div>\n </div>\n <div class=\"col-50 tablet-25\">\n <div class=\"item-content item-input item-input-outline item-input-with-value\">\n <div class=\"item-inner\">\n <div class=\"item-title item-label\">Kilogram</div>\n <div class=\"item-input-wrap\">\n <input value={k} on:input=\"{e => setBothFromK(e.target.value)}\" min=\"0\" type=number placeholder=\"kgs\">\n </div>\n </div>\n </div>\n </div>\n\n</div>\n<h1>Antibiotics</h1>\n{#each antibiotics as antibiotic, i}\n<div class=\"Rtable-row eachdrug eachdrugE\" data-id=\"{i + 1}\">\n <div class=\"Rtable-cell drug-cell\">\n <span class=\"drugTitle searchme\">{antibiotic.name}\n {#if antibiotic.concSelect.length === 1}\n {antibiotic.concentration} {antibiotic.perml}\n {:else if antibiotic.concSelect.length > 1}\n\n <select bind:value={selected} on:change=\"{() => concs = selected}\">\n\n\n {#each antibiotic.concSelect as concSelect}\n <option value={concSelect.conc}>\n {concSelect.name}\n </option>\n {/each}\n\n </select>\n {/if}\n\n </span>\n\n </div>\n</div>\n<div>\n\n <div>\n Dose: <input bind:value={antibiotic.dosevalue} step={antibiotic.dosestep} min=\"{antibiotic.dosemin}\" max=\"{antibiotic.dosemax}\" type=number>\n\n {#if antibiotic.dosevalue > antibiotic.dosemax * 1.1 }\n <span class=\"error-message1 hidden-print\" transition:fly=\"{{ y: 10, duration: 500 }}\"><i class=\"fas fa-exclamation-triangle fa-sm fa-fw hidden-print\" data-fa-transform=\"up-2\"></i> Above Range</span>\n {/if}\n\n </div>\n <div> <span class=\"vol\">{(k * antibiotic.dosevalue).toFixed(antibiotic.decimal)} {antibiotic.appendose}</span>\n <span class=\"vol\">{#if antibiotic.concSelect.length === 1}\n{((k * antibiotic.dosevalue) / antibiotic.concentration).toFixed(antibiotic.decimal)} {antibiotic.appendvol}\n {:else if antibiotic.concSelect.length > 1}\n{((k * antibiotic.dosevalue) / concs).toFixed(antibiotic.decimal)} {antibiotic.appendvol}\n{/if} </span></div>\n</div>\n\n\n{/each}\n<style>\ninput{min-width:120px}\n.vol {\nbackground: rgba(0, 0, 0, .12); padding:5px;}\n.error-message1 {\nfont-size: 10px !important;\nline-height: 11px !important;\nfont-weight: normal;\ncolor: red;\nopacity: 0.5;\nfont-weight: 700;\n}\n.eachdrug {border-top: 1px solid #ccc; margin-top:15px}\n</style>\n\n<script>\nimport { fade, fly } from 'svelte/transition';\nlet k = '';\nlet l = '' ;\nlet selected;\nlet concs =\"\";\n\nfunction setBothFromK(value) {\nk = +value;\nl = +( k * 2.2046226218).toFixed(1);\n}\nfunction setBothFromL(value) {\nl = +value;\nk = +( l / 2.2046226218).toFixed(1);\n}\n\nlet antibiotics = [\n { \n \"group\":\"\",\n \"route\":\"IV,IM,SQ BID\",\n \"perml\":\"mg/ml\",\n \"concentration\":\"50\",\n \"concSelect\": [\n { \"conc\": 50, \"name\": \"50 mg/ml\",\"perml\": \"ml\" }\n ],\n \"perkg\":\"mg/kg\",\n \"doseper\":\"10\",\n \"dosemin\":\"10\",\n \"dosemax\":\"30\",\n \"dosestep\":\"1\",\n \"dosevalue\":\"10\",\n \"hide\":\"\",\n \"name\":\"Amikacin\",\n \"calc\":\"Amikacin\",\n \"calcID\":\"Amikacin2\",\n \"decimal\": \"2\",\n \"appendose\": \" mg\",\n \"appendvol\": \" ml\",\n \"multiply\": \"\",\n \"class\": \"drug\",\n \"color\": \"green\"\n},\n{\n\"group\":\"\",\n\"route\":\"BID\",\n\"perml\":\"mg/ml\",\n\"concentration\":\"50\",\n\"concSelect\": [\n{\"id\": 1 , \"conc\": 50, \"name\": \"50 mg/ml\",\"perml\": \"ml\" },\n{\"id\": 2 , \"conc\": 100, \"name\": \"100 mg/ml\",\"perml\": \"\" },\n{\"id\": 3 , \"conc\": 150, \"name\": \"150 mg/ml\",\"perml\": \"\" },\n{\"id\": 4 , \"conc\": 200, \"name\": \"200 mg/ml\",\"perml\": \"\" },\n{\"id\": 5 , \"conc\": 400, \"name\": \"400 mg/ml\",\"perml\": \"\" }\n],\n\"perkg\":\"mg/kg\",\n\"doseper\":\"11\",\n\"dosemin\":\"11\",\n\"dosemax\":\"22\",\n\"dosestep\":\"1\",\n\"dosevalue\":\"11\",\n\"hide\":\"\",\n\"name\":\"Amoxicillin\",\n\"decimal\": \"2\",\n\"appendose\": \" mg\",\n\"appendvol\": \" ml\",\n\"class\": \"drug\"\n},\n{\n\"group\":\"\",\n\"route\":\"BID\",\n\"perml\":\"mg/ml\",\n\"concentration\":\"62.5\",\n\"concSelect\": [\n{\"id\": 1 , \"conc\": 62.5, \"name\": \"62.5\",\"perml\": \"ml\" },\n{\"id\": 2, \"conc\": 125, \"name\": \"125\",\"perml\": \"\" },\n{\"id\":3 , \"conc\": 250, \"name\": \"250\",\"perml\": \"\" },\n{\"id\": 4, \"conc\": 375, \"name\": \"375\",\"perml\": \"\" }\n],\n\"perkg\":\"mg/kg\",\n\"doseper\":\"13.75\",\n\"dosemin\":\"13.75\",\n\"dosemax\":\"25\",\n\"dosestep\":\"1\",\n\"dosevalue\":\"13.75\",\n\"hide\":\"\",\n\"name\":\"Amoxicillin-Clavulanate\",\n\"calc\":\"Amoxicillin-Clavulanate\",\n\"calcID\":\"Amoxicillin-Clavulanate2\",\n\"decimal\": \"2\",\n\"appendose\": \" mg\",\n\"appendvol\": \" ml\",\n\"class\": \"drug\",\n},\n{\n\"group\":\"\",\n\"route\":\"BID\",\n\"perml\":\"mg/ml\",\n\"concentration\":\"100\",\n\"concSelect\": [\n{\"id\": 1 , \"conc\": 100, \"name\": \"100\",\"perml\": \"ml\" },\n{\"id\": 2 , \"conc\": 125, \"name\": \"125\",\"perml\": \"\" },\n{\"id\": 3 , \"conc\": 250, \"name\": \"250\",\"perml\": \"\" },\n{ \"id\": 4 ,\"conc\": 500, \"name\": \"500\",\"perml\": \"\" }\n],\n\"perkg\":\"mg/kg\",\n\"doseper\":\"6.6\",\n\"dosemin\":\"6.6\",\n\"dosemax\":\"22\",\n\"dosestep\":\"1\",\n\"dosevalue\":\"6.6\",\n\"hide\":\"\",\n\"name\":\"Ampicillin\",\n\"calc\":\"Ampicillin\",\n\"calcID\":\"Ampicillin2\",\n\"decimal\": \"2\",\n\"appendose\": \" mg\",\n\"appendvol\": \" ml\",\n\"class\": \"drug\"\n}\n];1\n</script>\n```\n\n```js\n<select bind:value={selected} on:change=\"{() => concs = selected}\">\n...\n</select>\n```\n\n```js\n<select bind:value={antibiotic.concs}>\n...\n</select>\n...\n{#if antibiotic.concSelect.length === 1}\n ...\n{:else if antibiotic.concSelect.length > 1}\n {((k * antibiotic.dosevalue) / antibiotic.concs).toFixed(antibiotic.decimal)}{antibiotic.appendvol}\n{/if}\n...\n\n<script>\n...\nlet antibiotics = [\n {\n ...\n \"concs\": 50,\n },\n {\n ...\n \"concs\": 100,\n },\n {\n ...\n \"concs\": 62.5,\n },\n {\n ...\n \"concs\": 100,\n },\n]\n...\n</script>\n```\n\n```text\non:change\n```\n\n```text\nbind:value={concs}\n```\n\n```text\nNaN\n```\n\n```text\nconcs\n```\n\n```text\nconcs\n```\n\n```text\nantibiotic\n```\n\n========================================\n\nComments:\n- An additional newbie question. If I want to access the 2nd drugs input value, `bind:value={antibiotic.dosevalue}` ,how can I do that? I tried antibiotic.dosevalue[1], but that is not obviously the correct way.\n- @Macsupport If you're trying to access it from within your `each` loop, then it's simply `{antibiotic.dosevalue}`. `dosevalue` is not an array, it is a key on each of your `antibiotic` objects. If you're trying to access it from *outside* the `each` loop, then you'll have to specify which antibiotics' object you want to read the dosevalue of. For instance, for the 2nd antibiotic in the list, that would be `{antibiotics[1].dosevalue}` (note the **s** in antibiotics, we're referencing the whole array here).\n- @Macsupport Also, if you have a work-in-progress REPL and tell me what you're trying to do, I'll be happy to help if I can ;)\n- Thanks! What I'm working on is a bit more convoluted, for me at least. Here is the REPL I added some explanation on the REPL","metadata":{"transformedAt":"2026-08-18T18:33:40.685Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":504,"estimatedTokens":2951}}333{"id":"stack-45714809","source":"stackoverflow","questionId":45714809,"title":"Sveltejs render html attribute conditionally","tags":["svelte"],"text":"Title: Sveltejs render html attribute conditionally\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nHow can one render an attribute on a html element conditionally with svelte? To be clear, I am not talking about a conditional value, but the attribute presence itself.\n\nFor instance, I want to autofocus only the first item in this list of inputs:\n\n```\n{{#each codeInputs as codeInput, index}}\n \n{{/each}}\n```\n\nThe attribute `autofocus` should be there only for the first item. I could use index to detect the first item, but `autofocus=\"{{index===0}}\"` renders `autofocus=\"true\"` or `\"false\"`, so that is not what I need. \n\nAlso see https://github.com/sveltejs/svelte/issues/259\n\n========================================\n\nCode:\n```text\n{{#each codeInputs as codeInput, index}}\n <input bind:value=\"inputCodes[index]\" type=\"text\" autofocus> \n{{/each}}\n```\n\n```text\nautofocus\n```\n\n```text\nautofocus=\"{{index===0}}\"\n```\n\n```text\nautofocus=\"true\"\n```\n\n```text\n\"false\"\n```\n\n```text\nautofocus='{{xyz}}\n```\n\n========================================\n\nComments:\n- Excellent, that covers Boolean html5 attributes defined in html, as you explain in github.com/sveltejs/svelte/issues/301. My use case is solved by that.\n- But there is a related question: how about String attributes\n- Currently, that's not possible. We haven't yet encountered a situation where it's a problem (as opposed to a theoretical concern), but if it's causing a bug in your app, please raise an issue!","metadata":{"transformedAt":"2026-08-18T18:33:40.685Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":54,"estimatedTokens":367}}334{"id":"stack-68722048","source":"stackoverflow","questionId":68722048,"title":"How to enable JS and SCSS sourcemaps with SvelteKit?","tags":["svelte","sveltekit"],"text":"Title: How to enable JS and SCSS sourcemaps with SvelteKit?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI've set up a sveltekit project with scss support locally.\nBut all the generated JS and CSS is inline.\n\nHow to generate a `bundle.js` and `bundle.css` with sourcemaps at development time?\n\n**svelte.config.js** ( SvelteKit v1.0.0-next.144 )\n\n```\nimport preprocess from 'svelte-preprocess';\n\nconst production = !process.env.ROLLUP_WATCH;\n\nconst config = {\n kit: {\n target: '#svelte'\n },\n preprocess: preprocess({\n scss: {\n includePaths: ['src'],\n prependData: `@import 'src/style/_config.scss';`\n },\n sourceMap: true,\n }),\n compilerOptions: {\n dev: !production\n }\n};\n\nexport default config;\n```\n\n========================================\n\nTop Answer:\n**Workaround:**\n\nPut SCSS files in `/static/scss` and generate `style.css`. In my case with a file watcher in phpStorm.\n\nReference it in `/src/routes/__layout.svelte` like this\n\n```\n\n \n\n```\n\nIn devtools scss files are shown next to a style, but they have nothing to do with the specific style. Sucks\n\n========================================\n\nCode:\n```text\nimport preprocess from 'svelte-preprocess';\n\nconst production = !process.env.ROLLUP_WATCH;\n\nconst config = {\n kit: {\n target: '#svelte'\n },\n preprocess: preprocess({\n scss: {\n includePaths: ['src'],\n prependData: `@import 'src/style/_config.scss';`\n },\n sourceMap: true,\n }),\n compilerOptions: {\n dev: !production\n }\n};\n\nexport default config;\n```\n\n```text\nbundle.js\n```\n\n```text\nbundle.css\n```\n\n```js\nimport '../style/global.scss'\n```\n\n```text\n<svelte:head>\n <link rel=\"stylesheet\" href=\"../static/style.css\">\n</svelte:head>\n```\n\n```text\n/static/scss\n```\n\n```text\nstyle.css\n```\n\n```text\n/src/routes/__layout.svelte\n```\n\n========================================\n\nComments:\n- you can also separate your scss files from the generated CSS by using `savePath` if you're using `vscode-live-sass-compiler` ( github.com/ritwickdey/vscode-live-sass-compiler/blob/master/‌​… )","metadata":{"transformedAt":"2026-08-18T18:33:40.685Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":114,"estimatedTokens":522}}335{"id":"stack-63014165","source":"stackoverflow","questionId":63014165,"title":"Svelte application bug: converting string to boolean in the view fails","tags":["javascript","svelte","svelte-3"],"text":"Title: Svelte application bug: converting string to boolean in the view fails\nTags: javascript, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nIn a Svelte app, I have this array of countries:\n\n```\nlet countries = [\n {\n name:\"Alegeria\",\n status: \"1\"\n },\n {\n name:\"Bulgaria\",\n status :\"0\"\n }\n]\n```\n\nNote the `status` property is a string. I iterate the array this way:\n\n```\n{#if countries.length > 0}\n\n \n \n Country\n Status\n \n \n \n {#each countries as c} \n \n {c.name}\n \n \n {/each}\n \n\n{:else}\nNo countries found\n\n{/if}\n```\n\nAs you can see, I try to convert the value of the `status` property to a boolean this by using `Boolean(Number(c.status))`.\n\nInstead of the desired conversion I get the error: `Can only bind to an identifier (e.g.`foo`) or a member expression` as the **REPL** shows.\n\nWhat am I doing wrong?\n\n========================================\n\nTop Answer:\nI think the problem is that the Boolean() function creates a new object, to which you can't bind, because it is never again referenced. You can bind directly to your array of values in `countries`, using this code:\n\n```\n{#each countries as c, index} \n \n {c.name}\n \n \n{/each}\n```\n\nWhat has changed is that you use the `index` parameter of the `#each` loop now to bind to the variable of the countries array. Please be aware that in order for this to properly work, you need to change the status values to `true` or `false`. Otherwise it will still work, but the initial value will always be `true`.\n\n========================================\n\nCode:\n```text\nlet countries = [\n {\n name:\"Alegeria\",\n status: \"1\"\n },\n {\n name:\"Bulgaria\",\n status :\"0\"\n }\n]\n```\n\n```text\n{#if countries.length > 0}\n<table class=\"table\">\n <thead>\n <tr>\n <th>Country</th>\n <th class=\"text-right\">Status</th>\n </tr>\n </thead>\n <tbody>\n {#each countries as c} \n <tr>\n <td>{c.name}</td>\n <td class=\"text-right\"><Switch bind:checked={Boolean(Number(c.status))} /></td>\n </tr>\n {/each}\n </tbody>\n</table>\n{:else}\n<p class=\"alert alert-danger\">No countries found</p>\n{/if}\n```\n\n```text\nstatus\n```\n\n```text\nstatus\n```\n\n```text\nBoolean(Number(c.status))\n```\n\n```text\nCan only bind to an identifier (e.g.\n```\n\n```text\n) or a member expression\n```\n\n```text\nfunction handleClick(country) {\n countries.find(c => c.name == country.name).status = (country.status == \"1\") ? \"0\" :\"1\"\n}\n```\n\n```text\n<Switch checked={Boolean(Number(c.status))} on:change={() => handleClick(c)}/>\n```\n\n```text\nbind\n```\n\n```text\nbind\n```\n\n```text\nBoolean(Number(())\n```\n\n```text\nbind\n```\n\n```text\nchecked={Boolean(Number(c.status))}\n```\n\n```text\nchange\n```\n\n```text\n{#each countries as c, index} \n <tr>\n <td>{c.name}</td>\n <td class=\"text-right\"><Switch bind:checked={countries[index].status} /></td>\n </tr>\n{/each}\n```\n\n```text\ncountries\n```\n\n```text\nindex\n```\n\n```text\n#each\n```\n\n```text\ntrue\n```\n\n```text\nfalse\n```\n\n```text\ntrue\n```\n\n```text\n<td class=\"text-right\"><Switch checked={Boolean(Number(c.status))} /></td>\n```\n\n```text\nfunction onClick(event, country) {\n countries = countries.map(c => {\n if (c.name === country.name) {\n c.status = event.target.checked ? '1' : '0';\n }\n return c;\n })\n }\n\n ...\n\n <td class=\"text-right\"><Switch checked={c.status === '1'} on:click={(e) => onClick(e, c)}/></td>\n```\n\n```text\nSwitch\n```\n\n```text\nbind:\n```\n\n========================================\n\nComments:\n- Why don't you bind directly to the countries status? Does it have to be 0 and 1 instead of false and true?\n- @Gh05d I would still have to convert the strings `\"0\"` and `\"1\"` to tha numbers the strings `0` and `1`. So I would have the same problem.\n- I need to change the `countries` array (the data has to be saved in a database) si I guess I can't dich `bind`.\n- I mean you can change it without bind. (Updated the answer with a working code example)\n- I use Switch not Checkbox\n- Well you haven't mentioned how you are defining `Switch`, so I can't help you there. I only used a checkbox in my demo code that I wrote for you so that it could work, and you could see an example of manually defining a binding between a variable and input box.","metadata":{"transformedAt":"2026-08-18T18:33:40.685Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":230,"estimatedTokens":1072}}336{"id":"stack-56863265","source":"stackoverflow","questionId":56863265,"title":"How to link relative to current page in svelte/sapper component?","tags":["svelte","sapper"],"text":"Title: How to link relative to current page in svelte/sapper component?\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI've got a component in the sapper template with pagination. Currently all links are behaving as though they're relative to root (`localhost:3000/` in this case) regardless of whether the href is in the form `page` or `/page`, (I even tried `./page`.)\n\nSo for pagination where I just want to modify the query string I've got to pass the full path to the current view into the component for the href, which is a bit of a pain. Is there something I'm doing wrong that relative links aren't working? (Even better if there's a way to make them work calling `goto()` directly, I've got a \"Goto page: [x]\" input.) If not is there a recommended way to get the current path from inside a component so I can throw that in the pagination component?\n\n========================================\n\nTop Answer:\na workaround actually is possible, if your page is for example is http://localhost:3000/product/foo\n*normally* in your foo.svelte file the link to local page should like this:\n\n```\nlink to same page\n```\n\nbut in sapper you have to put the page full path:\n\n```\nlink to same page\n```\n\ntested on:\n\"sapper\": \"^0.28.10\",\n\"svelte\": \"^3.29.4\"\n\n========================================\n\nCode:\n```text\nlocalhost:3000/\n```\n\n```text\npage\n```\n\n```text\n/page\n```\n\n```text\n./page\n```\n\n```text\ngoto()\n```\n\n```text\nwindow.location.href\n```\n\n```text\n<a href=\"#anchor\"> link to same page </a>\n```\n\n```text\n<a href=\"product/foo#anchor\"> link to same page </a>\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.685Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":63,"estimatedTokens":391}}337{"id":"stack-72518587","source":"stackoverflow","questionId":72518587,"title":"Svelte conditional class with a Tailwind class including a slash in its name","tags":["tailwind-css","svelte"],"text":"Title: Svelte conditional class with a Tailwind class including a slash in its name\nTags: tailwind-css, svelte\nSource: Stack Overflow\n\nQuestion:\nI use Tailwind in a Svelte project.\n\nSome Tailwind classes have a slash in their name,\nnot compatible with Svelte conditional classes.\n\nExample:\n\n```\n\n```\n\nthere is an error on the `3` : `Expected >svelte(unexpected-token)`\n\n**How is it possible to use Tailwind classes with a slash in their name in a Svelte conditional class?**\n\n========================================\n\nTop Answer:\nIf you are using tailwind, you can also use the @apply directive and a custom class :\n\n```\n\n```\n\n```\n.custom-class {\n @apply w-1/3;\n}\n```\n\n========================================\n\nCode:\n```html\n<div class:w-1/3={condition}>\n```\n\n```text\n3\n```\n\n```text\nExpected >svelte(unexpected-token)\n```\n\n```html\n<div class={{ 'w-1/3': condition }}>\n```\n\n```html\n<div class={condition ? 'w-1/3' : ''}>\n```\n\n```text\nclsx\n```\n\n```text\nclass\n```\n\n```html\n<div class:custom-class>\n```\n\n```css\n.custom-class {\n @apply w-1/3;\n}\n```\n\n========================================\n\nComments:\n- **`/` is a valid character in class names.** The CSS specification defines that non-ASCII characters are valid: drafts.csswg.org/css-syntax/#ident-token-diagram It’s svelte, that doesn’t support valid class names.\n- @MaxHoffmann: It's not valid, because *it is* ASCII but not a letter, underscore or dash.\n- Not if it’s escaped and therefore a Unicode code point as defined in the specification: drafts.csswg.org/css-syntax/#escaping It’s in the spec, all browsers support it and that’s also the reason why Tailwind is able to use slashes in class names. It’s Svelte’s compiler that cannot handle it in the directive. Your example is the best proof that it works as soon as one doesn’t use Svelte’s proprietary syntax.\n- Also adding Matthias Bynens fantastic page here that demonstrates lots of valid class names, including using emojis: mathiasbynens.be/demo/crazy-class\n- This way it's not wrong, but it's not the best solution. The good solution is here: stackoverflow.com/a/77912688/1944500 Svelte will process the CSS class.\n- However, in the case of CSS modules, be careful not to end up bloating things and generating too much CSS. Excessive use of `@apply` is not recommended, especially not in CSS modules. Why stop using `@apply`","metadata":{"transformedAt":"2026-08-18T18:33:40.685Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":85,"estimatedTokens":586}}338{"id":"stack-60201324","source":"stackoverflow","questionId":60201324,"title":"Send data from one page to another instead of preloading?","tags":["svelte","sapper","svelte-3"],"text":"Title: Send data from one page to another instead of preloading?\nTags: svelte, sapper, svelte-3\nSource: Stack Overflow\n\nQuestion:\nSay I have a `blog` route that loads a complete array of all blog posts. The individual blog posts live at `blog/[postId]`. Is there a Sapper-idiomatic way to pass the data for the individual post from `blog` to `blog/[postId]`?\n\nEssentially, if you're on `blog` I'd like to preload the code for displaying `blog/[postId]`. And then when you click a link to `blog/[postId]`, navigate there instantly and display data from `blog`. But of course if you navigate directly to `blog/[postId]` then `preload()` should still be called.\n\n`prefetch` doesn't quite do it because that still requires a network request. I also tried a preload that checks a store and doesn't issue the network request unless its empty, but you can't use stores in ``.\n\n========================================\n\nCode:\n```text\nblog\n```\n\n```text\nblog/[postId]\n```\n\n```text\nblog\n```\n\n```text\nblog/[postId]\n```\n\n```text\nblog\n```\n\n```text\nblog/[postId]\n```\n\n```text\nblog/[postId]\n```\n\n```text\nblog\n```\n\n```text\nblog/[postId]\n```\n\n```text\npreload()\n```\n\n```text\nprefetch\n```\n\n```text\n<script context=\"module\">\n```\n\n```html\n<!-- blog/index.svelte -->\n<script context=\"module\">\n export async function preload (page, session) {\n let {posts} = session;\n if (undefined === posts) {\n const response = await this.fetch('blog/posts.json');\n posts = await response.json();\n session.posts = posts\n }\n\n return {posts}\n }\n</script>\n\n<script>\n export let posts;\n</script>\n\n{#each posts as post}\n <!-- ... -->\n{/each}\n```\n\n```html\n<!-- blog/[slug].svelte -->\n<script context=\"module\">\n export async function preload (page, session) {\n const {slug} = page.params\n const {posts} = session\n let post\n\n if (undefined === posts) {\n const response = await this.fetch(`blog/${slug}.json`)\n post = await response.json()\n } else {\n post = posts.find(p => p.slug === slug)\n }\n\n if (undefined === post) {\n this.error(404, \"Sorry we couldn\\'t find that post\")\n }\n\n return {post}\n }\n</script>\n\n<script>\n export let post\n</script>\n\n<!-- ... render post -->\n```\n\n```js\nsapper.middleware({\n // Define session parameter as an empty object\n session: (req, res) => ({})\n})\n```\n\n```text\n_layout\n```\n\n```text\npreload()\n```\n\n```text\npreload()\n```\n\n```text\nsession\n```\n\n```text\nthis.fetch()\n```\n\n```text\n[slug].svelte\n```\n\n```text\nsession.posts\n```\n\n```text\nsession\n```\n\n```text\npreload(page, session)\n```\n\n```text\nundefined\n```\n\n```text\nserver.js\n```\n\n========================================\n\nComments:\n- You could probably do that in your layout route. If that lives in your blog directory you can preload all posts in there and then according to each id you display that data. But I would probably just preload a single blog id and then once it's loaded fetch all the other posts and store them in a store.\n- Thanks for the suggestion. It set me on the path to figuring it out. Turns out `preload()` always gets called on navigation, regardless of whether its in `_layout.svelte`, a regular page component, or both. I ended up storing the data in the second parameter to `preload()`, `session`, and only calling `this.fetch()` if it was empty or stale.","metadata":{"transformedAt":"2026-08-18T18:33:40.685Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":172,"estimatedTokens":824}}339{"id":"stack-66982839","source":"stackoverflow","questionId":66982839,"title":"Is it possible to dispatch a svelte custom event with a target object?","tags":["svelte","custom-events"],"text":"Title: Is it possible to dispatch a svelte custom event with a target object?\nTags: svelte, custom-events\nSource: Stack Overflow\n\nQuestion:\nIs it possible to dispatch a svelte event (created with `createEventDispatcher`) with a target object like a native browser event?\n\nI.e. receiving on the handler side `event.target.value` instead of event.detail.\n\n========================================\n\nTop Answer:\nModified from hackape's answer\n\n```\nimport { get_current_component } from 'svelte/internal'\n\nfunction createEventDispatcher() {\n const component = get_current_component(bubbles = true);\n return (type, target, detail) => {\n const callbacks = component.$$.callbacks[type];\n if (callbacks) {\n const event = new CustomEvent(type, { bubbles, detail });\n // the key is to call `dispatchEvent` manually to set `event.target`\n target.dispatchEvent(event);\n /* You have already raised an event, you should not repeat the callbacks to avoid duplication\n callbacks.slice().forEach((fn) => {\n fn.call(component, event);\n });\n */\n }\n };\n}\n```\n\n========================================\n\nCode:\n```text\ncreateEventDispatcher\n```\n\n```text\nevent.target.value\n```\n\n```html\n<!-- Inner.svelte -->\n<script>\nimport { createEventDispatcher } from 'svelte'\nconst dispatch = createEventDispatcher()\nconst dispatchFoo = () => dispatch('foo', 'bar')\n</script>\n\n<button on:click={dispatchFoo}>send</button>\n\n<!-- Outer.svelte -->\n<script>\nimport Inner from './Inner.svelte'\nconst handleFoo = (e) => { console.log('receive foo', e) }\n</script>\n\n<Inner on:foo={handleFoo}></Inner>\n```\n\n```js\nimport { get_current_component } from 'svelte/internal'\n\nfunction createEventDispatcher() {\n const component = get_current_component();\n return (type, target, detail) => {\n const callbacks = component.$$.callbacks[type];\n if (callbacks) {\n const event = new CustomEvent(type, { detail });\n // the key is to call `dispatchEvent` manually to set `event.target`\n target.dispatchEvent(event);\n callbacks.slice().forEach((fn) => {\n fn.call(component, event);\n });\n }\n };\n}\n```\n\n```text\nInner\n```\n\n```text\nOuter\n```\n\n```text\nhandleFoo\n```\n\n```text\nOuter\n```\n\n```text\nInner\n```\n\n```text\ninner.$$.callbacks[\"foo\"]\n```\n\n```text\ndispatch\n```\n\n```text\ninner.$$.callbacks[\"foo\"]\n```\n\n```text\nCustomEvent\n```\n\n```text\ncustomEvent.target\n```\n\n```text\nelement.dispatchEvent(customEvent)\n```\n\n```text\nelement.dispatchEvent\n```\n\n```text\ncreateEventDispatcher\n```\n\n```js\nimport { get_current_component } from 'svelte/internal'\n\nfunction createEventDispatcher() {\n const component = get_current_component(bubbles = true);\n return (type, target, detail) => {\n const callbacks = component.$$.callbacks[type];\n if (callbacks) {\n const event = new CustomEvent(type, { bubbles, detail });\n // the key is to call `dispatchEvent` manually to set `event.target`\n target.dispatchEvent(event);\n /* You have already raised an event, you should not repeat the callbacks to avoid duplication\n callbacks.slice().forEach((fn) => {\n fn.call(component, event);\n });\n */\n }\n };\n}\n```\n\n```text\nfn.call(...)\n```\n\n```text\ntarget.dispatchEvent()\n```\n\n```js\n// Component.svelte\n<script>\n import { createEventDispatcher } from 'svelte'\n const payload = 'foo'\n\n function onClick (event) {\n const { target } = event\n dispatch('myEvent', { target, payload })\n }\n</script>\n\n<button on:click={ onClick }></button>\n```\n\n```js\n<script>\n import Component from 'Component.svelte'\n\n function handler (event) {\n const { target, payload } = event.detail\n }\n</script>\n\n<Component on:myEvent={ handler }/>\n```\n\n```text\ntarget\n```\n\n========================================\n\nComments:\n- Great elaboration on the subject. Yes, it's quite a hack, but with a lot of insights. Thanks!\n- One nice thing about svelte is that it compiles to plain old javascript. If you understand the internal, you can almost always hack your way around.\n- Please, comment the answer of the user, don't publish it as a new answer.","metadata":{"transformedAt":"2026-08-18T18:33:40.685Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":202,"estimatedTokens":1010}}340{"id":"stack-69832442","source":"stackoverflow","questionId":69832442,"title":"How to pass animate:flip to a component in svelte?","tags":["svelte","svelte-3","svelte-component","svelte-transition"],"text":"Title: How to pass animate:flip to a component in svelte?\nTags: svelte, svelte-3, svelte-component, svelte-transition\nSource: Stack Overflow\n\nQuestion:\nI'm trying to animate this list of Widgets. Of course I can't just `animate:flip` a component, Svelte needs a DOM element.\n\n```\n\n{#each widgets as widget (widget.id)}\n \n{/each}\n```\n\nI normally would have solved it with a simple container div:\n\n```\n\n{#each widgets as widget (widget.id)}\n \n \n \n{/each}\n```\n\nHowever, as I'm using a CSS Grid around the `#each`, I need Widget to be the immediate child. I can't wrap it in anything. How can I solve this? Is there any way to pass `animate:flip` to the Widget component and handling it there?\n\nHere is a REPL of what I'm trying to achieve. I'm unable to get the same behaviour when each row (containing three cells) is a Component.\n\n========================================\n\nTop Answer:\nIdea 1:\napply `display: contents` to the container div.\n\nIdea 2:\nObvious but maybe you can add `animate:flip` to the `Widget` component, maybe conditionally with a prop.\n\n========================================\n\nCode:\n```text\n<!-- invalid -->\n{#each widgets as widget (widget.id)}\n <Widget {...widget} animate:flip/>\n{/each}\n```\n\n```text\n<!-- does not apply to my situation -->\n{#each widgets as widget (widget.id)}\n <div animate:flip>\n <Widget {...widget} />\n </div>\n{/each}\n```\n\n```text\nanimate:flip\n```\n\n```text\n#each\n```\n\n```text\nanimate:flip\n```\n\n```css\ndisplay: grid;\ngrid-column: 1/-1;\ngrid-template-columns: subgrid;\n```\n\n```text\n<table>, <tr>, <td>\n```\n\n```text\n<div>\n```\n\n```text\ndisplay: table, table-row, table-cell\n```\n\n```text\ndisplay: contents\n```\n\n```text\nanimate:flip\n```\n\n```text\nWidget\n```\n\n========================================\n\nComments:\n- How's the html structure inside the Widget? Maybe you could make a small REPL ?\n- This is an example with a grid containing a Component. What's different in your case that the wrapper div with animate on it, is not possible?\n- @Corrl Thank you for looking into this! I've adapted your example to my situation: svelte.dev/repl/4707e7f2469e42ac80771d1314b51e49?version=3.4‌​4.1 . Here, wrapping the Component breaks the CSS grid.\n- Since you're basically trying to animate rows, you'll have to split your grid into two components: an outer grid of 1 column and *n* rows, and for each row, the same inner grid of *p* columns applied. Like this: svelte.dev/repl/d0a93034de2c4c27b3f1beb313427c1a?version=3.4‌​4.1\n- If your question is how to do this without the intermediate wrapper div, this answer is you cannot, because a grid row is not a document node.\n- @ThomasHennes Thank you for helping! The issue with introducing a nested grid seems to be that the cell widths need to be specified, as in the case with your REPL. The cells no longer adapt their widths, as they do in [the REPL I posted](svelte.dev/repl/4707e7f2469e42ac80771d1314b51e49?ver‌​sion=3.44.1). Do you think this is impossible to achieve if I want *both* CSS Grid and `flip:animate`, and I should be looking for another CSS layout solution?\n- \"cell widths need to be specified, as in the case with your REPL\" - you mean because they are set to '1fr 1fr 1fr' instead of 'auto auto auto'? \" The cells no longer adapt their widths\" - I can't see that, could you describe why you mean that?\n- @Corrl I've written a new REPL without Components that shows the behaviour I'm trying to achieve. I'm unable to achieve it *with* a Component representing each row (three cells): svelte.dev/repl/3386549a0e7f4488b6b8113c8b9874d6?version=3.4‌​4.1\n- Thanks Anna, just got what you mean! I'll have a look...\n- @Corrl I added `auto auto auto` and some zeroes and get this behaviour on your REPL: imgur.com/a/KZKVpJ0 whereas I'm looking for this alignment: imgur.com/a/M5Va5vL\n- Since you're looking for a 'table-like' behaviour, using this instead of grid might be a solution? Have a look at this REPL using \"display: table/table-row/table-cell\" (using table/tr/td elements might work as well)\n- In fact I moved away from table to CSS grid for some styling requirements that are no longer needed in this project, so I think this might be a good solution for my case! Thank you @Corrl !\n- 'display: contents' sounds like a good idea, but unfortunately it seems to break the animate - just tried it in this REPL\n- Thank you Zachiah. Idea 1 seems not to work. Could you please explain what you mean by idea 2?\n- What is inside the widget component? Could you just put `animate:flip` inside it?\n- @Zachiah I made a REPL here to show the example: svelte.dev/repl/4707e7f2469e42ac80771d1314b51e49?version=3.4‌​4.1 It's the lower grid that I'm trying to animate.\n- Neither of these worked for me. The component being looped through are inside a grid, so adding the CSS mentioned above in any combination doesn't work.\n- My element had `inline-block` which is why the grid styles were messing with it. Removing that was the solution for me. Man that took a few hours...","metadata":{"transformedAt":"2026-08-18T18:33:40.685Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":120,"estimatedTokens":1256}}341{"id":"stack-73543472","source":"stackoverflow","questionId":73543472,"title":"How do I set the type, for custom store, when I pass store via setContext or component prop?","tags":["typescript","svelte","jsdoc","sveltekit","svelte-store"],"text":"Title: How do I set the type, for custom store, when I pass store via setContext or component prop?\nTags: typescript, svelte, jsdoc, sveltekit, svelte-store\nSource: Stack Overflow\n\nQuestion:\nWhen using SvelteKit, the `store` must always be created in the route `page`/`layout`, otherwise there will be problems with the status being up-to-date after refreshing.\n\nYou can't create a `store` in an imported module, because the server-side module only loads once, and this causes errors in the `store`.\n\nAll this leads to a certain situation with types.\n\n**The problem:**\n\nI create and pass the store from `+page.svelte` to `Child.svelte`, via `setContext`:\n\n```\n\n import Child from \"./Child.svelte\";\n import { writable } from 'svelte/store';\n import { setContext } from \"svelte\";\n \n function createCount() {\n /** @type {import(\"svelte/store\").Writable} */\n const { subscribe, set, update } = writable(0);\n \n return {\n subscribe,\n increment: () => update(n => n + 1),\n decrement: () => update(n => n - 1),\n reset: () => set(0)\n };\n }\n \n export const count = createCount();\n \n setContext(\"store\", count);\n\n```\n\n```\n\nimport { getContext } from \"svelte\";\n \n const count = getContext(\"store\");\n\n### The count is {$count}\n\n+\n-\nreset\n```\n\nIn `Child.svelte` the type for `store` count is `any`:\n\nAnd it should be as in the place of the declaration:\n\n**That's what it should be** the type of `store`, returned from getContext(\"store\"):\n\n```\nconst count: {\n subscribe: (this: void, run: Subscriber, invalidate?: Invalidator | undefined) => Unsubscriber;\n increment: () => void;\n decrement: () => void;\n reset: () => void;\n}\n```\n\nPassing via `` has the same problem.\n\n**QUESTION:** How can this be done?\n\n### Alternative\n\nIt doesn't. You can only create a `store` in a module, and import it - then the types are preserved.\n\nBut this creates some problems with `store` validity, as I wrote about at the beginning.\n\n========================================\n\nCode:\n```html\n<!-- +page.svelte -->\n<script>\n import Child from \"./Child.svelte\";\n import { writable } from 'svelte/store';\n import { setContext } from \"svelte\";\n \n function createCount() {\n /** @type {import(\"svelte/store\").Writable<number>} */\n const { subscribe, set, update } = writable(0);\n \n return {\n subscribe,\n increment: () => update(n => n + 1),\n decrement: () => update(n => n - 1),\n reset: () => set(0)\n };\n }\n \n export const count = createCount();\n \n setContext(\"store\", count);\n</script>\n\n<Child/>\n```\n\n```html\n<!-- Child.svelte -->\n<script>\nimport { getContext } from \"svelte\";\n \n const count = getContext(\"store\");\n</script>\n\n<h1>The count is {$count}</h1>\n\n<button on:click={count.increment}>+</button>\n<button on:click={count.decrement}>-</button>\n<button on:click={count.reset}>reset</button>\n```\n\n```text\nconst count: {\n subscribe: (this: void, run: Subscriber<number>, invalidate?: Invalidator<number> | undefined) => Unsubscriber;\n increment: () => void;\n decrement: () => void;\n reset: () => void;\n}\n```\n\n```text\nstore\n```\n\n```text\npage\n```\n\n```text\nlayout\n```\n\n```text\nstore\n```\n\n```text\nstore\n```\n\n```text\n+page.svelte\n```\n\n```text\nChild.svelte\n```\n\n```text\nsetContext\n```\n\n```text\nChild.svelte\n```\n\n```text\nstore\n```\n\n```text\nany\n```\n\n```text\nstore\n```\n\n```text\n<Child {count}/>\n```\n\n```text\nstore\n```\n\n```text\nstore\n```\n\n```html\n<script lang=\"ts\">\n import { getContext } from 'svelte';\n\n // Prop\n export let count: StoreType;\n\n // Context\n const store = getContext<StoreType>('context');\n</script>\n```\n\n```html\n<script>\n import { getContext } from 'svelte';\n\n // Prop\n /** @type {StoreType} */\n export let count;\n\n // Context\n /** @type {StoreType} */\n const store = getContext('context');\n</script>\n```\n\n```js\n// create-count.js\nimport { writable } from 'svelte/store';\n\nexport function createCount() {\n const { subscribe, set, update } = writable(0);\n\n return {\n subscribe,\n increment: () => update(n => n + 1),\n decrement: () => update(n => n - 1),\n reset: () => set(0),\n };\n}\n```\n\n```html\n<script>\n import { getContext } from 'svelte';\n\n /** @type {ReturnType<import('./create-count').createCount>} */\n export let count;\n\n /** @type {ReturnType<import('./create-count').createCount>} */\n const store = getContext('context');\n</script>\n```\n\n```html\n<script lang=\"ts\">\n import type { createCount } from './create-count';\n import { getContext } from 'svelte';\n\n export let count: Count;\n\n const store = getContext<Count>('context');\n\n type Count = ReturnType<typeof createCount>;\n</script>\n```\n\n```text\npreprocess-svelte\n```\n\n```text\n.d.ts\n```\n\n```text\n@typedef\n```\n\n```text\ncreateCount\n```\n\n========================================\n\nComments:\n- Thanks, this completely solves the problem.\n- The second suggestion was great. I exported the type from the same file (in your example it would be `export type Count = ReturnType` in `./create-count` since it felt cleaner to only import the type wherever needed instead of importing the creator-function many everywhere","metadata":{"transformedAt":"2026-08-18T18:33:40.686Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":27,"totalLines":279,"estimatedTokens":1276}}342{"id":"stack-48177495","source":"stackoverflow","questionId":48177495,"title":"Svelte store not firing onchange when nested components update","tags":["javascript","svelte"],"text":"Title: Svelte store not firing onchange when nested components update\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nLet's say I want to create a multi-color picker with svelte, maybe to let the user choose a foreground color and a background color. My data model that looks like this:\n\n```\n{\n foreground: {\n r: 100,g:100,b:100\n },\n background: {\n r: 200,g:200,b:200\n }\n};\n```\n\nSo my app.js is\n\n```\nimport AppUI from './App.html';\nimport { Store } from 'svelte/store.js';\n\nconst defaultData = {\n foreground: {\n r: 100,g:100,b:100\n },\n background: {\n r: 200,g:200,b:200\n }\n};\n\nconst store = new Store(defaultData);\n\nwindow.store = store; // useful for debugging!\n\nstore.onchange(() => console.log('something changed'));\n\nvar app = new AppUI({\n target: document.querySelector( '#main' ),\n store\n});\n\nexport default app;\n```\n\nThen I can build an `RGBSelector` component to reuse:\n\n```\n{{data.r}}\n {{data.g}}\n {{data.b}}\n```\n\nAnd my `App.html` is pretty simple:\n\n```\nforeground:\n\nbackground:\n\n import RGBSelector from './RGBSelector.html';\n\n export default {\n components: {\n RGBSelector\n }\n };\n\n```\n\nThis seems to work, mostly. The two-way binding in the range inputs is working (the labels update), and the store is even being updated (verified by inspecting `store._state` in the console). So I believe the `bind` keywords in the `RGBSelector` are passing the change up to where they're declared in the `App`, which in turn is `bind`ing them to the store.\n\nTrouble is, the `store.onchange` handler is not firing. Can anyone see what I'm doing wrong?\n\nFull example: https://glitch.com/edit/#!/nonstop-hourglass\n\n========================================\n\nCode:\n```text\n{\n foreground: {\n r: 100,g:100,b:100\n },\n background: {\n r: 200,g:200,b:200\n }\n};\n```\n\n```text\nimport AppUI from './App.html';\nimport { Store } from 'svelte/store.js';\n\nconst defaultData = {\n foreground: {\n r: 100,g:100,b:100\n },\n background: {\n r: 200,g:200,b:200\n }\n};\n\nconst store = new Store(defaultData);\n\nwindow.store = store; // useful for debugging!\n\nstore.onchange(() => console.log('something changed'));\n\nvar app = new AppUI({\n target: document.querySelector( '#main' ),\n store\n});\n\nexport default app;\n```\n\n```text\n<input type=\"range\" min=0 max=255 step=1 bind:value=data.r/>{{data.r}}\n <input type=\"range\" min=0 max=255 step=1 bind:value=data.g/>{{data.g}}\n <input type=\"range\" min=0 max=255 step=1 bind:value=data.b/>{{data.b}}\n```\n\n```text\nforeground:\n<RGBSelector bind:data=$foreground/>\n\nbackground:\n<RGBSelector bind:data=$background/>\n\n<script>\n import RGBSelector from './RGBSelector.html';\n\n export default {\n components: {\n RGBSelector\n }\n };\n</script>\n```\n\n```text\nRGBSelector\n```\n\n```text\nApp.html\n```\n\n```text\nstore._state\n```\n\n```text\nbind\n```\n\n```text\nRGBSelector\n```\n\n```text\nApp\n```\n\n```text\nbind\n```\n\n```text\nstore.onchange\n```\n\n```html\nforeground: <RGBSelector bind:data=foreground/>\nbackground: <RGBSelector bind:data=background/>\ntext: <Textinput bind:value=text/>\n\n<script>\n import RGBSelector from './RGBSelector.html';\n import Textinput from './Textinput.html';\n\n export default {\n components: {\n RGBSelector, Textinput\n },\n\n oncreate() {\n this.observe('foreground', foreground => {\n this.store.set({ foreground });\n });\n\n this.observe('background', background => {\n this.store.set({ background });\n });\n\n this.observe('text', text => {\n this.store.set({ text });\n });\n }\n };\n</script>\n```\n\n```js\nvar app = new App({\n target: document.body,\n data: defaultData,\n store\n});\n```\n\n```js\n// inside `oncreate` — would also need to do this\n// for `background` and `text`\nlet foregroundUpdating = false;\n\nthis.observe('foreground', foreground => {\n if (foregroundUpdating) return;\n foregroundUpdating = true;\n this.store.set({ foreground });\n foregroundUpdating = false;\n});\n\nthis.store.observe('foreground', foreground => {\n if (foregroundUpdating) return;\n foregroundUpdating = true;\n this.set({ foreground });\n foregroundUpdating = false;\n});\n```\n\n```text\nstore\n```\n\n```text\nbind:data=$foreground\n```\n\n```text\n$foreground\n```\n\n```text\n<App>\n```\n\n```text\nforeground\n```\n\n========================================\n\nComments:\n- Glad to know it's not just me :). The confusing thing about that theory, though, is that the store *is* updated when you slide the range elements, so I suspect what's going on is a bit subtler. Anyway thanks for digging into it, I'll keep an eye on the github issue.","metadata":{"transformedAt":"2026-08-18T18:33:40.686Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":258,"estimatedTokens":1130}}343{"id":"stack-51803148","source":"stackoverflow","questionId":51803148,"title":"Packaging imported javascript into svelte component using rollup","tags":["rollupjs","svelte","svelte-component"],"text":"Title: Packaging imported javascript into svelte component using rollup\nTags: rollupjs, svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nIn my code, I want to import an external javascript file that is common across multiple components. When rollup builds the component, however, it has trouble resolving the imported dependency so it never gets included in the output package. Note, I'm trying to build a svelte component (as opposed to a svelte app) although I'm not sure that makes a difference. Here is my rollup.config.js:\n\n```\nimport svelte from 'rollup-plugin-svelte';\nimport pkg from './package.json';\n\nconst name = pkg.name\n .replace(/^(@\\S+\\/)?(svelte-)?(\\S+)/, '$3')\n .replace(/^\\w/, m => m.toUpperCase())\n .replace(/-\\w/g, m => m[1].toUpperCase());\n\nexport default {\n input: 'src/Radar.html',\n output: [\n { sourcemap: true, file: pkg.module, 'format': 'es' },\n { sourcemap: true, file: pkg.main, 'format': 'umd', name }\n ],\n plugins: [\n svelte({\n cascade: false,\n store: true\n })\n ]\n};\n```\n\n========================================\n\nCode:\n```text\nimport svelte from 'rollup-plugin-svelte';\nimport pkg from './package.json';\n\nconst name = pkg.name\n .replace(/^(@\\S+\\/)?(svelte-)?(\\S+)/, '$3')\n .replace(/^\\w/, m => m.toUpperCase())\n .replace(/-\\w/g, m => m[1].toUpperCase());\n\nexport default {\n input: 'src/Radar.html',\n output: [\n { sourcemap: true, file: pkg.module, 'format': 'es' },\n { sourcemap: true, file: pkg.main, 'format': 'umd', name }\n ],\n plugins: [\n svelte({\n cascade: false,\n store: true\n })\n ]\n};\n```\n\n```js\nimport svelte from 'rollup-plugin-svelte';\nimport resolve from '@rollup/plugin-node-resolve';\nimport pkg from './package.json';\n\nconst name = pkg.name\n .replace(/^(@\\S+\\/)?(svelte-)?(\\S+)/, '$3')\n .replace(/^\\w/, m => m.toUpperCase())\n .replace(/-\\w/g, m => m[1].toUpperCase());\n\nexport default {\n input: 'src/Radar.html',\n output: [\n { sourcemap: true, file: pkg.module, 'format': 'es' },\n { sourcemap: true, file: pkg.main, 'format': 'umd', name }\n ],\n plugins: [\n svelte({\n cascade: false,\n store: true\n }),\n resolve()\n ]\n};\n```\n\n```text\nRollup\n```\n\n```text\nRadar.html\n```\n\n```text\nRadar.svelte\n```\n\n========================================\n\nComments:\n- What does the import declaration inside `src/Radar.html` look like? If it's importing from `node_modules` then you will need to use rollup-plugin-node-resolve (and possibly rollup-plugin-commonjs)\n- It's not importing from node_modules but that's good info for the future. I've tried literally every form I can think of from 3 different forms of ES6 `import` and several forms of `require()`. I put them just inside the script tag.\n- can you post the whole thing as a gist?\n- @LarryMaccherone I think this question should be closed. It is more than 1 year old, is specific to your setup at the time, and it misses the relevant information to be solved by someone here (your actual code & error message). If your still interested in solving this, please add the missing info. If you have solved it yourself, maybe post the solution for others to see. If you're still interested in answers about packaging of Svelte libs in general, I think you should ask another question about that and not mention this project-specific problem that makes it unanswerable.\n- I'm voting to close this question as off-topic because it's too old","metadata":{"transformedAt":"2026-08-18T18:33:40.686Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":104,"estimatedTokens":872}}344{"id":"stack-75896304","source":"stackoverflow","questionId":75896304,"title":"Add class to svelte component","tags":["svelte"],"text":"Title: Add class to svelte component\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI created two components:\n\n**1. btn.svelte**\n\n```\n\n```\n\n**2. btnHold.svelte**\n\n```\n\n import Btn from './btn.svelte';\n\n```\n\nI'm trying to add a new class `btn--hold` to `btn.svelte`\n\n```\n\n```\n\nI get an error on `class`.\n\nBasically I would like in the end to have:\n\n```\n\n```\n\nHow can I add a class to an imported component?\n\n========================================\n\nTop Answer:\nIn the `btn.svelte` component you can do:\n\n```\n\n```\n\n- The `$$restProps` variable is an object of attributes which were passed to the component, but not explitly declared as props via the `export let` keyword.\n\n- I used the nullish coalescing operator `??`, because if you don't pass the `class` attribute to the component, the result will be `Btn undefined`.\n\nNow, in the `btnHold.svelte` component you simply do:\n\n```\n\n```\n\nWorking REPL here: https://svelte.dev/repl/c2b6625ed73144eeb6bebce6ea4a4d82?version=3.58.0\n\n========================================\n\nCode:\n```text\n<button class=\"btn\" />\n```\n\n```text\n<script>\n import Btn from './btn.svelte';\n</script>\n```\n\n```text\n<Btn class=\"{btn} btn--hold\" />\n```\n\n```text\n<button class=\"btn btn--hold\" />\n```\n\n```text\nbtn--hold\n```\n\n```text\nbtn.svelte\n```\n\n```text\nclass\n```\n\n```html\n<script>\n // Svelte 5\n const { class: className } = $props();\n\n // Svelte 3/4\n let className = '';\n export { className as class };\n</script>\n\n<button class=\"btn {className}\" ...\n```\n\n```html\n<Btn class=\"btn--hold\" ...\n```\n\n```text\nclass\n```\n\n```text\nbtn\n```\n\n```text\n<script>\n export let className;\n</script>\n\n<button class=\"btn {className}\" />\n```\n\n```text\n<script>\n import Btn from './btn.svelte';\n</script>\n\n<Btn class=\"btn--hold\" />\n```\n\n```text\nclassName\n```\n\n```html\n<button class={ 'Btn ' + ($$restProps.class ?? '') } />\n```\n\n```html\n<Btn class=\"btn--hold\" />\n```\n\n```text\nbtn.svelte\n```\n\n```text\n$$restProps\n```\n\n```text\nexport let\n```\n\n```text\n??\n```\n\n```text\nclass\n```\n\n```text\nBtn undefined\n```\n\n```text\nbtnHold.svelte\n```\n\n```html\n<button class={$$props.class}>Custom Button</button>\n```\n\n```html\n<script lang=\"ts\">\n import CustomButton from \"./CustomButton.svelte\";\n</script>\n\n<CustomButton class=\"myStyle\"/>\n```\n\n========================================\n\nComments:\n- As H.B. pointed out in a previous answer, 'class' a reserved keyword in Javascript so Svelte complier is going to give you an error if you try this. You'll need to use 'className' or some other appropriate identifier for your use case.\n- Thank you very much, it's working perfectly. Let me ask you one more thing, how can I add some text into that component like: text ``\n- Just define another property and interpolate it or use a slot. Have you done the tutorial?\n- Are there any gotchas with this approach?\n- this is a much more sveltey approach","metadata":{"transformedAt":"2026-08-18T18:33:40.686Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":192,"estimatedTokens":713}}345{"id":"stack-60416026","source":"stackoverflow","questionId":60416026,"title":"Reactivity of property changes of an object inside of an array","tags":["javascript","svelte"],"text":"Title: Reactivity of property changes of an object inside of an array\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nWhat's the proper way to trigger reactivity in svelte when I am updating a property of an object inside of an array that's then passed as a Component's prop?\n\n```\nlet items = [{\n id: 1,\n name: 'first'\n}, {\n id: 2,\n name: 'second'\n}];\n\nfunction findItem(id) {\n return items.find(item => item.id == id);\n}\n\nfunction modifyItem(id, changedProps) {\n let item = findItem(id);\n if(item) {\n Object.assign(item, changedProps);\n items = [...items]; // this does nothing\n console.log(items); // correctly displays the modified items array\n }\n}\n\n// ...\n\n```\n\nSo I am passing down my `modifyItem` function. A child component then calls it and wants to update the `items` array. That works just fine, but the reactivity is not triggered (I assume because svelte doesn't recognize that an object in the array has been modified) so `MyList` is never re-rendered.\n\nWhat's the \"proper\"/\"correct\" way of doing this? It seems a bit inefficient to `.map` the whole array just to create a new instance of the object and push it in. Any other way? Thanks a lot!\n\n========================================\n\nCode:\n```text\nlet items = [{\n id: 1,\n name: 'first'\n}, {\n id: 2,\n name: 'second'\n}];\n\nfunction findItem(id) {\n return items.find(item => item.id == id);\n}\n\nfunction modifyItem(id, changedProps) {\n let item = findItem(id);\n if(item) {\n Object.assign(item, changedProps);\n items = [...items]; // this does nothing\n console.log(items); // correctly displays the modified items array\n }\n}\n\n// ...\n\n<MyList {items}/>\n```\n\n```text\nmodifyItem\n```\n\n```text\nitems\n```\n\n```text\nMyList\n```\n\n```text\n.map\n```\n\n```text\n<script>\n import DisplayCounter from \"./DisplayCounter.svelte\";\n let items = [{text: 'hello', count: 0}];\n\n function incrementCounter() {\n items[0].count++;\n items = [...items];\n }\n</script>\n\n<button on:click={incrementCounter}>Click me</button>\n<DisplayCounter {items} />\n```\n\n```text\n<script>\n export let items = []\n</script>\n\n<div>{items[0].count}</div>\n```\n\n========================================\n\nComments:\n- You are right, it works. I found my problem: I was passing an object as prop to the \"ListItem\" and then destructing it directly in that component, which was not reactive. That's why I never saw the updates.\n- Glad you found it and understood the reason. Happy svelting!\n- @Fygo would you be able to expand on your solution here? I'm encountering something similar with an object where I am reassigning it (content = {...content}) but the view is not updating it\n- @Pete I am sorry, I actually don't remember anymore the specifics. But I think it was simply this: `export let obj; let notReactive = obj.date; $: reactive = obj.date;` (this would apply to destructuring as well)","metadata":{"transformedAt":"2026-08-18T18:33:40.686Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":113,"estimatedTokens":715}}346{"id":"stack-59351139","source":"stackoverflow","questionId":59351139,"title":"Is it possible to pass a Svelte store as a property on a component?","tags":["svelte"],"text":"Title: Is it possible to pass a Svelte store as a property on a component?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI’ve got a simple REPL example for a simple list-detail editor. It’s made up of three components:\n\n- `Annotation` is the detail\n\n- `Annotations` loops through the data and creates `Annotation` instances\n\n- `App` is the top-level that creates the `Annotations`\n\nI’ve figured out how to wire up a custom Svelte store to manage the `Array` of instance data for the `Annotations`. I can use this by importing the store directly into the `Annotations` component and calling it without any props from the top-level `App` component. However, I’d like to be able to pass the store in as a property on the `Annotations` component from the `App` parent, i.e. ``, not ``. \n\nIs this possible? I would think that injecting the store from a parent component would be more flexible/testable than importing it from the component itself. Have I done too much dependency injection with Spring in Java and I’m thinking about the Svelte model incorrectly?\n\n========================================\n\nTop Answer:\nSeems to work... \n\nIn **App.svelte**\n\nchange:\n\n`` \n\nIn **Annotations.svelte**\n\nRemove:\n\n`import { annotations } from './state.js';`\n\nAdd:\n\n`export let annotations = [];` \n\nREPL\n\nIs that what you were looking for?\n\n========================================\n\nCode:\n```text\nAnnotation\n```\n\n```text\nAnnotations\n```\n\n```text\nAnnotation\n```\n\n```text\nApp\n```\n\n```text\nAnnotations\n```\n\n```text\nArray\n```\n\n```text\nAnnotations\n```\n\n```text\nAnnotations\n```\n\n```text\nApp\n```\n\n```text\nAnnotations\n```\n\n```text\nApp\n```\n\n```text\n<Annotations items={store}/>\n```\n\n```text\n<Annotations/>\n```\n\n```html\n<Annotations items={annotations} />\n```\n\n```js\n<script>\n export let items\n ...\n items.addStuff(...);\n</script>\n\n{#each $items as annotation}\n ...\n{/each}\n```\n\n```html\n<script>\n export let Cmp // yes, can change at runtime, reactive!\n</script>\n\n<svelte:component this={Cmp} />\n\n<!-- or -->\n\n{#if Cmp}\n <Cmp />\n{/if}\n```\n\n```text\nApp.svelte\n```\n\n```text\nAnnotations.svelte\n```\n\n```text\nitems\n```\n\n```text\nannotations\n```\n\n```text\n<Annotations\n```\n\n```text\n<Annotations annotations={annotations}/>\n```\n\n```text\nimport { annotations } from './state.js';\n```\n\n```text\nexport let annotations = [];\n```\n\n========================================\n\nComments:\n- Yes, thank you. I must have been doing something dumb and my wiring wasn’t working. However, now svelte.dev/repl/5638f5575cee4e42935848b22e0837e9?version=3.1‌​6.4 I can’t get the edit method in the store to work. store.edit is being called, it just doesn’t seem to automatically propagate, even though I’m calling the underlying writable.update. Any ideas?\n- Argh. Never mind. It has to do with destructuring assignment…again. `let { id, text, user, timestamp}` is not the same as `let id, text, user, timestamp; $: ({id, text, user, timestamp} = details);`\n- `export let items = []` is wrong IMO. `item` is getting a store object from the prop but you are setting an empty array as a default value for it. Two different types dear! Had this been typescript, the complier would have started banging on you.\n- Indeed, the typing was not correct. I fixed the example.","metadata":{"transformedAt":"2026-08-18T18:33:40.686Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":166,"estimatedTokens":808}}347{"id":"stack-42737693","source":"stackoverflow","questionId":42737693,"title":"Is it possible in Svelte to have #each loops with two-way binding to nested object values?","tags":["javascript","object","each","svelte"],"text":"Title: Is it possible in Svelte to have #each loops with two-way binding to nested object values?\nTags: javascript, object, each, svelte\nSource: Stack Overflow\n\nQuestion:\nThe following Svelte code works fine:\n\n```\n\nHello {{options.name.value || 'stranger'}}!\n\n```\n\nUsing this JSON:\n\n```\n{\n \"options\": {\n \"name\": {\n \"value\": \"\",\n \"placeholder\": \"enter your name\"\n }\n }\n}\n```\n\nYou can see it in action. But what if we want to loop over `options` with an `#each` array...is that possible?\n\nIt *almost* works if we do everything except the bind:\n\n```\n{{#each Object.keys(options) as option}}\n\nHello {{options[option].value || 'stranger'}}!\n\n{{/each}}\n```\n\nYou can see that the placeholder is correct, and the two-way binding works correctly. But the code is not correct yet, because `options.name` is hard-coded in for the bind, instead of using the loop value. If we try to fix that, putting `bind:value='options[option].value'`, we get a syntax error, `Expected '`.\n\nSo, if it's possible to two-way bind within a loop using the loop value, what's the correct syntax?\n\n========================================\n\nTop Answer:\n```\n\n let options = {\n name: {\n value: '',\n placeholder: 'enter your name'\n },\n };\n \n $: console.table(options)\n\n{#each Object.entries(options) as [key, option]}\n \n{/each}\n```\n\nhttps://svelte.dev/repl/a77dd18da023469da962d873e6fb391f?version=3.47.0\n\n========================================\n\nCode:\n```text\n<input bind:value='options.name.value' placeholder='{{options.name.placeholder}}'>\n<p>Hello {{options.name.value || 'stranger'}}!</p>\n```\n\n```text\n{\n \"options\": {\n \"name\": {\n \"value\": \"\",\n \"placeholder\": \"enter your name\"\n }\n }\n}\n```\n\n```text\n{{#each Object.keys(options) as option}}\n<input bind:value='options.name.value' placeholder='{{options[option].placeholder}}'>\n<p>Hello {{options[option].value || 'stranger'}}!</p>\n{{/each}}\n```\n\n```text\noptions\n```\n\n```text\n#each\n```\n\n```text\noptions.name\n```\n\n```text\nbind:value='options[option].value'\n```\n\n```text\nExpected '\n```\n\n```js\n{#each options as option}\n <input bind:value={option.value} placeholder={option.placeholder}>\n{/each}\n```\n\n```js\n{\n \"options\": [\n {\n \"id\": \"name\",\n \"value\": \"\",\n \"placeholder\": \"enter your name\"\n },\n {\n \"id\": \"email\",\n \"value\": \"\",\n \"placeholder\": \"enter your email\"\n }\n ]\n}\n```\n\n```js\n{#each Object.keys(options) as option}\n <input bind:value={option}>\n{/each}\n```\n\n```html\n<script>\n let options = {\n name: {\n value: '',\n placeholder: 'enter your name'\n }\n };\n\n function updateValue(option, value) {\n options[option].value = value;\n }\n</script>\n\n{#each Object.keys(options) as option}\n <input\n on:input=\"{() => updateValue(option, e.target.value)}\"\n placeholder={options[option].placeholder}\n >\n{/each}\n```\n\n```text\neach\n```\n\n```text\nObject.keys(options)\n```\n\n```text\nfoo\n```\n\n```text\nfoo.bar\n```\n\n```text\noptions[option].value\n```\n\n```text\neach\n```\n\n```text\noptions[option].name\n```\n\n```text\noption\n```\n\n```text\n<script>\n let options = {\n name: {\n value: '',\n placeholder: 'enter your name'\n },\n };\n \n $: console.table(options)\n</script>\n\n{#each Object.entries(options) as [key, option]}\n <input\n bind:value={option.value}\n placeholder={option.placeholder}\n >\n{/each}\n```\n\n========================================\n\nComments:\n- Not using two-way binding would seem to preclude, e.g., having a checkbox with a `` in the each loop whose `on:click` also toggles the input. You also can't put the logic within the each loop, since you can't use `refs` in each loops. I guess for this one then has to use the array and just get used to using `Array.find()` in the code rather than hash key lookups. :)\n- It also seems that using `component.observe` on a nested property doesn't fire anything when the property gets set, so you can't add the other half of the two-way yourself.\n- You can do `{{#each things as thing, i}}` and pass `i` to event handlers, which can work around the lack of `ref` inside `each` blocks (on which see here). `component.observe` only works with top-level properties (issue here)\n- Hi @RichHarris is this still working on newest version of svelte? Is there a different syntax?","metadata":{"transformedAt":"2026-08-18T18:33:40.686Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":219,"estimatedTokens":1065}}348{"id":"stack-74020899","source":"stackoverflow","questionId":74020899,"title":"Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)","tags":["typescript","svelte","rollupjs"],"text":"Title: Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)\nTags: typescript, svelte, rollupjs\nSource: Stack Overflow\n\nQuestion:\nI have a custom dependency which is a `.ts` file. It contains `enums`, `interfaces` and `consts`, I'm importing like so:\n\n```\nimport type { inteface1, interface2} from \"common\";\n```\n\nThis works completely fine and the compiler doesn't give me any errors.\n\nIf I try to do an import from the same dependency like so:\n\n```\nimport { paths } from \"common\";\n```\n\nI get an error saying:\n\n[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)\nnode_modules/common/types.ts (1:7)\n\nBoth of these imports are from the same file but for some reason trying to import a `const` or `enum` doesn't work and importing an `interface` works. The only difference seems to be that when importing `interface`, there's the `type` keyword.\n\nrollup.config.js\n\n```\ntypescript({\n sourceMap: !production,\n rootDir: \"./src\",\n exclude: ['node_modules/**']\n }),\n```\n\ntsconfig.json\n\n```\n{\n \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n \n \"include\": [\"src/**/*\"],\n \"exclude\": [\"node_modules/*\", \"__sapper__/*\", \"public/*\"],\n }\n```\n\nI'm running with the command\n\n```\nrollup -c -w\n```\n\nversions:\n\n```\n\"@rollup/plugin-typescript\": \"^9.0.0\",\n```\n\nThe file I'm importing (`types.ts`):\n\n```\nexport interface interface1{\n field1: string\n field2: string\n}\nexport interface interface2{\n status: \"OK\" | \"NOK\",\n field3: string;\n}\n\nexport const paths = {\n path1: \"/path1\"\n}\n```\n\nHere's the package.json from the dependency\n\n```\n{\n \"name\": \"common\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"types.ts\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"author\": \"\",\n \"license\": \"ISC\",\n \"devDependencies\": {\n \"@types/node\": \"^18.8.3\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nMake insure you have correct extension of file. In my case, I am not give my extension to my js file that's why error is occure.\n\n========================================\n\nCode:\n```text\nimport type { inteface1, interface2} from \"common\";\n```\n\n```text\nimport { paths } from \"common\";\n```\n\n```text\ntypescript({\n sourceMap: !production,\n rootDir: \"./src\",\n exclude: ['node_modules/**']\n }),\n```\n\n```text\n{\n \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n \n \"include\": [\"src/**/*\"],\n \"exclude\": [\"node_modules/*\", \"__sapper__/*\", \"public/*\"],\n }\n```\n\n```text\nrollup -c -w\n```\n\n```text\n\"@rollup/plugin-typescript\": \"^9.0.0\",\n```\n\n```text\nexport interface interface1{\n field1: string\n field2: string\n}\nexport interface interface2{\n status: \"OK\" | \"NOK\",\n field3: string;\n}\n\n\nexport const paths = {\n path1: \"/path1\"\n}\n```\n\n```text\n{\n \"name\": \"common\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"types.ts\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"author\": \"\",\n \"license\": \"ISC\",\n \"devDependencies\": {\n \"@types/node\": \"^18.8.3\"\n }\n}\n```\n\n```text\n.ts\n```\n\n```text\nenums\n```\n\n```text\ninterfaces\n```\n\n```text\nconsts\n```\n\n```text\nconst\n```\n\n```text\nenum\n```\n\n```text\ninterface\n```\n\n```text\ninterface\n```\n\n```text\ntype\n```\n\n```text\ntypes.ts\n```\n\n```text\nexport {interface1} from \"./types\";\n```\n\n```text\n{\n \"compilerOptions\": {\n \"strict\": true,\n \"module\": \"ES6\",\n \"target\": \"ES6\",\n \"lib\": [\"ES2020\", \"DOM\", \"DOM.Iterable\"],\n \"declaration\": true,\n \"outDir\": \"./dist/lib/es6\",\n \"moduleResolution\": \"node\"\n },\n \"include\": [\"src/**/*\"]\n }\n```\n\n```text\n\"main\": \"./dist/lib/es6/index.js\",\n \"types\": \"./dist/lib/es6/index.d.ts\",\n```\n\n```text\n(!) `this` has been rewritten to `undefined`\n```\n\n```text\nindex.ts\n```\n\n```text\ntsconfig.json\n```\n\n```text\nnpx tsc\n```\n\n```text\n/dist/lib/es6\n```\n\n========================================\n\nComments:\n- Type imports are erased by typescript, so the compiler never sees it—hence no error is triggered. I suppose `common` is a .ts file?\n- @Terry Yes, it is a .ts file. Only contains bunch of interfaces and has no dependencies.\n- If you remove *Error: * from the post title, and use what's left to search this site, you'll find that this question has been asked and answered here many times before. One of those previous posts should be helpful in solving the problem.\n- Except I already did and tried every solution and they didn't work. Only one I didn't try is one where the issue was solved but they didn't tell how it was solved. Linking the one I could not try, also feel a bit lost with this current situation. stackoverflow.com/questions/63435078/…\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review","metadata":{"transformedAt":"2026-08-18T18:33:40.686Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":262,"estimatedTokens":1282}}349{"id":"stack-74095502","source":"stackoverflow","questionId":74095502,"title":"svelte invalidate not working with custom identifier","tags":["svelte","sveltekit"],"text":"Title: svelte invalidate not working with custom identifier\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nIn svelte/SvelteKit I have a load that is *not a fetch*. The goal is to reload this \"non-fetch\" load with a button in UI.\n\nAccording to Svelte documentation for depends, I should be able to use `invalidate` with a `custom identifier`, and \"register\" the custom identifier in the load?\n\nSomething like this:\n\n```\nexport const load: PageLoad = function( { depends }){\n depends(\n 'my:customurl'\n );\n...\n```\n\nThe `custom identifier` needs to be formated properly, and `beforecolon:aftercolon` should be legal format.\n\nI am unable to get any reaction in the load when calling `invalidate` or `invalidateAll` from `+page.svelte`.\nReproducable code (with hardcoded dummy data return) goes like this:\n\n`+page.ts:`\n\n```\nimport type { PageLoad } from './$types';\n\n export const load: PageLoad = function( { depends }){\n depends(\n 'my:customurl'\n );\n console.log(\"load is triggered...\")\n const someJson = JSON.parse(`{\"someData\":\"${new Date().toISOString()}\"}`);\n return {\n theData : someJson\n }\n}\n```\n\n`+page.svelte`:\n\n```\n\n import type { PageData } from \"./$types\";\n import { invalidate } from '$app/navigation';\n import { invalidateAll } from '$app/navigation';\n\n export let data: PageData;\n $: ({theData} = data)\n \n function reload(){\n invalidate('my:customurl');\n };\n function reloadAll(){\n invalidateAll();\n };\n\n \n \n \n\n### Actions\n\n Reload\n Reload All\n \n \n \n\n### Data\n\n {theData.someData}\n \n\n```\n\nI have also done the same with a `+page.server.ts`, but the result is the same.\n\nI am using the same custom identifier `my:customurl` both in `+page.svelte` and `+page.ts` (or alt `+page.server.ts`).\n\nI can tell the `invalidate` or `invalidateAll` is not working because the date is not changing when the buttons are clicked (The date is changing on browser page reload).\n\nWhat do I need to do to get invalidate working for a non-fetch load?\n\n========================================\n\nCode:\n```js\nexport const load: PageLoad = function( { depends }){\n depends(\n 'my:customurl'\n );\n...\n```\n\n```js\nimport type { PageLoad } from './$types';\n\n export const load: PageLoad = function( { depends }){\n depends(\n 'my:customurl'\n );\n console.log(\"load is triggered...\")\n const someJson = JSON.parse(`{\"someData\":\"${new Date().toISOString()}\"}`);\n return {\n theData : someJson\n }\n}\n```\n\n```text\n<script lang=\"ts\">\n import type { PageData } from \"./$types\";\n import { invalidate } from '$app/navigation';\n import { invalidateAll } from '$app/navigation';\n\n export let data: PageData;\n $: ({theData} = data)\n \n function reload(){\n invalidate('my:customurl');\n };\n function reloadAll(){\n invalidateAll();\n };\n\n</script>\n\n<div> \n <section>\n <h3>Actions</h3>\n <button on:click={reload}>Reload</button>\n <button on:click={reloadAll}>Reload All</button>\n </section>\n <section>\n <h3>Data</h3>\n <div>{theData.someData}</div>\n </section>\n</div>\n```\n\n```text\ninvalidate\n```\n\n```text\ncustom identifier\n```\n\n```text\ncustom identifier\n```\n\n```text\nbeforecolon:aftercolon\n```\n\n```text\ninvalidate\n```\n\n```text\ninvalidateAll\n```\n\n```text\n+page.svelte\n```\n\n```text\n+page.ts:\n```\n\n```text\n+page.svelte\n```\n\n```text\n+page.server.ts\n```\n\n```text\nmy:customurl\n```\n\n```text\n+page.svelte\n```\n\n```text\n+page.ts\n```\n\n```text\n+page.server.ts\n```\n\n```text\ninvalidate\n```\n\n```text\ninvalidateAll\n```\n\n```js\nconst someJson = JSON.parse(`{\"someData\":\"${new Date().toISOString()}\"}`);\n```\n\n```text\ninvalidate\n```\n\n```text\ninvalidateAll\n```\n\n```text\nconsole.log(\"load is triggered...\")\n```\n\n========================================\n\nComments:\n- I changed my code as you suggest so that data actually changes. The buttons triggering invalidate and invalidateAll is still not having an effect. Data unchanged. If I reload the browser page, the data changes.\n- I have just taken the code as is, if it does not work on your end, something outside the given code might be interfering. I also tried to upgrade all packages to the latest version to make sure the problem is not some regression, it still worked after that.\n- I adjusted my question to incorporate the smarter \"new Date\" trick to get data actually changing. Makes it safer and easier to observe :)\n- Ok. Useful to know the code should work, and works elswhere... I will investigate further on my end.\n- Ok, so I figured something out: when I had the two code files in a subfolder of routes, my code sample does not work. When I have them in root of routes it does work. So why does it not work in a sub page?\n- I have them in a folder `src/routes/depends` and that works the same as having them directly in `src/routes`.\n- So I moved them back in subfolder, the same as it was before and not working, and now it works there also. I have no idea why. Anyway, all good I guess. Thanks!\n- Maybe some dev server desynchronization issue.\n- Probably something like that. I physically moved the files, so pretty sure no code was changed.","metadata":{"transformedAt":"2026-08-18T18:33:40.686Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":235,"estimatedTokens":1269}}350{"id":"stack-78472639","source":"stackoverflow","questionId":78472639,"title":"Svelte 5: Passing state and derived values from children to parent (runes mode without stores)","tags":["components","svelte","svelte-5"],"text":"Title: Svelte 5: Passing state and derived values from children to parent (runes mode without stores)\nTags: components, svelte, svelte-5\nSource: Stack Overflow\n\nQuestion:\nI have a parent component with multiple draggable Item-components which will be created dynamically in the final app. Inside each Item I calculate the current position as well as a derived offset value. Each time, any Item is dragged I want its position/offset to be shared reactively with the parent component.\n\nIn Svelte 4 with stores this was fairly easy. However, I struggle implementing this in Svelte 5 with runes. Context-API somehow isn't an option, since I'd like to define pos/offset inside the Item-component where they belong... shouldn't I?\n\nThe current code has two issues:\n\n- (1) While sending the position (state) to the parent via bound props, this does not work for the offset (derived). Why?\n\n- (2) As soon as the second item-component is mounted, the connection between the first item and the parent is lost. Why?\n\n### Update 2024-05-14\n\nHere is a reduced verison of my code (REPL):\n\n**App.svelte**\n\n```\n\n import Item from './Item.svelte';\n\n let CURRENT = $state({pos: {x:99, y:99}, offset: 99});\n\n### Last dragged item: ({CURRENT.pos.x} / {CURRENT.pos.y}) Offset: {CURRENT.offset}\n\n```\n\n**Item.svelte**\n\n```\n\n import interact from 'interactjs';\n\n let { CURRENT = $bindable(), itemName } = $props();\n let item;\n \n let pos = $state({x:0, y:0});\n let offset = $derived(Math.floor(Math.sqrt( Math.pow(pos.x,2) + Math.pow(pos.y,2) )));\n\n CURRENT.pos = pos;\n CURRENT.offset = offset;\n\n const handleDraggable = (node) => {\n interact(node).draggable({ \n onmove: (ev) => {\n let el = ev.target;\n \n let x = (parseFloat(el.getAttribute('data-x')) || 0) + ev.dx;\n let y = (parseFloat(el.getAttribute('data-y')) || 0) + ev.dy;\n \n el.style.webkitTransform = el.style.transform = `translate(${x}px,${y}px)`;\n el.setAttribute('data-x', x);\n el.setAttribute('data-y', y);\n pos.x = x;\n pos.y = y;\n },\n });\n }\n\n \n {itemName} ({pos.x} / {pos.y}) Offset: {offset}\n\n```\n\n========================================\n\nCode:\n```html\n<svelte:options runes=\"{true}\" />\n\n<script>\n import Item from './Item.svelte';\n\n let CURRENT = $state({pos: {x:99, y:99}, offset: 99});\n\n</script>\n\n<h1>Last dragged item: ({CURRENT.pos.x} / {CURRENT.pos.y}) Offset: {CURRENT.offset}</h1>\n\n<Item bind:CURRENT={CURRENT} itemName='ONE' />\n<Item bind:CURRENT={CURRENT} itemName='TWO' />\n```\n\n```html\n<svelte:options runes=\"{true}\" />\n\n<script>\n import interact from 'interactjs';\n\n let { CURRENT = $bindable(), itemName } = $props();\n let item;\n \n let pos = $state({x:0, y:0});\n let offset = $derived(Math.floor(Math.sqrt( Math.pow(pos.x,2) + Math.pow(pos.y,2) )));\n\n CURRENT.pos = pos;\n CURRENT.offset = offset;\n\n const handleDraggable = (node) => {\n interact(node).draggable({ \n onmove: (ev) => {\n let el = ev.target;\n \n let x = (parseFloat(el.getAttribute('data-x')) || 0) + ev.dx;\n let y = (parseFloat(el.getAttribute('data-y')) || 0) + ev.dy;\n \n el.style.webkitTransform = el.style.transform = `translate(${x}px,${y}px)`;\n el.setAttribute('data-x', x);\n el.setAttribute('data-y', y);\n pos.x = x;\n pos.y = y;\n },\n });\n }\n</script>\n\n\n<div id=\"draggable\" bind:this={item} use:handleDraggable> \n <p>{itemName} ({pos.x} / {pos.y}) Offset: {offset}</p>\n</div>\n```\n\n```html\n<svelte:options runes=\"{true}\" />\n\n<script>\n import Item from './Item.svelte';\n \n let CURRENT = $state({pos: {x:99, y:99}, offset: 99});\n let onDragged = (pos, offset) => { \n CURRENT.pos = pos, \n CURRENT.offset = offset\n }\n</script>\n\n<h1>Last dragged item: ({CURRENT.pos.x} / {CURRENT.pos.y}) Offset: {CURRENT.offset}</h1>\n\n<Item itemName='ONE' {onDragged} } />\n<Item itemName='TWO' {onDragged} } />\n```\n\n```html\n<svelte:options runes=\"{true}\" />\n\n<script>\n import interact from 'interactjs';\n\n //let { CURRENT = $bindable(), itemName } = $props();\n let { itemName, onDragged } = $props();\n let item;\n \n let pos = $state({x:0, y:0});\n let offset = $derived(Math.floor(Math.sqrt( Math.pow(pos.x,2) + Math.pow(pos.y,2) )));\n\n const handleDraggable = (node) => {\n interact(node).draggable({ \n onmove: (ev) => {\n let el = ev.target;\n \n let x = (parseFloat(el.getAttribute('data-x')) || 0) + ev.dx;\n let y = (parseFloat(el.getAttribute('data-y')) || 0) + ev.dy;\n \n el.style.webkitTransform = el.style.transform = `translate(${x}px,${y}px)`;\n el.setAttribute('data-x', x);\n el.setAttribute('data-y', y);\n pos.x = x;\n pos.y = y;\n onDragged(pos, offset);\n },\n });\n }\n</script>\n\n\n<div id=\"draggable\" bind:this={item} use:handleDraggable> \n <p>{itemName} ({pos.x} / {pos.y}) Offset: {offset}</p>\n</div>\n\n\n<style>\n #draggable {\n background-color: green;\n width: 220px;\n }\n</style>\n```\n\n========================================\n\nComments:\n- The recommended way to pass info from parent to child is by using props, and from child to parent is by using events (in Svelte 4) and callback props (in Svelte 5). I think using that will solve your problem.\n- Include all relevant code ***in*** the question, remove anything irrelevant first or start from scratch to make the reproduction minimal.\n- I have just updated my question including some reduced code.\n- @PeppeL-G: Thank you! Which part exactly would you pass as a callback prop?\n- A function that receives the new position of the item each time it has been moved, for example: ` { CURRENT.pos = pos } } />`. Then in your child component you need to call the `onDragged()` props and pass it the new position each time it has been dragged a little. You can also include the computed offset if you want.\n- Oh wow, this is such a nice way to solve this problem! Thank you so much for showing me, @PeppeL-G! I'll update the question with a working REPL.\n- @The_Lab, write and accept your own answer to the question instead of writing it in your question :)\n- @PeppeL-G, oh, ok, I can do so. Was not sure how to handle this situation, since it's you who deserves the credits.\n- Thanks for the thought, but no problem ^^","metadata":{"transformedAt":"2026-08-18T18:33:40.686Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":203,"estimatedTokens":1641}}351{"id":"stack-79260991","source":"stackoverflow","questionId":79260991,"title":"How to use a global $derived in Svelte 5?","tags":["svelte","svelte-5"],"text":"Title: How to use a global $derived in Svelte 5?\nTags: svelte, svelte-5\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a global state with Svelte 5 and runes:\n\n```\n// store.svelte.ts\nexport const person = ({\n name: '',\n});\n\nexport const mrName = $derived('Mr. ' + person.name); // I can't make `$derived` to work:\n\n```\nCannot export derived state from a module.\n\n6 | export const mrName = $derived(\"Mr. \" + person.name);\n ^\n7 |\n```\n\nWhat's the correct approach to a global `$derived`?\n\n========================================\n\nCode:\n```js\n// store.svelte.ts\nexport const person = ({\n name: '',\n});\n\nexport const mrName = $derived('Mr. ' + person.name); // <-- problem!\n```\n\n```text\nCannot export derived state from a module.\n\n6 | export const mrName = $derived(\"Mr. \" + person.name);\n ^\n7 |\n```\n\n```text\n$derived\n```\n\n```text\n$derived\n```\n\n```js\n// store.svelte.ts\nexport class Person {\n name = $state('')\n mrName = $derived(\"Mr. \" + this.name)\n}\n```\n\n```js\n// store.svelte.ts\nexport const Person = () => {\n let name = $state('')\n let mrName = $derived(\"Mr. \" + name)\n return {\n get name() { return name },\n get mrName() { return mrName }\n }\n}\n```\n\n========================================\n\nComments:\n- In many cases you don't really need a `$derived`. If you export a function (or use an getter), it will also be reactive, the only difference would be that the value is potentially created multiple times even if the name did not change. Since this is not an expensive operation, it would not matter much.\n- there are so many ways to instantiate that lass person, 1) you can export const person = new Person() instead of the class 2) you can export the class and create its instance inside every component but this obviously ll be a new instance per component so data cannot be shared 3) you can use context, what is the recommended way to use classes\n- also worth noting for people looking this up, the classes themselves are not reactive, only their fields are if declared with $state/$derived","metadata":{"transformedAt":"2026-08-18T18:33:40.686Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":79,"estimatedTokens":520}}352{"id":"stack-72755269","source":"stackoverflow","questionId":72755269,"title":"Set crossOriginIsolated Svelte and SvelteKit","tags":["cors","svelte","sveltekit"],"text":"Title: Set crossOriginIsolated Svelte and SvelteKit\nTags: cors, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm new in Svelte and SvelteKit and I'm getting this error when trying to execute a worker:\n\n```\nUncaught DOMException: Failed to execute 'postMessage' on 'Worker': SharedArrayBuffer transfer requires self.crossOriginIsolated.\n```\n\nI know I need to set the headers (I'm moving from React to Svelte), but how/where do I set the headers?\n\n========================================\n\nTop Answer:\nAs of June 2023, the Svelte-Kit config syntax seems to have changed and Gum Rick's solution doesn't work verbatim.\n\nAs an alternate, the Vite plugin can be defined and configured in `vite.config.js`:\n\n```\n// vite.config.js\n\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vite';\n\n/** @type {import('vite').Plugin} */\nconst viteServerConfig = () => ({\n name: 'add-headers',\n configureServer: (server) => {\n server.middlewares.use((req, res, next) => {\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.setHeader(\"Access-Control-Allow-Methods\", \"GET\");\n res.setHeader(\"Cross-Origin-Opener-Policy\", \"same-origin\");\n res.setHeader(\"Cross-Origin-Embedder-Policy\", \"require-corp\");\n next();\n });\n }\n});\n\nexport default defineConfig({\n plugins: [sveltekit(), viteServerConfig()]\n});\n```\n\n========================================\n\nCode:\n```text\nUncaught DOMException: Failed to execute 'postMessage' on 'Worker': SharedArrayBuffer transfer requires self.crossOriginIsolated.\n```\n\n```text\nimport adapter from '@sveltejs/adapter-auto';\n\n/** @type {import('vite').Plugin} */\nconst viteServerConfig = {\n name: 'log-request-middleware',\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.setHeader(\"Access-Control-Allow-Methods\", \"GET\");\n res.setHeader(\"Cross-Origin-Opener-Policy\", \"same-origin\");\n res.setHeader(\"Cross-Origin-Embedder-Policy\", \"require-corp\");\n next();\n });\n }\n};\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n kit: {\n adapter: adapter(),\n vite: {\n plugins: [viteServerConfig]\n }\n }\n};\n\nexport default config;\n```\n\n```js\n// vite.config.js\n\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vite';\n\n/** @type {import('vite').Plugin} */\nconst viteServerConfig = () => ({\n name: 'add-headers',\n configureServer: (server) => {\n server.middlewares.use((req, res, next) => {\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.setHeader(\"Access-Control-Allow-Methods\", \"GET\");\n res.setHeader(\"Cross-Origin-Opener-Policy\", \"same-origin\");\n res.setHeader(\"Cross-Origin-Embedder-Policy\", \"require-corp\");\n next();\n });\n }\n});\n\nexport default defineConfig({\n plugins: [sveltekit(), viteServerConfig()]\n});\n```\n\n```text\nvite.config.js\n```\n\n========================================\n\nComments:\n- I'm using google one click auth and while this solution seems to not have any error, it causes my google popup to be a white screen\n- @ChenW The policies in the headers might have to be tweaked as per your requirement. This answer is merely about how to set the headers.\n- This doesn't seem to work for me.","metadata":{"transformedAt":"2026-08-18T18:33:40.686Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":117,"estimatedTokens":842}}353{"id":"stack-67272460","source":"stackoverflow","questionId":67272460,"title":"component with DOM elements","tags":["svelte","svelte-3","svelte-component"],"text":"Title: component with DOM elements\nTags: svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\n**Goal**\n\nI'm creating a button component in Svelte that will either render as `` or `` element, depending on whether it's a link or not. Is it possible to use `svelte:component`?\n\nSomething like this:\n\n```\n\n export let href: string = ''\n\n $: component = href ? a : button // where \"a\" and \"button\" are the HTML DOM elements\n\n \n\n```\n\nSo far, I've only seen examples of `svelte:component` rendering custom Svelte components, not DOM elements\n\nhttps://svelte.dev/tutorial/svelte-component\n\nHow to dynamically render components in Svelte?\n\n**Motivation**\n\nIt is possible to use if/else to get the desired results:\n\n```\n\n export let href: string = ''\n\n{# if href}\n \n \n \n{:else}\n \n \n \n{/if}\n```\n\nbut this is not maintainable.\n\n- The entire contents is duplicated. In the simple example above, the contents is just the children. In reality, there are multiple slots for (e.g, prefixes/suffixes), leading to lots of duplicated logic.\n\n- I can see uses for this design pattern in many other components with more than 2 variants (e.g., a `Container` component that can be a `div`, `section`, `article`, `aside`, etc.). More variants results in an even messier code structure.\n\n**React equivalent**\n\nHere's an example React component with the desired functionality.\n\n```\nconst Button = (props) => {\n const Tag = props.href ? 'a' : 'button'\n\n return {contents}\n}\n```\n\n**Solutions I wish to avoid**\n\nThe if/else pattern\n\nSame pattern as above.\n\nCreating a \"children\" component\n\nInstead of duplicating the children multiple times, you could move it into its own component and just import the child into the if/else chain. At least then there won't be duplicated logic, but the props/slots will need to be duplicated.\n\n```\n\n import Children from './children.svelte'\n\n export let href: string = ''\n\n{# if href}\n \n \n \n{:else}\n \n \n \n{/if}\n```\n\nCreate wrapper components\n\nFor every wrapper DOM element, just create a new Svelte component. Then, import those as actual Svelte components and use `svelte:component`\n\n```\n\n```\n\n```\n\n```\n\n```\n\n import A from './dom-a.svelte'\n import Button from './dom-button.svelte'\n\n export let href: string = ''\n\n $: component = href ? A : Button\n\n \n\n```\n\nWhile this is the nicest to use as a developer, there is a performance penalty for having unknown props. Therefore, it's not idea.\n\nI suppose you could specify every single possible prop in the `dom-button.svelte` and `dom-a.svelte` components, but that seems like overkill.\n\n========================================\n\nCode:\n```html\n<script lang='ts'>\n export let href: string = ''\n\n $: component = href ? a : button // where \"a\" and \"button\" are the HTML DOM elements\n</script>\n\n<svelte:component this={component}>\n <slot></slot>\n</svelte:component>\n```\n\n```html\n<script lang='ts'>\n export let href: string = ''\n</script>\n\n{# if href}\n <a {href}>\n <slot></slot>\n </a>\n{:else}\n <button>\n <slot></slot>\n </button>\n{/if}\n```\n\n```js\nconst Button = (props) => {\n const Tag = props.href ? 'a' : 'button'\n\n return <Tag href={props.href}>{contents}</Tag>\n}\n```\n\n```html\n<script lang='ts'>\n import Children from './children.svelte'\n\n export let href: string = ''\n</script>\n\n{# if href}\n <a {href}>\n <Children><slot></slot></Children>\n </a>\n{:else}\n <button>\n <Children><slot></slot></Children>\n </button>\n{/if}\n```\n\n```html\n<!-- dom-a.svelte -->\n\n<a {...$$props}><slot></slot></a>\n```\n\n```html\n<!-- dom-button.svelte -->\n\n<button {...$$props}><slot></slot></button>\n```\n\n```html\n<!-- button.svelte -->\n<script lang='ts'>\n import A from './dom-a.svelte'\n import Button from './dom-button.svelte'\n\n export let href: string = ''\n\n $: component = href ? A : Button\n</script>\n\n<svelte:component this={component}>\n <slot></slot>\n</svelte:component>\n```\n\n```text\n<button>\n```\n\n```text\n<a>\n```\n\n```text\nsvelte:component\n```\n\n```text\nsvelte:component\n```\n\n```text\nContainer\n```\n\n```text\ndiv\n```\n\n```text\nsection\n```\n\n```text\narticle\n```\n\n```text\naside\n```\n\n```text\nsvelte:component\n```\n\n```text\ndom-button.svelte\n```\n\n```text\ndom-a.svelte\n```\n\n```none\n<script>\n export let href = '';\n \n let tag = href ? 'a' : 'button';\n</script>\n\n<svelte:element this={tag} {href}>\n <slot></slot>\n</svelte:element>\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.686Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":264,"estimatedTokens":1077}}354{"id":"stack-73754777","source":"stackoverflow","questionId":73754777,"title":"Svelte: Import by absolute path does not work","tags":["typescript","svelte","vite"],"text":"Title: Svelte: Import by absolute path does not work\nTags: typescript, svelte, vite\nSource: Stack Overflow\n\nQuestion:\nI'm trying to import enums, objects, functions, and svelte components by using absolute paths to files, but the compiler can't find them.\n\nThis is how i do the imports:\n\n```\n\n import { MyEnum } from \"src/lib/enums\";\n ... code ...\n\n```\n\nThe VS Code compiler does not complain about the path.\n\nI get the following error message on the window when running the app:\n\n```\n[plugin:vite:import-analysis] Failed to resolve import \"src/lib/enums\" from \"src\\lib\\GUI\\ObjectOnBoard.svelte\". Does the file exist?\n35 | \n36 | const { Object: Object_1 } = globals;\n37 | import { MyEnum } from \"src/lib/enums\";\n | ^\n```\n\nI have done some research, and i've found out that there might be some issues regarding my config files, but i don't know how to configure these files in order to make the referencing work. These are the config files (the ones i think are relevant?) in my project:\n\nvite.config.ts:\n\n```\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [svelte()],\n})\n```\n\nsvelte.config.js:\n\n```\nimport sveltePreprocess from 'svelte-preprocess'\n\nexport default {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: sveltePreprocess(),\n}\n```\n\ntsconfig.json:\n\n```\n{\n \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n \"compilerOptions\": {\n \"target\": \"esnext\",\n \"useDefineForClassFields\": true,\n \"module\": \"esnext\",\n \"resolveJsonModule\": true,\n \"baseUrl\": \".\",\n /**\n * Typecheck JS in `.svelte` and `.js` files by default.\n * Disable checkJs if you'd like to use dynamic types in JS.\n * Note that setting allowJs false does not prevent the use\n * of JS in `.svelte` files.\n */\n \"allowJs\": true,\n \"checkJs\": true,\n \"isolatedModules\": true,\n },\n \"include\": [\"src/**/*.d.ts\", \"src/**/*.{svelte,ts,js}\"],\n \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\nThe answer given below works for compiling the code, so now it actually runs which is awesome! But there are still some problem regarding VS Code autocompletion and error messages (red wiggly lines).\n\nSpecifying absolute paths works flawless inside of .svelte files, but in .ts files, typescript keeps alerting the error, eventhough the code compiles and works:\n\n```\n\"Cannot find module 'src/lib/objects/outlet' or its corresponding type declarations.\"\n```\n\nThis error statements appears within the file \"src/lib/MainDataStructure\".\n\nI've tried \"Restart TS Server\", but it does not help. I've looked at this question which has alot of suggestions on how to solve this, but none works for me.\n\nThis is my current tsconfig.json file:\n\n```\n{\n \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n \"compilerOptions\": {\n \"moduleResolution\": \"node\",\n \"target\": \"esnext\",\n \"useDefineForClassFields\": true,\n \"module\": \"esnext\",\n \"resolveJsonModule\": true,\n \"allowSyntheticDefaultImports\": true,\n /**\n * Typecheck JS in `.svelte` and `.js` files by default.\n * Disable checkJs if you'd like to use dynamic types in JS.\n * Note that setting allowJs false does not prevent the use\n * of JS in `.svelte` files.\n */\n \"allowJs\": true,\n \"checkJs\": true,\n \"isolatedModules\": true,\n \"baseUrl\": \".\",\n \"paths\": {\n \"src/*\": [\n \"src/*\"\n ],\n }\n },\n \"include\": [\"src/**/*.d.ts\", \"src/**/*.{svelte,ts,js}\"],\n \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\nThis is an image of my directory in the project:\n\nhttps://i.sstatic.net/UpZV1.png\n\n========================================\n\nTop Answer:\nThis is an answer to those who is using SvelteKit.\n\nReference:\n\nhttps://kit.svelte.dev/docs/configuration#alias\n\nUse case:\n\n```\n\n import 'src/app.css';\n\n```\n\nWhere the folder `src` is located at the root level of the project.\n\nSolution:\n\nThis section is needed in `svelte.config.js`.\n\n```\nconst config = {\n ...\n kit: {\n + alias: {\n + src: 'src',\n + },\n }\n};\n```\n\nNo need to change `vite.config.ts` or `tsconfig.json` manually as the documentation says Svelte will handle it.\n\nYou can also change the line to `$src: 'src'` to make it look closer to Svelte's convention.\n\n```\n\n import '$src/app.css';\n\n```\n\n========================================\n\nCode:\n```text\n<script lang=ts>\n import { MyEnum } from \"src/lib/enums\";\n ... code ...\n<script/>\n```\n\n```text\n[plugin:vite:import-analysis] Failed to resolve import \"src/lib/enums\" from \"src\\lib\\GUI\\ObjectOnBoard.svelte\". Does the file exist?\n35 | \n36 | const { Object: Object_1 } = globals;\n37 | import { MyEnum } from \"src/lib/enums\";\n | ^\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [svelte()],\n})\n```\n\n```text\nimport sveltePreprocess from 'svelte-preprocess'\n\nexport default {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: sveltePreprocess(),\n}\n```\n\n```text\n{\n \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n \"compilerOptions\": {\n \"target\": \"esnext\",\n \"useDefineForClassFields\": true,\n \"module\": \"esnext\",\n \"resolveJsonModule\": true,\n \"baseUrl\": \".\",\n /**\n * Typecheck JS in `.svelte` and `.js` files by default.\n * Disable checkJs if you'd like to use dynamic types in JS.\n * Note that setting allowJs false does not prevent the use\n * of JS in `.svelte` files.\n */\n \"allowJs\": true,\n \"checkJs\": true,\n \"isolatedModules\": true,\n },\n \"include\": [\"src/**/*.d.ts\", \"src/**/*.{svelte,ts,js}\"],\n \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\n```text\n\"Cannot find module 'src/lib/objects/outlet' or its corresponding type declarations.\"\n```\n\n```text\n{\n \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n \"compilerOptions\": {\n \"moduleResolution\": \"node\",\n \"target\": \"esnext\",\n \"useDefineForClassFields\": true,\n \"module\": \"esnext\",\n \"resolveJsonModule\": true,\n \"allowSyntheticDefaultImports\": true,\n /**\n * Typecheck JS in `.svelte` and `.js` files by default.\n * Disable checkJs if you'd like to use dynamic types in JS.\n * Note that setting allowJs false does not prevent the use\n * of JS in `.svelte` files.\n */\n \"allowJs\": true,\n \"checkJs\": true,\n \"isolatedModules\": true,\n \"baseUrl\": \".\",\n \"paths\": {\n \"src/*\": [\n \"src/*\"\n ],\n }\n },\n \"include\": [\"src/**/*.d.ts\", \"src/**/*.{svelte,ts,js}\"],\n \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\n```json\n{\n \"compilerOptions\": {\n \"paths\": {\n \"src/*\": [\n \"src/*\"\n ],\n },\n // ...\n}\n```\n\n```text\n// ...\nimport path from 'path';\n\nexport default defineConfig({\n // ...\n resolve: {\n alias: {\n src: path.resolve('src/'),\n },\n }\n});\n```\n\n```text\ntsconfig/svelte\n```\n\n```text\nsrc\n```\n\n```text\ntsconfig.json\n```\n\n```text\nbaseUrl\n```\n\n```text\n'.'\n```\n\n```text\nsrc\n```\n\n```text\nvite-tsconfig-paths\n```\n\n```text\nvite.config.js\n```\n\n```text\ntsconfig\n```\n\n```text\n<script>\n import 'src/app.css';\n</script>\n```\n\n```text\nconst config = {\n ...\n kit: {\n + alias: {\n + src: 'src',\n + },\n }\n};\n```\n\n```text\n<script>\n import '$src/app.css';\n</script>\n```\n\n```text\nsrc\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nvite.config.ts\n```\n\n```text\ntsconfig.json\n```\n\n```text\n$src: 'src'\n```\n\n========================================\n\nComments:\n- I tried adding \"paths\": { \"src/*\" : [ \"src/*\" ] } into compilerOptions, but it does not yet work. I don't think i can you on Node module resolution and baseUrl, could you elaborate?\n- If you look at the `vite.config.js`, it has an import from `'vite'`. There is no such folder => By default imports look for modules in `node_modules` (unless they start with a `.`). This lookup mechanism is called \"module resolution\", and searching for `node_modules` is the mechanism for Node.\n- The `baseUrl` option specifies what folder the paths used with the `path` option and other imports are relative to.\n- (The TS config from `@tsconfig/svelte` sets `\"moduleResolution\": \"node\"`, by the way.)\n- I don't really know what i want to set my configurations to, all i know is i want to specify the locations of files as like \"src/lib/enums\", and your answer does not seem to work for me unfortunately. Appart from adding \"paths\": { \"src/*\" : [ \"src/*\" ] } to compilerOptions, is there anything else i'm missing?\n- I just noticed that Vite needs additional setup to handle this; edited my answer.\n- Added some more info for a manual Vite fix.\n- Amazing, adding the vite-tsconfig-paths package worked!\n- Now i find, as you mentioned, that code completion regarding absolute path in typescript does not work, VS Code is giving an error on the absolute path, eventhough the code compiles and works (only in .ts files, .svelte files works fine). You mention the tsconfig file, what should i correct to make autocompletion work and get rid of the VS Code error?\n- Depends on your folder structure, also make sure to restart the TS language server after changes to the config. Would recommend checking other questions like this one.\n- I've tried almost every combination on the question you sent in the comment, but nothing works. I'm updating my question with further information...\n- Sorry, I do not know what the issue with that might be. I would suggest moving that to a separate question since this is mainly a dev tooling issue, unrelated to Svelte.\n- Both work for me: kit.alias in svelte.config.js, or resolve.alias in vite.config.js, or both together.","metadata":{"transformedAt":"2026-08-18T18:33:40.687Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":391,"estimatedTokens":2420}}355{"id":"stack-79123984","source":"stackoverflow","questionId":79123984,"title":"Svelte 5 snippets parameter 'x' implicitly has an 'any' type","tags":["node.js","svelte","sveltekit","svelte-5"],"text":"Title: Svelte 5 snippets parameter 'x' implicitly has an 'any' type\nTags: node.js, svelte, sveltekit, svelte-5\nSource: Stack Overflow\n\nQuestion:\nAfter upgrading to Svelte 5, I tried the new `{#snippet ...}`. I am getting this type errors, but in the svelte docs it is like they do not exist for them.\n\n```\n{#snippet NavLink(href, text)}\n {text}\n{/snippet}\n```\n\nParameter href implicitly has an `any` type.\n\nWe can fix this issue provisionally by doing this (but I don't like it):\n\n```\n{#snippet NavLink(/** @type {any} */ href)}\n hello\n{/snippet}\n```\n\nIs there a better way?\n\n========================================\n\nCode:\n```html\n{#snippet NavLink(href, text)}\n <a class=\"text-white\" {href}>{text}</a>\n{/snippet}\n```\n\n```html\n{#snippet NavLink(/** @type {any} */ href)}\n <a class=\"text-white\" {href}>hello</a>\n{/snippet}\n```\n\n```text\n{#snippet ...}\n```\n\n```text\nany\n```\n\n```html\n{#snippet NavLink(href: string, text: string)}\n <a class=\"text-white\" {href}>{text}</a>\n{/snippet}\n```\n\n```text\ncheckJs\n```\n\n```text\nstrict\n```\n\n```text\nnoImplicitAny\n```\n\n```text\n<script lang=\"ts\">\n```\n\n========================================\n\nComments:\n- I think you mean Svelte 5, not SvelteKit 5\n- In my case I hadn't yet written any script. Very good to know that adding an empty `` to the top allows using typescript in the template","metadata":{"transformedAt":"2026-08-18T18:33:40.687Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":75,"estimatedTokens":333}}356{"id":"stack-59313371","source":"stackoverflow","questionId":59313371,"title":"How could I integrate Materialize CSS and JavaScript components into Svelte","tags":["javascript","materialize","svelte"],"text":"Title: How could I integrate Materialize CSS and JavaScript components into Svelte\nTags: javascript, materialize, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm new to Svelte, and I want to build my next project with it.\n\nI want to use Materialize for CSS and JavaScript components, but I couldn't find a way to set it up and integrate with Svelte.\n\nHow could I do that?\n\n========================================\n\nTop Answer:\nI have developed this template with Svelte + MaterializeCSS and SMUI (Svelte Material UI) >> Svelte + MaterializeCSS + SMUI\n\n========================================\n\nCode:\n```html\n<!-- base styles -->\n<link rel='stylesheet' href='/global.css'>\n\n<!-- styles that were defined in the components -->\n<link rel='stylesheet' href='/build/bundle.css'>\n```\n\n```js\nimport '../node_modules/materialize-css/dist/css/materialize.css'\nimport '../public/global.css'\n\n// import js stuff too\nimport '../node_modules/materialize-css/dist/js/materialize'\n\n....\n\n// init material plugins\nM.AutoInit()\n```\n\n```text\n- <link rel='stylesheet' href='/global.css'>\n+ <link rel='stylesheet' href='/build/base.css'>\n```\n\n```text\nmaterialize-css\n```\n\n```text\nyarn add -D materialize-css\n```\n\n```text\npublic/index.html\n```\n\n```text\nglobal.css\n```\n\n```text\nglobal.css\n```\n\n```text\nmaterialize/dist/materialize.css\n```\n\n```text\nrollup-plugin-css-only\n```\n\n```text\nyarn add -D rollup-plugin-css-only\n```\n\n```text\nrollup.config.js\n```\n\n```text\nimport css from 'rollup-plugin-css-only'\n```\n\n```text\ncss({output: \"public/build/base.css\"})\n```\n\n```text\nplugins\n```\n\n```text\n.css\n```\n\n```text\nsrc/main.js\n```\n\n```text\npublic/index.html\n```\n\n```text\nbase.css\n```\n\n```text\nglobal.css\n```\n\n========================================\n\nComments:\n- @josnuss what if you were using Sapper & Svelte? I'm assuming the `M.AutoInit()` and plugin would apply on the client side - correct?\n- Yes, correct. Materialize runs only on the client side.\n- Please explain how this relates to the question and how it works.","metadata":{"transformedAt":"2026-08-18T18:33:40.687Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":119,"estimatedTokens":498}}357{"id":"stack-73427634","source":"stackoverflow","questionId":73427634,"title":"Is it possible to somehow change the value of a derived store directly?","tags":["javascript","svelte","sveltekit"],"text":"Title: Is it possible to somehow change the value of a derived store directly?\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am currently working with SvelteKit.\n\nI have a `derived` store, which is necessary because it depends on another store. Now I need to change some values in the `derived` store directly. The problem is that `derived` stores are not modifyable as far as my understanding goes.\n\nIs there any way to change the value of a `derived` store directly?\n\nFor example if I'd have a `derived` store called `tiles` which is an array of objects and I would like to change the property of one of its objects (`$tiles[n].x = 'something new'`)\n\n========================================\n\nCode:\n```text\nderived\n```\n\n```text\nderived\n```\n\n```text\nderived\n```\n\n```text\nderived\n```\n\n```text\nderived\n```\n\n```text\ntiles\n```\n\n```text\n$tiles[n].x = 'something new'\n```\n\n```js\nconst parent = writable({ items: [{ name: 'pochi' }, { name: 'maru' }]});\nconst items = derived(parent, value => value.items);\nitems.set = newItems => $parent.items = newItems;\n```\n\n```text\nset\n```\n\n========================================\n\nComments:\n- Thanks for the reponse. Could you take a look at this REPL example and tell me how I would go about including it there? It's still quite confusing for me.\n- @h-thilo: You can't, because all the data the store returns is fully generated. If you want things to be mutable, you have to pull them out of the function that generates the store.\n- @h-thilo: This would be the simples approach: REPL - Note that this will not be able to handle replacements, it just mutates the existing items and triggers an update.\n- @h-thilo Here would be a more complex example that allows replacement of the whole tile set, depending on the current setting: REPL.\n- Thanks a lot for all of your effort! Interesting examples! However, I managed to find a relatively simple way to do what I wanted to do. I simply pass the other `writable` store as function paramter to the other `writable` store. This way I don't have to rely on derived stores. Here the example: REPL\n- That is just a function, at least in that example there is no need for the store at all (REPL).\n- Yeah in my current code I think it does make sense. I need to those values over multiple components and my code is much longer. Can't really put that all into the REPL though.","metadata":{"transformedAt":"2026-08-18T18:33:40.687Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":64,"estimatedTokens":594}}358{"id":"stack-57229360","source":"stackoverflow","questionId":57229360,"title":"Svelte internals: how does reactive declaration syntax work","tags":["svelte"],"text":"Title: Svelte internals: how does reactive declaration syntax work\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nRegarding reactive declarations in svelte like \n`$: doubled = count*2`, it states in the svelte tutorial that\n\n Don't worry if this looks a little alien. It's valid (if unconventional) JavaScript, which Svelte interprets to mean 're-run this code whenever any of the referenced values change'\n\nThe conventional javascript feature refrences seems to be labels (please confirm) \n\nPlease explain how this is done by the svelte compiler in simple words and provide a reference to the place in the compiler code where this happens [or starts to happen]\n\nThere is a githb issue open to explain svelte internals eventually.\n\n========================================\n\nCode:\n```text\n$: doubled = count*2\n```\n\n```text\n$: quadrupled = doubled * 2;\n$: doubled = count * 2;\n```\n\n```text\nif ($$dirty.count) { $$invalidate('doubled', doubled = count * 2); }\nif ($$dirty.doubled) { $$invalidate('quadrupled', quadrupled = doubled * 2); }\n```\n\n```text\n$$self.$$.update\n```\n\n```text\n$: doubled = count * 2;\n```\n\n```text\nif ($$dirty.count) { $$invalidate('doubled', doubled = count * 2); }\n```\n\n```text\n$$invalidate\n```\n\n========================================\n\nComments:\n- Try making a simple example in the svelte.dev/repl and inspect the JS output on the right hand side.","metadata":{"transformedAt":"2026-08-18T18:33:40.687Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":53,"estimatedTokens":343}}359{"id":"stack-68134909","source":"stackoverflow","questionId":68134909,"title":"Svelte: Use function from a parent component","tags":["svelte","svelte-component"],"text":"Title: Svelte: Use function from a parent component\nTags: svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nIn my App.svelte I have the following code with my function:\n\n```\n\n import Categories from \"./Categories.svelte\";\n\n let choice = { category: false };\n\n export function toggle() {\n choice.category = !choice.category;\n }\n\n{#if choice.category}\n \n{:else}\n Foo.\n\n{/if}\n```\n\nIn my Categories component I have the following code:\n\n```\n\n Analyse vegetation and forestry\n\n```\n\nWhat I want is that: When I click on the button in the category component, the `toggle()` function should be called.\n\nHow can I do that?\n\n========================================\n\nCode:\n```-svelte\n<script>\n import Categories from \"./Categories.svelte\";\n\n let choice = { category: false };\n\n export function toggle() {\n choice.category = !choice.category;\n }\n</script>\n\n{#if choice.category}\n <Categories />\n{:else}\n <p>Foo.</p>\n{/if}\n```\n\n```svelte\n<button id=\"vegetation\" on:click=\"toggle()\">\n <span>Analyse vegetation and forestry</span>\n</button>\n```\n\n```text\ntoggle()\n```\n\n```html\n<!-- Parent.svelte -->\n<script>\n function something() { }\n</script>\n\n<Child on:toggle={something} />\n```\n\n```html\n<!-- Child.svelte -->\n<script>\n import { createEventDispatcher } from 'svelte'\n const dispatch = createEventDispatcher()\n\n function toggle() {\n dispatch('toggle')\n }\n</script>\n\n<button on:click={toggle}>click me</button>\n```\n\n```html\n<!-- Parent.svelte -->\n<script>\n function parentToggle() { }\n</script>\n<Child toggle={parentToggle} />\n```\n\n```html\n<!-- Child.svelte -->\n<script>\n export let toggle = () => {} // no-operation function\n</script>\n<button on:click={toggle}>Click me</button>\n```\n\n========================================\n\nComments:\n- You can forward the click event (without using a dispatcher). Example from the tutorial: svelte.dev/tutorial/dom-event-forwarding\n- Is any solution to be preferred to the other ?\n- @cassepipe the first one is preferred because it will look the same for both native elements and components, giving more consistency in your code.","metadata":{"transformedAt":"2026-08-18T18:33:40.687Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":113,"estimatedTokens":526}}360{"id":"stack-65542265","source":"stackoverflow","questionId":65542265,"title":"adding dynamic class name in svelte","tags":["css","svelte","tailwind-css","rollup","sapper"],"text":"Title: adding dynamic class name in svelte\nTags: css, svelte, tailwind-css, rollup, sapper\nSource: Stack Overflow\n\nQuestion:\nI am currently writing an app with svelte, sapper and tailwind. So to get tailwind working I have added this to my rollup config\n\n```\nsvelte({\n compilerOptions: {\n dev,\n hydratable: true,\n },\n preprocess: sveltePreprocess({\n sourceMap: dev,\n postcss: {\n plugins: [\n require(\"tailwindcss\"),\n require(\"autoprefixer\"),\n require(\"postcss-nesting\"),\n ],\n },\n }),\n emitCss: true,\n })\n```\n\nAll in all this works, but I am getting some issues with dynamic class names.\n\nWriting something like this always seems to work\n\n```\n\n```\n\nboth `class-a` and `class-b` will be included in the final emitted CSS and everything works as expected.\n\nBut when I try to add a variable class name it won't work. So imagine this:\n\n```\n\n```\n\nIt will work exactly as expected and it will get the proper styling from the css class `col-span-6` in tailwind.\n\nBut if I change it to this:\n\n```\n\n```\n\nThen the style won't be included.\nIf I on the other hand already have a DOM element with the class `col-span-6` then the styling will be added to both elements.\n\nSo my guess here is that the compiler sees that the css is not used and it gets removed.\nAnd I suppose that my question is then if there is any way to force in all the styling from tailwind? so that I can use more dynamic class names\n\nand not sure if it is relevant but the component I have been testing this on, have this style block\n\n```\n\n @tailwind base;\n @tailwind components;\n @tailwind utilities;\n\n```\n\n*edit:* can add that I am getting a bunch of prints in the log saying that there are unused css selectors that seems to match all tailwind classes\n\n========================================\n\nTop Answer:\nI think that when the class attribute is a variable or depends on a variable it will not used to extract style during compilation (`class-${6}` is not evaluated during compilation but during runtime), because svelte marks it as unused css selector because the value of that class attribute is not known when the code is compiled.\n\nTo force svelte to include your style you must mark it as global, and to do that we have two options:\n\n```\n\n// component logic goes here\n\ndiv class={`class-${6}`}/>\n```\n\noption 1:\n\n```\n\n :global(.class-6){\n // style goes here\n }\n\n```\n\noption 2: this will mark all your style as global\n\n```\n\n .class-6{\n // style goes here\n }\n\n```\n\n========================================\n\nCode:\n```text\nsvelte({\n compilerOptions: {\n dev,\n hydratable: true,\n },\n preprocess: sveltePreprocess({\n sourceMap: dev,\n postcss: {\n plugins: [\n require(\"tailwindcss\"),\n require(\"autoprefixer\"),\n require(\"postcss-nesting\"),\n ],\n },\n }),\n emitCss: true,\n })\n```\n\n```text\n<div class={true ? 'class-a' : 'class-b'}>\n```\n\n```text\n<div class={`col-span-6`}>\n```\n\n```text\n<div class={`col-span-${6}`}>\n```\n\n```text\n<style>\n @tailwind base;\n @tailwind components;\n @tailwind utilities;\n</style>\n```\n\n```text\nclass-a\n```\n\n```text\nclass-b\n```\n\n```text\ncol-span-6\n```\n\n```text\ncol-span-6\n```\n\n```js\n// tailwind.config.js\nmodule.exports = {\n purge: {\n content: ['./src/**/*.html'],\n\n // These options are passed through directly to PurgeCSS\n options: {\n // Generate col-span-1 -> 12\n safelist: [...Array.from({ length: 12. }).fill('').map((_, i) => `col-span-${i + 1}`],\n },\n },\n // ...\n}\n```\n\n```js\n<script>\n// component logic goes here\n</script>\ndiv class={`class-${6}`}/>\n```\n\n```js\n<style>\n :global(.class-6){\n // style goes here\n }\n</style>\n```\n\n```js\n<style global>\n .class-6{\n // style goes here\n }\n</style>\n```\n\n```text\nclass-${6}\n```\n\n```text\n<div class=\"pl-{indent*4}\">\n```\n\n```text\n<div style=\"padding-left:{indent}rem\">\n```\n\n```text\npl-1\n```\n\n```text\npadding-left: 0.25rem; /* 4px */\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.687Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":220,"estimatedTokens":984}}361{"id":"stack-65791210","source":"stackoverflow","questionId":65791210,"title":"Svelte reactive statement which updates when only some of the referenced variables are changed","tags":["svelte"],"text":"Title: Svelte reactive statement which updates when only some of the referenced variables are changed\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI have been using Svelte for a while and this issue really bugs me.\nHow could I create a reactive statement which updates when only some of the referenced variables are changed?\n\nFor example, I want to re-compute `d` only when `a` or `b` are changed, but not when `c` is changed:\n\n```\n\n let a = 1;\n let b = 2;\n let c = 3;\n $: d = a + b + c;\n\n```\n\nBut `d` is re-eveluated when `a`,`b`, or `c` changes.\n\nHow could I do that?\n\n========================================\n\nCode:\n```html\n<script>\n let a = 1;\n let b = 2;\n let c = 3;\n $: d = a + b + c;\n</script>\n```\n\n```text\nd\n```\n\n```text\na\n```\n\n```text\nb\n```\n\n```text\nc\n```\n\n```text\nd\n```\n\n```text\na\n```\n\n```text\nb\n```\n\n```text\nc\n```\n\n```text\nfunction update(a, b) {\n return a + b + c;\n}\n\n$: d = update(a, b);\n```\n\n```text\na\n```\n\n```text\nb\n```\n\n```text\nc\n```\n\n========================================\n\nComments:\n- Brilliant I wish the official docs referenced this","metadata":{"transformedAt":"2026-08-18T18:33:40.687Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":91,"estimatedTokens":268}}362{"id":"stack-63071835","source":"stackoverflow","questionId":63071835,"title":"Svelte: is not working with style attribute in div on window resize","tags":["javascript","resize","window","height","svelte"],"text":"Title: Svelte: is not working with style attribute in div on window resize\nTags: javascript, resize, window, height, svelte\nSource: Stack Overflow\n\nQuestion:\nOn window resize, I have tried to add dynamic height as style property in div element, using svelte special element `` but I am not getting the proper result which I am looking for, Is there anything I missed.\n\n**Code**:-\n\n```\n\n var innerHeight;\n\n \n\n### window height : {innerHeight}\n\n```\n\n**Output**:-\n\nenter image description here\n\nThanks in advance\n\n========================================\n\nCode:\n```text\n<script>\n var innerHeight;\n</script>\n\n<svelte:window bind:innerHeight={innerHeight} />\n\n<div style=\"height: {innerHeight};\">\n <h1>window height : {innerHeight}</h1>\n</div>\n```\n\n```text\n<svelte:window bind:innerHeight />\n```\n\n```text\ninnerHeight\n```\n\n```text\nstyle=\"height: {innerHeight}px;\"\n```\n\n========================================\n\nComments:\n- I have got the answer since the innerHeight is unit less value we have to add px like this style=\"height: {innerHeight}px;\"\n- Yes, I got the solution and its working fine. Thanks a lot!!","metadata":{"transformedAt":"2026-08-18T18:33:40.687Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":57,"estimatedTokens":278}}363{"id":"stack-75760355","source":"stackoverflow","questionId":75760355,"title":"What should I choose for the href attribute for an `` element in Svelte?","tags":["svelte","sveltekit"],"text":"Title: What should I choose for the href attribute for an `` element in Svelte?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nSuppose I want to use an `` link for a toggle in Svelte/SvelteKit. For example:\n\n```\ncollapsed=!collapsed}>Toggle\n```\n\nI get this warning from my VS Code plugin:\n\n`A11y: element should have an href attributesvelte(a11y-missing-attribute)`\n\nWhat's an appropriate choice for `href`? If I try `#` or `javascript:void(0)` as suggested at Which \"href\" value should I use for JavaScript links, \"#\" or \"javascript:void(0)\"? I am told:\n\n`A11y: '#' is not a valid href attributesvelte(a11y-invalid-attribute)`\n\n========================================\n\nCode:\n```html\n<a on:click|preventDefault={_=>collapsed=!collapsed}>Toggle</a>\n```\n\n```text\n<a>\n```\n\n```text\nA11y: <a> element should have an href attributesvelte(a11y-missing-attribute)\n```\n\n```text\nhref\n```\n\n```text\n#\n```\n\n```text\njavascript:void(0)\n```\n\n```text\nA11y: '#' is not a valid href attributesvelte(a11y-invalid-attribute)\n```\n\n```text\n<button on:click={_=>collapsed=!collapsed}>Toggle</button>\n```\n\n```text\n<div on:click={_=>collapsed=!collapsed}>Toggle</div> (DO NOT DO THIS)\n```\n\n========================================\n\nComments:\n- In my app using SvelteKit with a static site adapter, using `href=\"./\"` seems to behave reasonably and not raise any warnings. (I'd prefer an answer that explains more of the rationale for this warning, particularly why leaving off `href` altogether isn't acceptable.)\n- Thanks. As a bonus, I think the UI is improved for the purpose I'm currently working on with the button styling vs. appearing as a link. I'm not using any CSS framework for this project, but I suppose this is why e.g. Bootstrap has support for a btn-link class: getbootstrap.com/docs/5.0/components/buttons/#examples","metadata":{"transformedAt":"2026-08-18T18:33:40.687Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":63,"estimatedTokens":456}}364{"id":"stack-56844807","source":"stackoverflow","questionId":56844807,"title":"Svelte Long Press","tags":["javascript","reactive-programming","dom-events","svelte"],"text":"Title: Svelte Long Press\nTags: javascript, reactive-programming, dom-events, svelte\nSource: Stack Overflow\n\nQuestion:\nI need a long press event to bind to buttons in svelte 3. I want to do this in the least \"boilerplaty\" way possible.\n\nI've tried with a long press function but this seems a little convoluted and hacky, also seems a little slow. \n\n```\nfunction longPress(node, callback) {\n console.log(node)\n function onmousedown(event) {\n const timeout = setTimeout(() => callback(node.innerHTML), 1000);\n\n function cancel() {\n clearTimeout(timeout);\n node.removeEventListener(\"mouseup\", cancel, false);\n }\n\n node.addEventListener(\"mouseup\", cancel, false);\n }\n\n node.addEventListener(\"mousedown\", onmousedown, false);\n\n return {\n destroy() {\n node.removeEventListener(\"mousedown\", onmousedown, false);\n }\n };\n }\n\n \n {#each Object.entries(bindings) as [id, value]}\n longPress(this,addImage)}> {id} \n {/each}\n\n```\n\nThis works but I'm sure there is a better way.\n\n========================================\n\nTop Answer:\nI would recommend using 'press' action in svelte-gestures library if you want consistent support on desktop and mobile devices. It allows setting up duration time.\n\n========================================\n\nCode:\n```text\nfunction longPress(node, callback) {\n console.log(node)\n function onmousedown(event) {\n const timeout = setTimeout(() => callback(node.innerHTML), 1000);\n\n function cancel() {\n clearTimeout(timeout);\n node.removeEventListener(\"mouseup\", cancel, false);\n }\n\n node.addEventListener(\"mouseup\", cancel, false);\n }\n\n node.addEventListener(\"mousedown\", onmousedown, false);\n\n return {\n destroy() {\n node.removeEventListener(\"mousedown\", onmousedown, false);\n }\n };\n }\n</script>\n\n<div>\n <Video />\n {#each Object.entries(bindings) as [id, value]}\n <button on:click = {()=>longPress(this,addImage)}> {id} </button>\n {/each}\n</div>\n```\n\n```html\n<script>\n import { longpress } from './actions.js';\n let pressed;\n</script>\n\n<button use:longpress on:longpress=\"{e => pressed = true}\">\n longpress me\n</button>\n```\n\n```js\nexport function longpress(node, threshold = 500) {\n // note — a complete answer would also consider touch events\n\n const handle_mousedown = () => {\n let start = Date.now();\n\n const timeout = setTimeout(() => {\n node.dispatchEvent(new CustomEvent('longpress'));\n }, threshold);\n\n const cancel = () => {\n clearTimeout(timeout);\n node.removeEventListener('mousemove', cancel);\n node.removeEventListener('mouseup', cancel);\n };\n\n node.addEventListener('mousemove', cancel);\n node.addEventListener('mouseup', cancel);\n }\n\n node.addEventListener('mousedown', handle_mousedown);\n\n return {\n destroy() {\n node.removeEventListener('mousedown', handle_mousedown);\n }\n };\n}\n```\n\n```text\nlongpress\n```\n\n```text\nlongpress\n```\n\n```text\naddImage\n```\n\n```text\nnode.innerHTML\n```\n\n========================================\n\nComments:\n- Awesome stuff, just change `setTimeout` to `setInterval`.\n- setTimeout is correct. setInterval would repeat it.\n- @sudobangbang Right that was what I needed to do. This makes for an even more re-usable function.\n- How to make `on:click` co-exist with `on:longpress`? Click gets triggered for longpress as well\n- @SaravanabalagiRamachandran to prevent the click from triggering when user actually intends to do a long press, listen for \"mouseup\" event instead of \"click\". Mouseup means user releases the mouse/press, and so you can determine whether it was a long press or a short tap.\n- @SaravanabalagiRamachandran any updates? I've run into the same issue.","metadata":{"transformedAt":"2026-08-18T18:33:40.687Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":148,"estimatedTokens":915}}365{"id":"stack-69919047","source":"stackoverflow","questionId":69919047,"title":"Is this a problem with Array push() in Svelte or is it something I'm doing wrong?","tags":["arrays","promise","push","svelte"],"text":"Title: Is this a problem with Array push() in Svelte or is it something I'm doing wrong?\nTags: arrays, promise, push, svelte\nSource: Stack Overflow\n\nQuestion:\nI've been wracking my brain over this issue for several hours now, and although I've found a workaround to the problem, I can't get over the fact that it's happening at all. I don't understand it. There seems to be some sort of an issue in using Array.push() within a promise handler. I've created the below test code to demonstrate it, and it's reproducable in Svelte REPL. Am I just doing something wrong?\n\n```\n\n const myPromise = new Promise((resolve, reject) => {\n setTimeout(() => {\n resolve('foo');\n }, 300);\n });\n\n let itemsA = [];\n let itemsB = [];\n\n const addItem = (item) => {\n itemsA[itemsA.length] = item;\n itemsB.push(item);\n }\n \n const loadItems = (last) => {\n addItem(\"Begin\");\n\n myPromise\n .then((value) => {\n addItem(value);\n });\n\n addItem(\"End\");\n return true;\n };\n\n loadItems();\n\nItems A: {itemsA}\nItems B: {itemsB}\n```\n\nI would think that itemsB.push(item) should do the same thing as itemsA[itemsA.length] = item, and it does, except when called from inside the promise handler.\n\nI get the following results instead:\n\n```\nItems A: Begin,End,foo\nItems B: Begin,End\n```\n\nEdit: I've eliminated promises as the source of the weirdness. The following code illustrates it more simply.\n\n```\n\n let itemsA = [];\n let itemsB = [];\n\n const addItem = (item) => {\n itemsA[itemsA.length] = item;\n itemsB.push(item);\n }\n\n const clickHandler = () => {\n addItem('click');\n }\n \n addItem('load');\n\nItems A: {itemsA}\nItems B: {itemsB}\nClick Me\n```\n\n========================================\n\nTop Answer:\nYou can try this:\nhttps://svelte.dev/repl/0dedb37665014ba99e05415a6107bc21?version=3.53.1\n\nuse a library called `svelox`.\nIt allows you to use the `Array` native api(push/splice...etc.) without reassignment statements.\n\n========================================\n\nCode:\n```text\n<script>\n const myPromise = new Promise((resolve, reject) => {\n setTimeout(() => {\n resolve('foo');\n }, 300);\n });\n\n let itemsA = [];\n let itemsB = [];\n\n const addItem = (item) => {\n itemsA[itemsA.length] = item;\n itemsB.push(item);\n }\n \n const loadItems = (last) => {\n addItem(\"Begin\");\n\n myPromise\n .then((value) => {\n addItem(value);\n });\n\n addItem(\"End\");\n return true;\n };\n\n loadItems();\n</script>\n\n<div>Items A: {itemsA}</div>\n<div>Items B: {itemsB}</div>\n```\n\n```text\nItems A: Begin,End,foo\nItems B: Begin,End\n```\n\n```text\n<script>\n let itemsA = [];\n let itemsB = [];\n\n const addItem = (item) => {\n itemsA[itemsA.length] = item;\n itemsB.push(item);\n }\n\n const clickHandler = () => {\n addItem('click');\n }\n \n addItem('load');\n</script>\n\n<div>Items A: {itemsA}</div>\n<div>Items B: {itemsB}</div>\n<button on:click={clickHandler}>Click Me</button>\n```\n\n```js\nitemsB.push(item);\nitemsB = itemsB\n```\n\n```js\nitemsB = [...itemsB, item]\n```\n\n```text\nsvelox\n```\n\n```text\nArray\n```\n\n========================================\n\nComments:\n- This is the way promises work. The `addItem` in the outer scope of `loadItems` runs before the `addItem` inside the promise handler. For more information, there's a great video here: youtube.com/watch?v=8aGhZQkoFbQ&ab_channel=JSConf\n- This is useful, and I'll be sure not to use push (I kind of narrowed it down myself as you can see from the edit I added just as you were adding this response).. I'm not sure I understand why Svelte doesn't render it though. Shouldn't it?\n- I'm not sure I understand what you mean..? You mean why it's not rendered with just using .push()?\n- Yes, that's what I mean.\n- Well, I think I'll have to pass this question to the makers of Svelte... :-) I just accepted (for now) that the assignment is important for everything to behave as expected","metadata":{"transformedAt":"2026-08-18T18:33:40.687Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":172,"estimatedTokens":959}}366{"id":"stack-66354346","source":"stackoverflow","questionId":66354346,"title":"Mousewheel function returning error on svelte","tags":["typescript","svelte","svelte-component"],"text":"Title: Mousewheel function returning error on svelte\nTags: typescript, svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\ni'd like to know why this code\n\n```\nhandleScroll(e)}\">\n```\n\nis returning the following error\n\nType '{ class: string; onmousewheel: (e: any) => void; }' is not assignable to type 'HTMLProps'.\nProperty 'onmousewheel' does not exist on type 'HTMLProps'.\n\nIt is just for curiosity because it works perfectly even with the error.\n\nPs. I'm using TypeScript\n\n========================================\n\nTop Answer:\nI believe the event you are looking for is onwheel which would translate to `on:wheel` in Svelte.\n\nAlternatively, if you're only interested in the mouse wheel events for scrolling purposes, the correct event would be onscroll (`on:scroll` in Svelte).\n\n========================================\n\nCode:\n```text\n<div class=\"home\" on:mousewheel=\"{e=>handleScroll(e)}\"></div>\n```\n\n```text\n// additional-svelte-jsx.d.ts\ndeclare namespace svelte.JSX {\n interface HTMLAttributes<T> {\n onmousewheel?: (event: any) => any;\n }\n}\n```\n\n```text\non:wheel\n```\n\n```text\non:scroll\n```\n\n========================================\n\nComments:\n- I am not familiar with typescript, but I think you need to do it something like that: `handleScroll(e)}\">` see here stackoverflow.com/a/55573846/4593433 Also there is a typo: `on:mousewheel`, but I suppose its not in your real code if it works already.\n- The namespace has changed from `svelte.JSX` to `svelteHTML` now. github.com/sveltejs/language-tools/blob/master/docs/…","metadata":{"transformedAt":"2026-08-18T18:33:40.687Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":56,"estimatedTokens":388}}367{"id":"stack-63712141","source":"stackoverflow","questionId":63712141,"title":"How do I design a svelte component to be available in multiple projects?","tags":["typescript","package.json","composition","svelte"],"text":"Title: How do I design a svelte component to be available in multiple projects?\nTags: typescript, package.json, composition, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm building two web applications in svelte/typescript:\n\n- Site A that works as the public-facing front that needs to be as fast and lean as possible\n\n- Site B that is the administration UI where editors update the content that is presented in Site A\n\nI want to use the same \"view component\" (from Site A) in the editor (in Site B) but attach some editor logic in order to build a WYSIWYG experience without code duplication.\n\nI could of course just make both Site A and Site B be part of the same svelte application but I don't want the visitors of Site A to load all the modules and code used in Site B.\n\nHow should I design this to avoid code duplication but still prevent logic from Site B from leaking into Site A?\n\n========================================\n\nTop Answer:\nLet’s say you have an individual project folders for A and B, then you place shared components into a shared-folder, which is sibling to A and B.\n\nWhen you import shared component to A you just give the import a correct path like `../shared/Comp.svelte`. And when you build your project, bundle.js will include only components, that are needed and nothing else.\n\n========================================\n\nCode:\n```js\nexport { Button } from 'path/to/component/Button';\nexport { Card } from 'path/to/component/Card';\n...\n```\n\n```js\nimport { Button } from 'my-design-system';\n```\n\n```text\nButton\n```\n\n```text\nCard\n```\n\n```text\nindex.js\n```\n\n```text\nindex.js\n```\n\n```text\n../shared/Comp.svelte\n```\n\n========================================\n\nComments:\n- Good info. While I was learning about design system I found this article. It explains more about folder structures and index.js: digitalocean.com/community/tutorials/…\n- I'd prefer to access the ts files directly and not to use a build step in between, generating sourcemaps and symlinking and so on. So I'll start out with grohjy's answer first and see how far that takes me :-)\n- @ChristerCarlsund It will be enough until you want that someone else work on your project ;)\n- I believe you should go with @johannchopin ’s way. Making a npm package is pretty easy process and that way you “must” decide, which components are ready for publishing. I believe you can keep published and work-in-process components under the same “shared”-folder, but each of them should have it’s own folder. Now you can develop new components and when they are ready just move them to published folder and update you package. The package makes it easy to use these components in different projects. You just need to ‘npm install your_package’ and you’re ready to use you shared component.","metadata":{"transformedAt":"2026-08-18T18:33:40.687Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":64,"estimatedTokens":692}}368{"id":"stack-67264618","source":"stackoverflow","questionId":67264618,"title":"PouchDB and SvelteKit","tags":["javascript","couchdb","svelte","sveltekit","pouchdb"],"text":"Title: PouchDB and SvelteKit\nTags: javascript, couchdb, svelte, sveltekit, pouchdb\nSource: Stack Overflow\n\nQuestion:\nI want to use PouchDB with SvelteKit. I have copied pouchdb-7.2.1.js to `/src/lib`d in SvelteKit and renamed it to pouchdb.js. Pouchdb should run in the browser. Therefore I have used ssr=false to suppress server side rendering. I get the first error at the import statement. This is my first very short page (couchdb.svelte):\n\n```\n\n export const ssr = false;\n\n import PouchDB from '$lib/pouchdb.js'; \n\n```\n\nI get an error 500\n\n```\nimport not found: PouchDB\n```\n\nI have tried a lot of diffent version without any success. For example:\n\n```\nimport PouchDB from 'pouchdb-browser'; (After npm i pouchdb-browser)\nimport PouchDB from 'pouchdb'; (After npm i pouchdb)\n```\n\nWhat is the correct way to use pouchdb?\n\n========================================\n\nTop Answer:\nFor future googlers trying to integrate `pouchdb-browser` and/or `RxDB` with sveltekit here are the changes to \"fix\" the enviornment for pouchdb in the browser when using vite.\n\n- Add to your `` section before `%svelte.head%`\n\n```\n\n window.process = window.process || {env: {NODE_DEBUG:undefined, DEBUG:undefined}};\n window.global = window;\n\n```\n\n- In `svelte.config.js` add the `optimizeDeps` to `config.kit.vite.optimizeDeps`\n\n```\noptimizeDeps: {\n allowNodeBuiltins: ['pouchdb-browser', 'pouchdb-utils', 'base64id', 'mime-types']\n}\n```\n\nHere is a commit that makes these changes to my app:\nhttps://github.com/TechplexEngineer/bionic-scouting/commit/d1c4a4dcdc7096ae40937501d97a7ef9ee10ab66\n\nThanks to:\npouchdb/pouchdb#8266 (comment)\n\n========================================\n\nCode:\n```text\n<script context=\"module\">\n export const ssr = false;\n</script>\n\n<script>\n import PouchDB from '$lib/pouchdb.js'; \n</script>\n```\n\n```text\nimport not found: PouchDB\n```\n\n```text\nimport PouchDB from 'pouchdb-browser'; (After npm i pouchdb-browser)\nimport PouchDB from 'pouchdb'; (After npm i pouchdb)\n```\n\n```text\n/src/lib\n```\n\n```text\n<script>\n import { onMount } from 'svelte'\n\n // Ensure execution only on the browser, after the pouchdb script has loaded.\n onMount(async function() {\n var db = new PouchDB('my_database');\n console.log({PouchDB})\n console.log({db})\n });\n</script>\n\n\n<svelte:head>\n <script src=\"//cdn.jsdelivr.net/npm/pouchdb@7.2.1/dist/pouchdb.min.js\"></script>\n</svelte:head>\n```\n\n```text\nimport\n```\n\n```text\nvite\n```\n\n```text\n<script>\n```\n\n```text\n<script>\n window.process = window.process || {env: {NODE_DEBUG:undefined, DEBUG:undefined}};\n window.global = window;\n</script>\n```\n\n```text\noptimizeDeps: {\n allowNodeBuiltins: ['pouchdb-browser', 'pouchdb-utils', 'base64id', 'mime-types']\n}\n```\n\n```text\npouchdb-browser\n```\n\n```text\nRxDB\n```\n\n```text\n<head>\n```\n\n```text\n%svelte.head%\n```\n\n```text\nsvelte.config.js\n```\n\n```text\noptimizeDeps\n```\n\n```text\nconfig.kit.vite.optimizeDeps\n```\n\n```text\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"description\" content=\"\" />\n <link rel=\"icon\" href=\"%svelte.assets%/favicon.png\" />\n <meta name=\"viewport\" content=\"width=device-width, initial- \n scale=1\" />\n <!-- Call the Pouchdb import -->\n <script type=\"text/javascript\" src=\"../src/lib/pouchdb.js\">\n </script>\n <!-- create new databases for use in the app -->\n <script>\n const user = new PouchDB('user');\n </script>\n %svelte.head%\n</head>\n```\n\n```text\n<script lang=\"ts\" context=\"module\">\n //Declare the database name so that it is recognized.\n declare const user;\n</script>\n\n<script lang=\"ts\">\n//Example use of database.\nconst addUser = () => {\n //Call the database by name established in app.html\n user.put({\n _id: 'someid',\n firstName: 'Jon',\n lastName: 'doe'\n });\n};\n</script>\n```\n\n========================================\n\nComments:\n- Renaming pouchDB sounds like a bad idea. Check out this ultra simple app, github.com/neighbourhoodie/svelte-pouchdb-couchdb - maybe an epiphany will dawn.\n- I have renamed the file from pouchdeb-7.2.1.js to pouchdb.js. I don't think that makes a difference.\n- Unfortunately the hint did not bring any enlightenment. As I have written, the problem occurs already with a one-line-page. All lines return error messages. And I have tried many more variants: import PouchDB from '$lib/pouchdb.js'; import PouchDB from 'pouchdb-browser'; import PouchDB from 'pouchdb';\n- I spun up the canned sveltekit app and then I did `npm i pouchdb-browser`, `npm i pouch-adapter-memory`, and just used e.g. `import PouchDB from \"pouchdb-browser\"`. Looked ok but am getting the dreaded \"global is not defined\". Likely related to some global/globalThis madness (I am not familiar with svelte). I should think npm should just work.\n- Yes, I also got this error message when I tried. Maybe someone with detailed knowledge of SvelteKit and PouchDB could take a look.\n- this tut: neighbourhood.ie/blog/2019/05/10/…\n- Thank you for this workaround. i tried using onMount, but apparently wasn't quite on the right track.\n- Thanks! Works for me in Svelte but instead of 'onMount' I needed to bind a custom function 'db_library_loaded' to the on:load event, e.g.,","metadata":{"transformedAt":"2026-08-18T18:33:40.687Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":203,"estimatedTokens":1302}}369{"id":"stack-62115704","source":"stackoverflow","questionId":62115704,"title":"Svelte Tabs - Don't reload / destroy data","tags":["javascript","templating","svelte"],"text":"Title: Svelte Tabs - Don't reload / destroy data\nTags: javascript, templating, svelte\nSource: Stack Overflow\n\nQuestion:\nI am using a svelte tabs component that is described here: \n\nhttps://svelte.dev/repl/8e68120858e5322272dc9136c4bb79cc?version=3.5.1\n\nInside two tabs I have the following svelte template code:\n\n```\n\n \n \n {#each value.items as item, i}\n \n {/each}\n \n\n```\n\nEvery time I click on the tabs to switch between the data, it seems to reload or rebuild it. How can I adjust the tab component so that it's not destroying the data each time?\n\n========================================\n\nCode:\n```text\n<TabPanel>\n <Filter/>\n <div id='to-filter' class='scroll-container'>\n {#each value.items as item, i}\n <Item \n itemFilter={item.name} \n itemDay={item.itemDay} \n itemMonth={item.itemMonth} \n itemYear={item.itemYear} \n itemCity={item.itemCity} \n itemCountry={item.itemCountry} \n itemVenue={item.venue}\n itemLink={item.link}\n itemDotw={itemDatesOnly[i].itemDotw}\n />\n {/each}\n </div>\n</TabPanel>\n```\n\n```text\n{#if $selectedPanel === panel}\n <slot></slot>\n{/if}\n```\n\n```text\n<div hidden={$selectedPanel !== panel}>\n <slot></slot>\n</div>\n```\n\n```text\nhidden\n```\n\n========================================\n\nComments:\n- this is great! thank you so much!!! if i wanted to add in a fade in / out when switching tabs would that also be possible? so when one is completed fading out the other fades in ?\n- I am not sure if it is possible to use Svelte's transitions / animations without actually re-rendering a component. So you might have to resort to using CSS transitions or animations that get triggered based on a conditional class. You could add this class by using the class directive: svelte.dev/tutorial/classes","metadata":{"transformedAt":"2026-08-18T18:33:40.687Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":69,"estimatedTokens":477}}370{"id":"stack-72586711","source":"stackoverflow","questionId":72586711,"title":"Svelte dynamic multiple component array","tags":["typescript","svelte"],"text":"Title: Svelte dynamic multiple component array\nTags: typescript, svelte\nSource: Stack Overflow\n\nQuestion:\nEDIT: REPL for answer https://svelte.dev/repl/eb7616fd162a4829b14a778c3d1627e4?version=3.48.0\n\nWhat I'm talking would render this:\n\nFirst we have a button:\n\n```\n Add \n\n```\n\nWhen I click it, this should happen:\n\n```\n Add \n\ncomp1 (instance1) \ncomp2 (instance1)\n\n```\n\nWhen I click it again, another row gets added (with new instances):\n Add \n\n```\n\ncomp1 (instance1) \ncomp2 (instance1)\n\ncomp1 (instance2)\ncomp2 (instance2)\n\n```\n\nThere is an interface:\n\n```\nexport interface complexObject {\n comp1 : ComplexObj1\n comp2: ComplexObj2\n}\n\nlet row: complexObject[] = []\n```\n\nAdd function:\n\n```\nfunction add(){ \n let newObj:complexObject = {\n comp1: new Comp1({target: div}), // I have to add a target here, or I get compile error, but how since the element doesn't exist?\n comp2: new Comp2({target: div})\n }\n\n row.push(newObj);\n}\n```\n\nI would use this way of doing it, but I can't since I'm getting compile error without adding target:\n\n```\n{#each row as rowitem }\n\n \n {rowitem.comp1}\n {rowitem.comp2}\n \n \n{/each}\n```\n\nEdit: It turns out that the styling gets applied correctly when I add the target as the html specified in the render as so:\n\nAdd function:\n\n```\nfunction add(){ \n let div = document.createElement(\"div\");\n div.setAttribute('class',\"row\")\n\n let newObj:complexObject = {\n comp1: new Comp1({target: div}),\n comp2: new Comp2({target: div})\n }\n\n row.push(newObj);\n}\n\n{#each row as rowitem }\n\n {rowitem.comp1}\n {rowitem.comp2}\n \n \n\n{/each}\n```\n\nNow the problem is that the components do not get rendered, what I get instead is\n\n```\n[object Object] [object Object]\n```\n\nWhen I try to render as such:\n\n```\n\n \n```\n\nI get error:\n\n```\nTypeError: l is not a constructor\n```\n\nIf I try to modify Add function and remove `new` keyword I get this:\n\n```\nType 'typeof comp1__SvelteComponent_' is missing the following properties from type 'comp1__SvelteComponent_': $$prop_def, $$events_def, $$slot_def, $on, and 5 more.ts(2740)\n```\n\nTurns out that this is a problem with specifying the interface, it should be specified like so:\n\n```\nexport interface complexObject {\n comp1 : typeof ComplexObj1\n comp2: typeof ComplexObj2\n}\n```\n\n========================================\n\nTop Answer:\nIf you need a reference to a DOM element, you can either query it inside `onMount` or set a reference to a variable via `bind:this` (then as well defined/accessible inside onMount) REPL\n\n```\n\n import {onMount} from 'svelte'\n import Comp from './Comp.svelte'\n let container\n \n onMount(() => {\n const containerRef = document.getElementById('container')\n console.log(containerRef, container)\n const c = new Comp({target: container})\n })\n\n```\n\n(You query `getElementByID` but your outer element has `class=\"columnflexbox\"` and do you iterate `newObjs` or `row`? Because first is an object and can't be directly iterated I think...)\n\n========================================\n\nCode:\n```text\n<button on:click={add}> Add </button>\n<div id=\"columnflexbox\">\n```\n\n```text\n<button on:click={add}> Add </button>\n<!-- This exists in DOM-->\n<div id=\"columnflexbox\">\n\n<!-- This div and components get rendered, the Div does not exist in DOM -->\n<div class=\"row\" style=\"display:flex;flex-direction:row\">\ncomp1 (instance1) \ncomp2 (instance1)\n</div>\n```\n\n```text\n<div id=\"columnflexbox\">\n\n\n<div class=\"row\" style=\"display:flex;flex-direction:row\">\ncomp1 (instance1) \ncomp2 (instance1)\n</div>\n<!-- Second div is generated, it does not exist in DOM, new instances of components -->\n<div class=\"row\" style=\"display:flex;flex-direction:row\">\ncomp1 (instance2)\ncomp2 (instance2)\n</div>\n\n\n</div>\n```\n\n```text\nexport interface complexObject {\n comp1 : ComplexObj1\n comp2: ComplexObj2\n}\n\nlet row: complexObject[] = []\n```\n\n```text\nfunction add(){ \n let newObj:complexObject = {\n comp1: new Comp1({target: div}), // I have to add a target here, or I get compile error, but how since the element doesn't exist?\n comp2: new Comp2({target: div})\n }\n\n row.push(newObj);\n}\n```\n\n```text\n{#each row as rowitem }\n\n <div class=\"row\">\n {rowitem.comp1}\n {rowitem.comp2}\n </div>\n \n{/each}\n```\n\n```text\nfunction add(){ \n let div = document.createElement(\"div\");\n div.setAttribute('class',\"row\")\n\n\n let newObj:complexObject = {\n comp1: new Comp1({target: div}),\n comp2: new Comp2({target: div})\n }\n\n row.push(newObj);\n}\n\n\n{#each row as rowitem }\n<div class=\"row\">\n {rowitem.comp1}\n {rowitem.comp2}\n</div> \n \n\n{/each}\n```\n\n```text\n[object Object] [object Object]\n```\n\n```text\n<svelte:component this={rowitem.comp1}>\n\n </svelte:component>\n```\n\n```text\nTypeError: l is not a constructor\n```\n\n```text\nType 'typeof comp1__SvelteComponent_' is missing the following properties from type 'comp1__SvelteComponent_': $$prop_def, $$events_def, $$slot_def, $on, and 5 more.ts(2740)\n```\n\n```text\nexport interface complexObject {\n comp1 : typeof ComplexObj1\n comp2: typeof ComplexObj2\n}\n```\n\n```text\nnew\n```\n\n```html\n<script>\n import Comp from './Comp.svelte';\n \n let components = [\n [Comp, { content: 'Initial' }],\n [Comp, { content: 'Initial 2' }],\n ];\n function add(component, props) {\n components = [...components, [component, props]];\n }\n</script>\n\n<button type=button on:click={() => add(Comp, { content: 'Added' })}>\n Add\n</button>\n\n{#each components as [component, props]}\n <svelte:component this={component} {...props}>\n (Slotted content)\n </svelte:component>\n{/each}\n```\n\n```html\n<script lang=\"ts\">\n import type { SvelteComponent, SvelteComponentTyped } from 'svelte';\n import Comp from './Comp.svelte';\n import Comp2 from './Comp2.svelte';\n \n let components: [typeof SvelteComponent, Record<string, any>][] = [\n [Comp, { content: 'Initial' }],\n [Comp2, { color: 'blue' }],\n ];\n function add<T extends typeof SvelteComponentTyped<P, any, any>, P>(\n component: T,\n props: P\n ) {\n components = [...components, [component, props]];\n }\n</script>\n```\n\n```text\nsvelte:component\n```\n\n```text\nadd\n```\n\n```text\n<script>\n import {onMount} from 'svelte'\n import Comp from './Comp.svelte'\n let container\n \n onMount(() => {\n const containerRef = document.getElementById('container')\n console.log(containerRef, container)\n const c = new Comp({target: container})\n })\n</script>\n\n<div id=\"container\" bind:this={container} />\n```\n\n```text\nonMount\n```\n\n```text\nbind:this\n```\n\n```text\ngetElementByID\n```\n\n```text\nclass=\"columnflexbox\"\n```\n\n```text\nnewObjs\n```\n\n```text\nrow\n```\n\n========================================\n\nComments:\n- *\" what I get instead is [object Object]\"* This is because with `comp1: new Comp1({target: div})` comp1 holds a reference to the component which can't be used to create it in the html part. Have a look at this REPL\n- Thank you for pushing me in the right direction, but this answer is in JS and while I understand most of it, I'm trying to find a solution specific to typescript.\n- Adding types would not make this any easier to understand, if anything, it would be more complicated. If you want to type this with a high level of accuracy you need to employ generics and use inferred generic typing for the component properties. Not sure if that would really be worth the trouble.\n- You might be correct, I do quite often get stuck with this kind of stuff because of using typescript, and every time think it's not worth the trouble. But I do like to create custom types between the server and client as it makes easier to keep track of things.\n- @sander: Added an example with some typing...\n- Sorry, those were typos from typing the question. Edited my question.\n- @sander No problem. Does it help you with your case? *\"The problem is that the div class \"row\" doesn't exist in dom so it can't be set as the target in the initialization of the component.\"*\n- @sander *\" In vanilla JS I would just create the object in the dom ...\"* If the element doesn't exist yet, you can also just create it in Svelte like with in js ~ see the updated REPL\n- Updated the answer to format the question better.\n- @sander I see, so I think H.B.'s answer covers this. Use `` instead of `new Comp()` svelte.dev/repl/eb7616fd162a4829b14a778c3d1627e4?version=3.4‌​8.0","metadata":{"transformedAt":"2026-08-18T18:33:40.688Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":385,"estimatedTokens":2098}}371{"id":"stack-62017974","source":"stackoverflow","questionId":62017974,"title":"How can I set a background image with svelte?","tags":["javascript","date","desktop-application","svelte","datefield"],"text":"Title: How can I set a background image with svelte?\nTags: javascript, date, desktop-application, svelte, datefield\nSource: Stack Overflow\n\nQuestion:\nHow can I set a background image with svelte?\n\nThe code is here for reference: Svelte sandbox\n\n========================================\n\nCode:\n```text\n:global(body){\n background-color: lightseagreen;\n background-image: url(\"https://images.pexels.com/photos/956981/milky-way-starry-sky-night-sky-star-956981.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260\");\n }\n```\n\n```text\nstyle\n```\n\n```text\nTodos.svelte\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.688Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":26,"estimatedTokens":145}}372{"id":"stack-50043557","source":"stackoverflow","questionId":50043557,"title":"Lazy load images in (svelte/sapper)","tags":["svelte"],"text":"Title: Lazy load images in (svelte/sapper)\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nWhat would be best way to do this kind of lazy loading in Sapper:\n\n- Navigate to page containing image\n\n- First download small image from src\nStart loading larger version from data-src and change that to src\nwhen ready\n\n- Navigate to another page\n\n- Come back to image page and have already loaded larger image there\n\nIf someone could help, I would be very happy :)\n\n========================================\n\nCode:\n```js\n<img\n alt=\"random photo\"\n src=\"https://picsum.photos/100/50\"\n use:lazy=\"{src: 'https://picsum.photos/400/200'}\"\n>\n\n<style>\n img {\n width: 400px;\n height: 200px;\n }\n</style>\n\n<script>\n const loaded = new Map();\n\n export default {\n actions: {\n lazy(node, data) {\n if (loaded.has(data.src)) {\n node.setAttribute('src', data.src);\n } else {\n // simulate slow loading network\n setTimeout(() => {\n const img = new Image();\n img.src = data.src;\n img.onload = () => {\n loaded.set(data.src, img);\n node.setAttribute('src', data.src);\n };\n }, 2000);\n }\n\n return {\n destroy(){} // noop\n };\n }\n }\n };\n</script>\n```\n\n```text\ndestroy\n```\n\n```text\nupdate\n```\n\n========================================\n\nComments:\n- Do we have a better way to do this in V3?\n- You can use the exact same technique svelte.dev/repl/26ba12b3fbd146eaaefc8b024a826da7?version=3.5‌​.1\n- @RichHarris I know this is very old post, though based on the REPL, it's actually the same scenario I had, actually the approach I used is to use [await, then], however it requests twice, similar to what you have in the REPL, is there anyway to prevent it from requesting twice in a minimal way of coding?","metadata":{"transformedAt":"2026-08-18T18:33:40.688Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":79,"estimatedTokens":464}}373{"id":"stack-72483848","source":"stackoverflow","questionId":72483848,"title":"How can I get all files in a directory with svelte?","tags":["svelte"],"text":"Title: How can I get all files in a directory with svelte?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI want to show all images in a folder, like:\n\n```\n\n let list = /*array of all files in a folder*/;\n\n{#each list as l}\n \n{/each}\n```\n\nHow can I get that 'list' and paths of its elements?\n\n========================================\n\nCode:\n```text\n<script>\n let list = /*array of all files in a folder*/;\n</script>\n\n{#each list as l}\n <img src={(path_of_l)} alt=\"\"/>\n{/each}\n```\n\n```js\nconst imageModules = import.meta.glob(\"../../static/*.jpg\");\n\n for (const modulePath in imageModules) {\n imageModules[modulePath]().then(({ default: imageUrl }) => {\n console.log(modulePath, imageUrl);\n });\n }\n```\n\n========================================\n\nComments:\n- That depends on how you run your application. If this runs directly in the browser you first need to ask for permission to access the disk, and the user has to select the directory (also browser support for this will be limited). If you have a desktop application, it depends on what it is running on (e.g. Tauri or Electron).\n- If its about images inside your project folder look into vitejs.dev/guide/features.html#glob-import\n- Right, if the files are static and supposed to be known at build time, you need to get the paths in a way specific to the build system you are using.\n- @BobFanger Thank you so much! That is what I wanted exactly.\n- Thanks for the answer. I am doing a similar thing with svelte components. Do you know if you can render the components from the list inside the for-loop?\n- @brendangibson Yes, using {#each} and nested {#await} or without {#await} if you're using SvellteKit: load and await the components in a +page.js file because the components are then also rendered during SSR.\n- @BobFanger can you take a look at his question regarding the components issue: stackoverflow.com/questions/78955169/…","metadata":{"transformedAt":"2026-08-18T18:33:40.688Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":51,"estimatedTokens":478}}374{"id":"stack-51523499","source":"stackoverflow","questionId":51523499,"title":"How do I reference a Svelte component's parent component?","tags":["javascript","svelte","svelte-component","svelte-2"],"text":"Title: How do I reference a Svelte component's parent component?\nTags: javascript, svelte, svelte-component, svelte-2\nSource: Stack Overflow\n\nQuestion:\nPer the Svelte documentation on Props I am using props to pass a reference to the parent component to a child. \n\n Props, short for 'properties', are the means by which you pass data down from a parent to a child component \n\nThat's exactly what I want to do. Here is a Svelte REPL with my code, that is also copied below:\n\nMy parent is **App.html**:\n\n```\n\n \n\n import Widget from './Widget.html';\n\n export default {\n data: function(){ \n return {\n baz: 'click me and check the console'\n }\n },\n components: {\n Widget\n }\n };\n\n```\n\nThe child component is **Widget.html**:\n\n```\nfoo: {foo}\n\nbar: {bar}\n\nbaz: {baz}\n\n export default {\n oncreate: function(){\n window.document.body.addEventListener('click', function(event){\n console.log(`Clicked!, ${baz}`)\n });\n }\n }\n\n```\n\nThanks to the props, the HTML `` elements can clearly reference the parent. However **how can I reference the values in the parent component in the child component's JavaScript?**\n\n========================================\n\nCode:\n```text\n<div class='widget-container'>\n <Widget foo bar=\"static\" {baz}/>\n</div>\n\n<script>\n import Widget from './Widget.html';\n\n export default {\n data: function(){ \n return {\n baz: 'click me and check the console'\n }\n },\n components: {\n Widget\n }\n };\n</script>\n```\n\n```text\n<p>foo: {foo}</p>\n<p>bar: {bar}</p>\n<p>baz: {baz}</p>\n\n<script>\n export default {\n oncreate: function(){\n window.document.body.addEventListener('click', function(event){\n console.log(`Clicked!, ${baz}`)\n });\n }\n }\n\n</script>\n```\n\n```text\n<p>\n```\n\n```html\n<p>foo: {foo}</p>\n<p>bar: {bar}</p>\n<p>baz: {baz}</p>\n\n<script>\n export default {\n oncreate: function(){\n window.document.body.addEventListener('click', () => {\n const { baz } = this.get();\n console.log(`Clicked!, ${baz}`)\n });\n }\n }l\n</script>\n```\n\n```text\nthis.get()\n```\n\n========================================\n\nComments:\n- Thanks. Didn't realise `this.get()` travelled up to parents. 🙂\n- To be specific, and to avoid confusing anyone else who sees this answer 😀: It doesn't travel up to parents — it's getting its *own* data, but that includes `baz` because it was passed down from the parent\n- Hrm, it looks like that's a second copy of the data. How do I reference the parent's data, not make a second copy?\n- if you want to manipulate the parents data in a child component you should use bind like this in your App.html `bind:baz={baz}` or even the shorthand `bind:{baz}`","metadata":{"transformedAt":"2026-08-18T18:33:40.688Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":126,"estimatedTokens":693}}375{"id":"stack-72742588","source":"stackoverflow","questionId":72742588,"title":"How to use Swiper JS method in Svelte","tags":["svelte","swiper.js"],"text":"Title: How to use Swiper JS method in Svelte\nTags: svelte, swiper.js\nSource: Stack Overflow\n\nQuestion:\nI want to use slideNext() method in Swiper JS. However, from the documentation of Swiper JS for Svelte, there is no example on showing how to access to method in Svelte. In React, there is a hook called useSwiper but no such thing in Svelte. Does anyone know how?\n\n========================================\n\nTop Answer:\nSince Swiper JS no longer supports Svelte directly (and soon will probably drop support for all other frameworks), we should now use Swiper as a custom HTML element (web component) Swiper component. Below is an example of how to use Swiper in Svelte:\n\n```\n// App.svelte\n\n import { register } from 'swiper/element/bundle';\n register(); // register swiper components\n\n // ...\n\n// SomeComponent.svelte\n\nimport {type SwiperContainer} from 'swiper/element/bundle';\nimport {onMount} from \"svelte\";\n\nlet swiperEl: SwiperContainer|undefined;\nlet swiperNextElem: HTMLElement|undefined;\nlet swiperPrevElem: HTMLElement|undefined;\nonMount(() => {\n if(swiperEl != undefined && swiperNextElem != undefined && swiperPrevElem != undefined) {\n const swiperParams = {\n navigation: {\n nextEl: swiperNextElem,\n prevEl: swiperPrevElem,\n },\n slidesPerView: 1,\n loop: true,\n }\n\n // now we need to assign all parameters to Swiper element\n Object.assign(swiperEl, swiperParams);\n\n // and now initialize it\n swiperEl.initialize();\n }\n});\n\n \n CUSTOM ELEMENT\n CUSTOM ELEMENT\n CUSTOM ELEMENT\n \n\n Prev\n Next\n\n```\n\n========================================\n\nCode:\n```html\n<script>\n // ...\n let swiper;\n</script>\n\n<Swiper on:swiper={e => swiper = e.detail[0]}>\n <SwiperSlide>Slide 1</SwiperSlide>\n <SwiperSlide>Slide 2</SwiperSlide>\n <SwiperSlide>Slide 3</SwiperSlide>\n</Swiper>\n\n<button type=button on:click={() => swiper.slidePrev()}>Previous</button>\n<button type=button on:click={() => swiper.slideNext()}>Next</button>\n```\n\n```text\nswiper\n```\n\n```text\n// App.svelte\n<script lang=\"ts\">\n import { register } from 'swiper/element/bundle';\n register(); // register swiper components\n\n // ...\n</script>\n\n\n\n// SomeComponent.svelte\n<script lang=\"ts\">\nimport {type SwiperContainer} from 'swiper/element/bundle';\nimport {onMount} from \"svelte\";\n\nlet swiperEl: SwiperContainer|undefined;\nlet swiperNextElem: HTMLElement|undefined;\nlet swiperPrevElem: HTMLElement|undefined;\nonMount(() => {\n if(swiperEl != undefined && swiperNextElem != undefined && swiperPrevElem != undefined) {\n const swiperParams = {\n navigation: {\n nextEl: swiperNextElem,\n prevEl: swiperPrevElem,\n },\n slidesPerView: 1,\n loop: true,\n }\n\n // now we need to assign all parameters to Swiper element\n Object.assign(swiperEl, swiperParams);\n\n // and now initialize it\n swiperEl.initialize();\n }\n});\n</script>\n\n\n<div>\n <swiper-container init=\"false\" bind:this={swiperEl}>\n <swiper-slide><div>CUSTOM ELEMENT</div></swiper-slide>\n <swiper-slide><div>CUSTOM ELEMENT</div></swiper-slide>\n <swiper-slide><div>CUSTOM ELEMENT</div></swiper-slide>\n </swiper-container>\n\n <div bind:this={swiperPrevElem}>Prev</div>\n <div bind:this={swiperNextElem}>Next</div>\n</div>\n```\n\n========================================\n\nComments:\n- Thank you so much for the answer. I have marked your answer as the correct answer.","metadata":{"transformedAt":"2026-08-18T18:33:40.688Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":137,"estimatedTokens":855}}376{"id":"stack-69020710","source":"stackoverflow","questionId":69020710,"title":"Fall back image with SvelteKit","tags":["javascript","svelte","sveltekit"],"text":"Title: Fall back image with SvelteKit\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI got started with Svelte(Kit) and I really like it so far. However, I ran into an issue that I couldn't resolve.\n\nI'm trying to dynamically display images and like to have a fall back image in case the normal one does not exist.\n\nWith vanilla HTML/JS, I would use this Source:\n\n```\n\n```\n\nI tried to make it happen in my Svelte project, but it either does not work (e.g. A) or it works sometimes (for a brief moment or until I refresh (e.g. B)).\n\nThis is my code (A):\n\n```\n\nlet profileImg = person.profile;\nconst missingProfile = () => {\n console.log('image does not exist');\n profileImg = '../default.png';\n};\n\n...\n\n```\n\nor just the hardcoded version (B)\n\n```\n\n```\n\nThere is this question, but I believe the answer is what I am doing. Is there a difference whether I use SvelteKit vs. Svelte?\n\n### Addition\n\nIt looks like that Svelte does not even set the `src` for the ``, if the original variable with the url for the image is `undefined` (in my example `person.profile`). The accepted answer wouldn't work in that case.\n\nI edited this line to prevent that case:\n\n```\nlet profileImg = person.profile === undefined ? '../default.png' : person.profile;\n```\n\n========================================\n\nTop Answer:\nIn my case, I wanted to display a different element when the image was not found. With the help I found on this page about using `on:error={}`, I was able to do this:\n\n```\n{#if image}\n image = undefined}\n >\n{:else}\n ... \n{/if}\n```\n\nThis way I can handle both scenarios: when the image is not set, and when the image is set but not found. In the event that the image is set but not found, the `image` variable will be set to `undefined` and Svelte will then use the `:else` part and display my other element.\n\n========================================\n\nCode:\n```text\n<img src=\"imagefound.gif\" onerror=\"this.onerror=null;this.src='imagenotfound.gif';\" />\n```\n\n```text\n<script>\nlet profileImg = person.profile;\nconst missingProfile = () => {\n console.log('image does not exist');\n profileImg = '../default.png';\n};\n</script>\n\n...\n\n<img\n src={profileImg}\n on:error={missingProfile}\n alt={person.name}\n/>\n```\n\n```text\n<img \n src=\"imagefound.gif\" \n onerror=\"console.log('image not found');this.onerror=null;this.src='./person.png';\" \n/>\n```\n\n```text\nlet profileImg = person.profile === undefined ? '../default.png' : person.profile;\n```\n\n```text\nsrc\n```\n\n```text\n<img />\n```\n\n```text\nundefined\n```\n\n```text\nperson.profile\n```\n\n```html\n<script>\n let fallback = 'http://placekitten.com/200/200'\n let image = \"\"\n \n const handleError = ev => ev.target.src = fallback\n</script>\n\n<img src={image} alt=\"\" on:error={handleError}>\n```\n\n```text\n{#if image}\n <img\n class=\"image\"\n src={image.url}\n alt=\"...\"\n on:error={() => image = undefined}\n >\n{:else}\n <div class=\"fallback\"> ... </div>\n{/if}\n```\n\n```text\non:error={}\n```\n\n```text\nimage\n```\n\n```text\nundefined\n```\n\n```text\n:else\n```\n\n========================================\n\nComments:\n- concerning your addition: yes this is correct, the svelte compiler does not add the attributes if the value is undefined","metadata":{"transformedAt":"2026-08-18T18:33:40.688Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":161,"estimatedTokens":809}}377{"id":"stack-72968759","source":"stackoverflow","questionId":72968759,"title":"Svelte App Won't Render my Data in the Browser","tags":["javascript","json","rest","svelte","sveltekit"],"text":"Title: Svelte App Won't Render my Data in the Browser\nTags: javascript, json, rest, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm pretty new to Svelte and I'm trying to render my data object in the browser. I'm not sure what's going on as the backend seems to be okay and I'm able to print the data object in the console.\n\nI have a backend flask api that reads the following url\n\nhttps://api.le-systeme-solaire.net/rest/bodies/\n\nThat's up and working fine. If you look it up you can see what the json looks like\n\nThis is the top half of my index.svelte file:\n\n```\n\nlet data = []\n\nasync function initFetchSolarSystemData() {\n let response = await fetch(\"http://127.0.0.1:5000/solar-system/gravity\");\n data = await response.json();\n\nconsole.log(\"data\", data)\nconsole.log([\"id\", data.bodies[0].id])\nconsole.log([\"gravity\", data.bodies[0].gravity])\nconsole.log([\"bodies\", data.bodies.length])\n}\n\ninitFetchSolarSystemData()\n\n```\n\nSo when it runs, I can see values in the console like:\n\n```\n['id', 'lune']\n['gravity', 1.62]\n'bodies', 287]\n```\n\nSo that seems to be working fine as well. Here is the bottom portion of the file where I believe the error is stemming from:\n\n```\n\n {#if data.length}\n {#each data.bodies as item}\n\n \n \n {item.gravity}\n \n \n\n {/each}\n {/if}\n\n```\n\nWhen the I run the script, I get no errors in the console. Nothing renders. If I replace this line:\n\n```\n{#if data.length}\n```\n\nwith\n\n```\n{#if data.bodies.length}\n```\n\nI get:\n\n```\nCannot read properties of undefined (reading 'length')\n```\n\nWhich I'm confused about because these values are being read earlier above in the file.\n\nI think I'm missing something here, and any help would be immensely appreciated.\n\n========================================\n\nTop Answer:\nThe real issue here is that you are mixing types.\n\nWith `{#if data.length}`, you are checking the *length* property of *data*, which initially is an array of length **0**, so it doesn't render the if block.\n\nThen in your function you assign an **object** to data instead of an **array** as it was before. Now `data.length` will be *undefined* because your object doesn't have a property '*length*' and your if block doesn't render.\n\nYou are getting close with your idea of checking `data.bodies.length` because that is indeed the array you want to check. But you get into an error because your initial array doesn't have `bodies` so you can't read the length of it.\n\n### 2 Solutions\n\nA first solution would be the initialize `data` to be similar to what you expect from the API:\n\n```\nlet data = { bodies: [] }\n```\n\nthen you can do `{#if data.bodies.length}`\n\nAnother solution is to actually only use the `bodies` part:\n\n```\nconst result = await fetch(...).then(res => res.json());\ndata = result.bodies;\n```\n\nand then `data` is an array with all your bodies, so use `{#each data as item}` instead.\n\n========================================\n\nCode:\n```text\n<script>\n\nlet data = []\n\nasync function initFetchSolarSystemData() {\n let response = await fetch(\"http://127.0.0.1:5000/solar-system/gravity\");\n data = await response.json();\n\nconsole.log(\"data\", data)\nconsole.log([\"id\", data.bodies[0].id])\nconsole.log([\"gravity\", data.bodies[0].gravity])\nconsole.log([\"bodies\", data.bodies.length])\n}\n\ninitFetchSolarSystemData()\n\n</script>\n```\n\n```text\n['id', 'lune']\n['gravity', 1.62]\n'bodies', 287]\n```\n\n```text\n<section>\n\n {#if data.length}\n {#each data.bodies as item}\n\n <div class=\"gravity\">\n <h1 id=\"item\">\n {item.gravity}\n </h1>\n </div>\n\n {/each}\n {/if}\n\n</section>\n```\n\n```text\n{#if data.length}\n```\n\n```text\n{#if data.bodies.length}\n```\n\n```text\nCannot read properties of undefined (reading 'length')\n```\n\n```js\n{#await initFetchSolarSystemData()}\n <p>Loading…</p>\n {:then data}\n …\n {:catch error}\n <p>Uh oh, an error.</p>\n {/await}\n```\n\n```js\nlet data = { bodies: [] }\n{#if data.bodies.length}\n```\n\n```text\n{#if data.bodies?.length}\n```\n\n```text\nArray\n```\n\n```text\nObject\n```\n\n```text\n{#if data.length}\n```\n\n```text\n{#if data.bodies?.length}\n```\n\n```text\n{#if data.length}\n```\n\n```text\ndata\n```\n\n```text\n#if\n```\n\n```text\n0\n```\n\n```text\n{#if data.length}\n```\n\n```text\n{#if data.bodies.length}\n```\n\n```text\ndata.bodies\n```\n\n```text\nlength\n```\n\n```text\nfetch\n```\n\n```text\ndata\n```\n\n```text\nObject\n```\n\n```text\n{#if data.length}\n```\n\n```text\nundefined\n```\n\n```text\nfetch\n```\n\n```text\ndata\n```\n\n```text\nObject\n```\n\n```text\nArray\n```\n\n```text\n#if\n```\n\n```text\ndata.bodies\n```\n\n```text\ndata\n```\n\n```text\n<section>…</section>\n```\n\n```text\nawait\n```\n\n```text\ninitFetchSolarSystemData()\n```\n\n```text\nreturn\n```\n\n```text\ndata\n```\n\n```text\ninitFetchSolarSystemData()\n```\n\n```text\n<script>…</script>\n```\n\n```text\nfalse\n```\n\n```text\n#if\n```\n\n```text\n#each\n```\n\n```text\nfetch\n```\n\n```text\nfetch\n```\n\n```text\ndata\n```\n\n```text\ndata\n```\n\n```text\nbodies\n```\n\n```js\nlet data = { bodies: [] }\n```\n\n```js\nconst result = await fetch(...).then(res => res.json());\ndata = result.bodies;\n```\n\n```text\n{#if data.length}\n```\n\n```text\ndata.length\n```\n\n```text\ndata.bodies.length\n```\n\n```text\nbodies\n```\n\n```text\ndata\n```\n\n```text\n{#if data.bodies.length}\n```\n\n```text\nbodies\n```\n\n```text\ndata\n```\n\n```text\n{#each data as item}\n```\n\n========================================\n\nComments:\n- Using the `#await` is a very good proposal, but your problem description is wrong, if the OP would have assigned an actual `Array` instead of an `Object` their code would have worked as expected since Svelte will pick up that the array changed, regardless of it being async.\n- @StephaneVanraes Indeed, thank you very much! If only the `#if` was changed to `{#if data.bodies?.length}`, Svelte would handle the rest. I've updated my answer and added a demo for this.","metadata":{"transformedAt":"2026-08-18T18:33:40.688Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":59,"totalLines":395,"estimatedTokens":1439}}378{"id":"stack-70962059","source":"stackoverflow","questionId":70962059,"title":"How to rerender {#each array} block in svelte after you push something to an array","tags":["javascript","svelte"],"text":"Title: How to rerender {#each array} block in svelte after you push something to an array\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nHello I'm making a comment section for my website which works but when I push an object to an array my `{#each}` block doesn't update here is this block of code\n\n```\n{#each commentsScript as { userName, rating, comment }, i}\n \n \n \n\n### {userName}\n\n \n\n### {rating}\n\n \n \n {comment}\n\n \n \n {/each}\n```\n\nIn my script section, I push a new comment to an array and it does show up after I refresh the page but I want to rerender it as soon as the user leaves a comment so the user would see hes/her own comment so is there any way I can rerender it?\n\n========================================\n\nTop Answer:\nIn addition to reassignment, there are several existing libraries that help you use the Array native APIs.\n\nYou can try this: https://svelte.dev/repl/0dedb37665014ba99e05415a6107bc21?version=3.53.1\n\nuse a library called svelox. It allows you to use the Array native api(push/splice...etc.) without reassignment statements.\n\nBecause it's weird to write a reassignment every time, this is something that every svelte beginner finds strange. Also, using the Array native APIs is not recommended(you should use spread).\n\n========================================\n\nCode:\n```html\n{#each commentsScript as { userName, rating, comment }, i}\n <div class=\"flex\">\n <div class=\"w-1/4\">\n <h5>{userName}</h5>\n <h5>{rating}</h5>\n </div>\n <div class=\"w-3/4\">\n <p>{comment}</p>\n </div>\n </div>\n {/each}\n```\n\n```text\n{#each}\n```\n\n```text\ncommentsScript = commentsScript\n```\n\n========================================\n\nComments:\n- How are you updating the array? Provide code for that.\n- svelte.dev/tutorial/updating-arrays-and-objects You have to assign commentsScript = commentsScript if you are using push function.\n- This doesn't work if the array is shared between components\n- Thanks a lot, saved me a lot of time. Makes sense, as the array itself is not changing, it's not firing a change detection. When you re-set the array, the change is detected!","metadata":{"transformedAt":"2026-08-18T18:33:40.688Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":73,"estimatedTokens":568}}379{"id":"stack-70787043","source":"stackoverflow","questionId":70787043,"title":"Svelte how to bind div inside each lop to obtain a reference using this","tags":["javascript","binding","svelte"],"text":"Title: Svelte how to bind div inside each lop to obtain a reference using this\nTags: javascript, binding, svelte\nSource: Stack Overflow\n\nQuestion:\nI need to get a reference to every div created inside a each loop in svelte, then I'll use the reference to toggle css class of a certain div when the user clicks on previous div.\n\n```\nlet contentOptions;\n \n function handleClick(event) {\n \n contentOptions.classList.toggle(\"close\");\n \n }\n \n {#each items as item, i}\n \n \n \n {item.label}\n \n \n Content Option {i}\n \n {/each}\n```\n\nItems array have three objects, and it always appears the last div with text \"Content Option 2\" despite clicking on another div.\n\nis possible to bind each div separately?\n\n========================================\n\nCode:\n```text\nlet contentOptions;\n \n function handleClick(event) {\n \n contentOptions.classList.toggle(\"close\");\n \n }\n \n {#each items as item, i}\n \n <div class=\"titleOption\" on:click={handleClick}>\n <img src=\"./assets/{item.icon}\"/>\n <span>{item.label}</span>\n </div>\n \n <div class=\"content close\" bind:this={contentOptions}>Content Option {i}</div>\n \n {/each}\n```\n\n```text\n<script>\n const items = [{label: 'item1'}, {label: 'item2'}]\n let contentOptions = [];\n\n function handleClick(index) {\n contentOptions[index].classList.toggle(\"close\");\n }\n</script>\n\n{#each items as item, i}\n\n<div class=\"titleOption\" on:click={() => handleClick(i)}>\n <span>{item.label}</span>\n</div>\n\n<div class=\"content close\" bind:this={contentOptions[i]}>Content Option {i}</div>\n\n{/each}\n\n<style>\n .close {\n background: red;\n }\n</style>\n```\n\n```text\n<script>\n const items = [{label: 'item1'}, {label: 'item2'}]\n\n function handleClick(event) {\n event.currentTarget.nextElementSibling.classList.toggle('close')\n }\n</script>\n\n{#each items as item, i}\n\n<div class=\"titleOption\" on:click={handleClick}>\n <span>{item.label}</span>\n</div>\n\n<div class=\"content close\">Content Option {i}</div>\n\n{/each}\n\n<style>\n .close {\n background: red;\n }\n</style>\n```\n\n```text\ncontentOptions\n```\n\n```text\nbind:this={contentOptions[i]}\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.688Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":116,"estimatedTokens":544}}380{"id":"stack-72296342","source":"stackoverflow","questionId":72296342,"title":"Best way to handle Svelte component props","tags":["javascript","tailwind-css","svelte","sveltekit"],"text":"Title: Best way to handle Svelte component props\nTags: javascript, tailwind-css, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm building an app using SvelteKit and Tailwind. I know that when using Tailwind to style it is recommended to leverage components to reduce the amount of repeated code you have to write using Tailwinds utility classes. My issue is that when making components based on HTML tags, for instance an `` tag, dealing with props in that component that would normally just be attributes for that tag is getting overwhelming. MDN shows that the `` tag has 31 possible attributes. I know that I won't be using all of them but going back and forth and adding them as props to a component is getting tiresome.\n\nWhat is the best way to solve this problem without adding up to 31 lines of `export let attribute` to a component and adding them to the **real** HTML tag inside of the component?\n\nExample:\n\n```\n\n export let name;\n export let id;\n export let type;\n export let disabled;\n export let required;\n export let minLength;\n export let maxLength;\n export let min;\n export let max;\n export let pattern;\n\n let value;\n let borderColor = '#D1D5DB';\n\n const inputHandler = (e) => {\n if (e.target.value === '') {\n borderColor = '#D1D5DB';\n } else {\n borderColor = '';\n }\n };\n\n```\n\n========================================\n\nTop Answer:\nIf you want to be able to do\n\n```\n\n```\n\nWithout having to declare all these extra attribute, the best way to do so is to use the `$$restProps`, this object will contain all the props that have been passed to the component but have not been explicitly defined as props (exported).\n\n```\n\n export let name = \"\";\n\n```\n\n(here `name` was defined, so it will not be included in `$$restProps` and I had to add it myself)\n\n========================================\n\nCode:\n```text\n<script>\n export let name;\n export let id;\n export let type;\n export let disabled;\n export let required;\n export let minLength;\n export let maxLength;\n export let min;\n export let max;\n export let pattern;\n\n let value;\n let borderColor = '#D1D5DB';\n\n const inputHandler = (e) => {\n if (e.target.value === '') {\n borderColor = '#D1D5DB';\n } else {\n borderColor = '';\n }\n };\n</script>\n\n<input\n {name}\n {id}\n {type}\n {disabled}\n {required}\n {minLength}\n {maxLength}\n {min}\n {max}\n {pattern}\n on:input={inputHandler}\n style={`border-color: ${borderColor}`}\n class=\"\n w-full px-1 py-px mb-4 bg-transparent border-2 border-gray-300 \n rounded-xl last:mb-0 valid:border-emerald-300 invalid:border-rose-400\n \"\n/>\n```\n\n```text\n<input>\n```\n\n```text\n<input>\n```\n\n```text\nexport let attribute\n```\n\n```text\n<script>\n import Input from './Input.svelte';\n\n const options ={\n type: 'number',\n placeholder:'input a number',\n required: true\n };\n</script>\n\n<Input {options} />\n```\n\n```text\n<script>\n export let options = {}\n export let value = ''\n</script>\n\n<input type=\"text\"\n placeholder=\"default placeholder\"\n {...options}\n bind:value\n style:border-color=\"{options.required && value === '' ? 'tomato' : ''}\"\n class=\"w-full px-1 py-px mb-4 bg-transparent border-2 ...\"\n />\n```\n\n```text\n$$restProps\n```\n\n```html\n<MyInputField name=\"123\" maxLength=\"5\" type=\"text\">\n```\n\n```html\n<script>\n export let name = \"\";\n</script>\n\n<input name={name} {..$$restProps}>\n```\n\n```text\n$$restProps\n```\n\n```text\nname\n```\n\n```text\n$$restProps\n```\n\n========================================\n\nComments:\n- you could export an object as prop and then spread it into the `input`\n- @pilchard this is absolutely the way to do it, you should write it up as an answer using your REPL code as a guideline\n- @pilchard The default values which are set on the exported variable get overwritten if the prop is passed on the component. So if just one value should be modified, all the values must be defined again in the parent. To prevent that I would suggest to seperate the default Options into a seperate object and spread both on the input element svelte.dev/repl/52715e3c326349fca4f310060869960b?version=3.4‌​8.0\n- Or probably even better - set the attributes which actually have a default value directly on the input element and spread the options afterwards svelte.dev/repl/062b19cdfc1a45409d66fbd1245609c6?version=3.4‌​8.0\n- @Corrl your last suggestion seems a good way forward, mine was a little off the cuff too late at night.\n- You commented above that @pilchard's way is the one to do it. Is that because of the \"optimisation problems\" the docs state? *\"It shares the same optimisation problems as $$props, and is likewise not recommended\"*\n- That comment was not mine, but yes the optimization is an issue with props and restProps.\n- Oh my fault, both your names come up so often. Sorry for the confusion and thanks for answering!\n- I'm curious, do you think that this would suffer from the same optimization problems as $$restProps since the props aren't explicitly defined? This solution and $$restProps are exactly what I'm looking for, minus the optimization problems and I'm likely going to go with one or the other. I wonder if the optimization problems are referring to props that are reactive and are likely to change a lot, like value or possibly disabled. If so, using this solution or $$restProps wouldn't be a big deal for props such as placeholder or type since they are usually set once and not changed again.\n- Your solution for setting the border color if the value is empty is also much more succinct than my original solution! Thank you for the bonus optimization!\n- @Clarence I was also wondering if the 'kind of props' like you discribe make a difference with the optimization. Unfortunately I don't know enough from 'behind the scenes' yet to be able to tell if there are similar problems with the exported options version","metadata":{"transformedAt":"2026-08-18T18:33:40.688Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":187,"estimatedTokens":1489}}381{"id":"stack-71962807","source":"stackoverflow","questionId":71962807,"title":"Why isn't my svelte {#each} block reactive?","tags":["javascript","html","frameworks","svelte","svelte-component"],"text":"Title: Why isn't my svelte {#each} block reactive?\nTags: javascript, html, frameworks, svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nSo basically I am playing with Svelte trying to spin up a quick app, details of the app aren't important but basically it hosts a bunch of embedded sites. see example here & for replicability:\n\nhttps://svelte.dev/repl/6f3484554ef8489b9a5960487a0a1f95?version=3.47.0\n\nMy problem is that when I add a new url & title to the sites list, the `{#each}` block that creates the embedded views doesn't update to reflect the new state of the list, even though the list is clearly updating in the console output. Is it something to do with scope or is it a Svelte issue of not triggering reactivity on prop reassignments from components?\n\n**Update:** some sites don't allow embedding so use https://wikipedia.org as a safe one for testing.\n\nif you replace a hard-coded url in the sites list with wiki address it should work fine. i basically want a new window to pop up as the `{#each}` block creates a new `SiteView` component\n\n========================================\n\nTop Answer:\nIf you want to change a value from another component you need to `bind` the property, otherwise the relationship is one-way only (from parent component to child).\n\n```\n\n```\n\n========================================\n\nCode:\n```text\n{#each}\n```\n\n```text\n{#each}\n```\n\n```text\nSiteView\n```\n\n```html\n<InputBar bind:sites {site} />\n```\n\n```js\nfunction add() { sites = sites.concat({...site}); console.log(sites)}\n// or alternatively\nfunction add() { sites = [...sites, {...site}]; console.log(sites); }\n```\n\n```html\n<script>\n import { createEventDispatcher } from 'svelte'\n let url = ''\n let title = ''\n const dispatch = createEventDispatcher()\n function add() {\n dispatch('add', { url, title })\n url = ''\n title = ''\n }\n</script>\n<div class=\"rounded\">\n <p>Enter a site to stream:</p>\n <input type=\"text\" placeholder=\"www.example.com\" bind:value={url}>\n <br>\n <input type=\"text\" placeholder=\"example\" bind:value={title}>\n <button on:click={add}>add</button>\n</div>\n```\n\n```html\n<InputBar on:add={(ev) => sites = [...sites, ev.detail]} />\n```\n\n```text\nsites\n```\n\n```text\nbind:\n```\n\n```text\n<svelte:head>\n```\n\n```html\n<InputBar bind:sites {site}/>\n```\n\n```text\nbind\n```\n\n========================================\n\nComments:\n- thank you, you solved my question but Stephane's answer is a little more holistic so i have chosen to mark their's as the accepted answer\n- thank you for the solution & crash course in Svelte haha :)\n- should i do the same with body? use ``?\n- no `svelte:body` is just if you want to add listeners to the body","metadata":{"transformedAt":"2026-08-18T18:33:40.688Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":101,"estimatedTokens":675}}382{"id":"stack-67136240","source":"stackoverflow","questionId":67136240,"title":"Svelte custom button component or style with css","tags":["button","components","themes","svelte"],"text":"Title: Svelte custom button component or style with css\nTags: button, components, themes, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm very new to Svelte and I want to build a theme for a website.\nWhen I want buttons to have a certain look and animations, do I create a new Button component and use that every time with slots or do I just create a class for this button that has some css code and use the standard html button?\n\nOf course I can do it both ways, but which one is preferred in svelte?\n\n========================================\n\nCode:\n```html\n<script>\n import Button from \"./Button.svelte\"\n</script>\n\n\n<Button class=\"primary\">\n My Button\n</Button>\n\n<Button class=\"danger\">\n My Button\n</Button>\n```\n\n```html\n<script>\n let buttonProps = {\n class:[$$restProps.class]\n }\n</script>\n <button on:click\n on:mouseover\n on:mouseenter\n on:mouseleave\n {...buttonProps}>\n <slot/>\n </button>\n\n<style>\n .primary{\n color:green;\n }\n .danger {\n color:red;\n }\n</style>\n```\n\n```text\n$$restProps\n```\n\n========================================\n\nComments:\n- this exactly answers my question. thanks!","metadata":{"transformedAt":"2026-08-18T18:33:40.688Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":60,"estimatedTokens":298}}383{"id":"stack-63246730","source":"stackoverflow","questionId":63246730,"title":"Reloading current page to fill session","tags":["session","svelte","goto","sapper"],"text":"Title: Reloading current page to fill session\nTags: session, svelte, goto, sapper\nSource: Stack Overflow\n\nQuestion:\nI'm having an issue with the session not been filled after login-ing, but if I refresh the page manually it does.\nSo as a workaround I'm trying to reload my login page after login was successful so the session will be populated with the data.\n\nHow do is use the goto? i tired goto('/') but it opens the index page.\nI'm looking for something dynamic and not use the page name.\n\nAnd does anybody have an idea how to fill the session without reloading the page? session is been filled in 'sapper.middleware' in the server.js coed.\n\n========================================\n\nCode:\n```html\n<script>\n import { stores } from '@sapper/app';\n\n const { session } = stores();\n\n async function login() {\n const res = await fetch('auth/login', {\n credentials: 'include',\n method: 'post',\n body: JSON.stringify(whatever)\n });\n\n if (res.ok) {\n session.update(store => ({\n ...store,\n user: await res.json()\n });\n } else {\n // handle the error\n }\n }\n</script>\n\n{#if $session.user}\n <h1>Welcome back {$session.user.name}!</h1>\n{:else}\n <button on:click={login}>log in</button>\n{/if}\n```\n\n```text\nsession\n```\n\n```text\nlocation.reload()\n```\n\n========================================\n\nComments:\n- Can you please any relevant code snippet? How are you filling the session after logging in? how are you using goto?\n- I did as you said, I looked at my code and not all was updated on the client side. My next question is what is the best practice for this? External code that uses the same function?","metadata":{"transformedAt":"2026-08-18T18:33:40.688Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":60,"estimatedTokens":414}}384{"id":"stack-56997452","source":"stackoverflow","questionId":56997452,"title":"Svelte splitter example","tags":["splitter","svelte"],"text":"Title: Svelte splitter example\nTags: splitter, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm looking for a svelte way to adjust the size of a `div` on a page. \n\nthere's an example here.\n\nI have not found any examples specifically but I'm sure someone has solved this.\n\nThanks\n\n========================================\n\nTop Answer:\nHere a quick implementation of a split pane in svelte, no external library :\nhttps://svelte.dev/repl/b467a4787de3487fbe5c4508e8221268?version=3.42.1\n\nIt lets you to chose the minimum width of the panes, and it prevents automatic highlighting of the text in the panes while dragging the splitter.\n\nThe component logic is quite simple, so you can change it and adapt it to your project.\n\n========================================\n\nCode:\n```text\ndiv\n```\n\n```text\n<SplitPane>\n```\n\n========================================\n\nComments:\n- What have you tried so far?\n- I'm thinking using stores is an option. I'm working on svelte.dev/repl/cf13540ebadf406c85f74d007aa2be3b?version=3.6‌​.7\n- Thanks Rich, I see it working here but I'm not sure why the splitter if not visible or why the text on either side hidden as well.\n- I guess what we really need is SplitPane to be a component like svelte-subdivide is","metadata":{"transformedAt":"2026-08-18T18:33:40.688Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":41,"estimatedTokens":310}}385{"id":"stack-57204295","source":"stackoverflow","questionId":57204295,"title":"How to use stage 3 syntax in svelte/sapper?","tags":["babeljs","ecmascript-next","svelte","sapper"],"text":"Title: How to use stage 3 syntax in svelte/sapper?\nTags: babeljs, ecmascript-next, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI want to use class property and private fields in my sapper project. Apparently they have to be preprocessed by babel right now.\n\nI tried to add the corresponding babel plugins to rollup.config.js, only to realize a few things.\n\n- the babel rollup plugin is only used in legacy mode.\n\n- the server part doesn't use babel at all.\n\nI tried to add the babel rollup plugin to the end of server plugins like this,\n\n```\nbabel({\n extensions: ['.js', '.mjs', '.html', '.svelte'],\n runtimeHelpers: true,\n exclude: ['node_modules/@babel/**'],\n plugins: [\n '@babel/plugin-proposal-class-properties',\n '@babel/plugin-proposal-private-methods',\n ],\n}),\n```\n\nBut it doesn't seem to take effect at all.\n\nI also added it to the client plugins (before the legacy entry), but it complained about I needed to add `@babel/plugin-syntax-dynamic-import`, so looks like babel has to recognize the whole syntax in order to preprocess, and I don't really want to compile dynamic import for modern browsers.\n\nHow do I enable the use of esnext syntax in sapper?\n\n========================================\n\nCode:\n```text\nbabel({\n extensions: ['.js', '.mjs', '.html', '.svelte'],\n runtimeHelpers: true,\n exclude: ['node_modules/@babel/**'],\n plugins: [\n '@babel/plugin-proposal-class-properties',\n '@babel/plugin-proposal-private-methods',\n ],\n}),\n```\n\n```text\n@babel/plugin-syntax-dynamic-import\n```\n\n```js\nplugins: [\n svelte({\n // ...\n preprocess: {\n script: ({ content }) => {\n return transformWithBabel(content);\n }\n },\n // ...\n })\n]\n```\n\n```text\n<script>\n```\n\n```text\npreprocess\n```\n\n```text\ntransformWithBabel\n```\n\n```text\nimport * as babel from '@babel/core'\n```\n\n```text\n@babel/plugin-syntax-dynamic-import\n```\n\n```text\n<script>\n```\n\n========================================\n\nComments:\n- Thanks Rich! I’ll give it a shot, but wondering if that will include runtime helper/polyfills twice.\n- If I add the dynamic import plugin, and in the server case, put the babel plugin before commonjs, somehow everything works.","metadata":{"transformedAt":"2026-08-18T18:33:40.688Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":95,"estimatedTokens":547}}386{"id":"stack-75220435","source":"stackoverflow","questionId":75220435,"title":"SvelteKit: +page.js load() function causes \"500 Internal Error\" after refreshing the page","tags":["svelte","sveltekit"],"text":"Title: SvelteKit: +page.js load() function causes \"500 Internal Error\" after refreshing the page\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am trying to use the load() function in the +page.js file to fetch data, which works fine after the initial load of the page. Though if I refresh the page (or change the code and it auto-refreshes) it gives me an error: \"500 Internal Error\".\n\nI can navigate to another route on my page and go back to this page and it works again.\n\n+page.js:\n\n```\nexport async function load() {\n const res = await fetch('https://jsonplaceholder.typicode.com/posts');\n const books = await res.json();\n\n return {\n books\n }\n}\n```\n\n+page.svelte:\n\n```\n\n export let data\n let id = parseInt(new URLSearchParams(window.location.search).get('id')) - 1\n\n### {data.books[id].title}\n\n{data.books[id].body}\n\n```\n\nWhat am I doing wrong?\n\n========================================\n\nCode:\n```text\nexport async function load() {\n const res = await fetch('https://jsonplaceholder.typicode.com/posts');\n const books = await res.json();\n\n return {\n books\n }\n}\n```\n\n```text\n<script>\n export let data\n let id = parseInt(new URLSearchParams(window.location.search).get('id')) - 1\n</script>\n\n<h2>{data.books[id].title}</h2>\n<p>{data.books[id].body}</p>\n```\n\n```js\nimport { browser } from '$app/environment';\nexport let data;\nlet id = 0;\n \nif (browser)\n id = parseInt(new URLSearchParams(window.location.search).get('id')) - 1\n```\n\n```text\nbrowser\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.688Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":73,"estimatedTokens":376}}387{"id":"stack-68744615","source":"stackoverflow","questionId":68744615,"title":"How to test a function from a svelte component with jest?","tags":["jestjs","svelte","ts-jest","babel-jest"],"text":"Title: How to test a function from a svelte component with jest?\nTags: jestjs, svelte, ts-jest, babel-jest\nSource: Stack Overflow\n\nQuestion:\nThere is a lot of documentation on the internet to test svelte component with jest, calling render functions and simulating browser events. This is nice, but how can I test a function inside a svelte component?\n\n### mycompoment.svelte\n\n```\n\nfunction veryComplicated(foo) {\n ...\n}\n\n...\n```\n\n### mycomponent.test.js\n\n```\nimport { veryComplicated } from \"./mycomponent.svelte\"\n\ntest('it works', async () => {\n expect(vercomplicated(\"foo\").toBe(\"bar\"))\n})\n```\n\n### jest\n\n```\nFAIL src/mycomponent.test.ts\n ● Test suite failed to run\n\n src/mycomponent.test.ts:1:10 - error TS2614: Module '\"*.svelte\"' has no exported member 'veryComplicated'. Did you mean to use 'import veryComplicated from \"*.svelte\"' instead?\n\n 1 import { veryComplicated } from \"./mycomponent.svelte\"\n ~~~~~~~~~~~~~~~\n\nTest Suites: 1 failed, 1 total\nTests: 0 total\nSnapshots: 0 total\nTime: 1.697 s\nRan all test suites.\n```\n\nAdding `export` before the `veryComplicated` definition does not help.\n\nHow can I test the `veryComplicated` function?\n\n========================================\n\nTop Answer:\nYou can export a function using a module context script block.\n\n```\n\n export veryComplicated() {\n // ...\n }\n\n...\n```\n\nThen you can do `import { veryComplicated } from './mycomponent.svelte'` as you were originally trying to do.\n\nhttps://svelte.dev/tutorial/module-exports\n\n========================================\n\nCode:\n```text\n<script>\nfunction veryComplicated(foo) {\n ...\n}\n</script>\n\n<div>...</div>\n```\n\n```text\nimport { veryComplicated } from \"./mycomponent.svelte\"\n\ntest('it works', async () => {\n expect(vercomplicated(\"foo\").toBe(\"bar\"))\n})\n```\n\n```text\nFAIL src/mycomponent.test.ts\n ● Test suite failed to run\n\n src/mycomponent.test.ts:1:10 - error TS2614: Module '\"*.svelte\"' has no exported member 'veryComplicated'. Did you mean to use 'import veryComplicated from \"*.svelte\"' instead?\n\n 1 import { veryComplicated } from \"./mycomponent.svelte\"\n ~~~~~~~~~~~~~~~\n\nTest Suites: 1 failed, 1 total\nTests: 0 total\nSnapshots: 0 total\nTime: 1.697 s\nRan all test suites.\n```\n\n```text\nexport\n```\n\n```text\nveryComplicated\n```\n\n```text\nveryComplicated\n```\n\n```text\nimport { render } from '@testing-library/svelte'\nimport MyComponent from \"./mycomponent.svelte\"\n\ntest('it works', async () => {\n const component = render(MyComponent)\n expect(component.veryComplicated(\"foo\")).toBe(\"bar\")\n})\n```\n\n```html\n<script>\nexport function veryComplicated(foo) {\n ...\n}\n</script>\n```\n\n```text\nrender\n```\n\n```text\nveryComplicated\n```\n\n```text\n<script context=\"module\">\n export veryComplicated() {\n // ...\n }\n</script>\n\n<div>...</div>\n```\n\n```text\nimport { veryComplicated } from './mycomponent.svelte'\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.688Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":156,"estimatedTokens":716}}388{"id":"stack-66688467","source":"stackoverflow","questionId":66688467,"title":"Table pagination using Svelte","tags":["svelte"],"text":"Title: Table pagination using Svelte\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI'm starting working on the project built in Svelte and never worked with Svelte before.\nI'm building the table with pagination and the issue I've got at the moment is that I don't know how can I implement pagination buttons working to display different rows.\nAny suggestions what I should do in the next steps?\n\n```\n\n import { onMount } from \"svelte\";\n \n import Header from \"./components/Header.svelte\";\n import Row from \"./components/Row.svelte\";\n import Footer from \"./components/Footer.svelte\";\n import Overlay from \"./components/Overlay.svelte\";\n\n let rows = [];\n let page = 0;\n let totalPages = [];\n let currentPageRows = [];\n let itemsPerPage = 5;\n let loading = true;\n\n const paginate = (items) => {\n const pages = Math.ceil(items.length / itemsPerPage);\n\n const paginatedItems = Array.from({ length: pages }, (_, index) => {\n const start = index * itemsPerPage;\n return items.slice(start, start + itemsPerPage);\n });\n\n console.log(\"paginatedItems are\", paginatedItems);\n totalPages = [...paginatedItems];\n currentPageRows = paginatedItems[page];\n };\n\n onMount(() => {\n fetch(\"devapi/accountStatement/transactions.json\")\n .then((response) => {\n if (response.ok) {\n return response.json();\n }\n throw Error(response.status);\n })\n .then((data) => {\n rows = data;\n paginate(data);\n loading = false;\n })\n .catch((error) => {\n console.log(error);\n });\n });\n\n const nextPageHandler = () => {\n if (page {\n if (page > 0) {\n page -= 1;\n }\n\n console.log(\"page is\", page);\n };\n\n \n\n \n {#if loading}\n \n {/if}\n {#each currentPageRows as row, i}\n \n {:else}\n \n \n \n\n### There is no data to display here.\n\n \n \n {/each}\n \n \n\n \n \n previousPageHandler()}\n >PREV\n \n \n\n {#each totalPages as page, i}\n \n {i + 1}\n \n {/each}\n\n \n nextPageHandler()}\n >NEXT\n \n \n \n\n```\n\n========================================\n\nCode:\n```text\n<script>\n import { onMount } from \"svelte\";\n \n import Header from \"./components/Header.svelte\";\n import Row from \"./components/Row.svelte\";\n import Footer from \"./components/Footer.svelte\";\n import Overlay from \"./components/Overlay.svelte\";\n\n let rows = [];\n let page = 0;\n let totalPages = [];\n let currentPageRows = [];\n let itemsPerPage = 5;\n let loading = true;\n\n const paginate = (items) => {\n const pages = Math.ceil(items.length / itemsPerPage);\n\n const paginatedItems = Array.from({ length: pages }, (_, index) => {\n const start = index * itemsPerPage;\n return items.slice(start, start + itemsPerPage);\n });\n\n console.log(\"paginatedItems are\", paginatedItems);\n totalPages = [...paginatedItems];\n currentPageRows = paginatedItems[page];\n };\n\n onMount(() => {\n fetch(\"devapi/accountStatement/transactions.json\")\n .then((response) => {\n if (response.ok) {\n return response.json();\n }\n throw Error(response.status);\n })\n .then((data) => {\n rows = data;\n paginate(data);\n loading = false;\n })\n .catch((error) => {\n console.log(error);\n });\n });\n\n const nextPageHandler = () => {\n if (page < totalPages.length) {\n page += 1;\n }\n\n console.log(\"page is\", page);\n };\n\n const previousPageHandler = () => {\n if (page > 0) {\n page -= 1;\n }\n\n console.log(\"page is\", page);\n };\n</script>\n\n<table class=\"table table-bordered table-striped table-hover\">\n <Header />\n\n <tbody>\n {#if loading}\n <Overlay />\n {/if}\n {#each currentPageRows as row, i}\n <Row {row} />\n {:else}\n <tr>\n <td colspan=\"100%\">\n <h5 class=\"text-center\">There is no data to display here.</h5>\n </td>\n </tr>\n {/each}\n </tbody>\n <Footer />\n</table>\n<nav class=\"pagination\">\n <ul>\n <li>\n <button\n type=\"button\"\n class=\"btn-next-prev\"\n on:click={() => previousPageHandler()}\n >PREV\n </button>\n </li>\n\n {#each totalPages as page, i}\n <li>\n <button type=\"button\" class=\"btn-page-number\">{i + 1}</button>\n </li>\n {/each}\n\n <li>\n <button\n type=\"button\"\n class=\"btn-next-prev\"\n on:click={() => nextPageHandler()}\n >NEXT\n </button>\n </li>\n </ul>\n</nav>\n```\n\n```js\n...\n let rows = [];\n let page = 0;\n let totalPages = [];\n let currentPageRows = [];\n let itemsPerPage = 5;\n let loading = true;\n\n $: currentPageRows = totalPages.length > 0 ? totalPages[page] : [];\n\n const paginate = (items) => {\n ...\n }\n ...\n```\n\n```js\nconst setPage = (p) => {\n if (p >= 0 && p < totalPages.length) {\n page = p;\n }\n }\n```\n\n```js\n<nav class=\"pagination\">\n <ul>\n <li>\n <button\n type=\"button\"\n class=\"btn-next-prev\"\n on:click={() => setPage(page - 1)}\n >\n PREV\n </button>\n </li>\n\n {#each totalPages as page, i}\n <li>\n <button\n type=\"button\"\n class=\"btn-page-number\"\n on:click={() => setPage(i)}\n >\n {i + 1}\n </button>\n </li>\n {/each}\n\n <li>\n <button\n type=\"button\"\n class=\"btn-next-prev\"\n on:click={() => setPage(page + 1)}\n >\n NEXT\n </button>\n </li>\n </ul>\n</nav>\n```\n\n```text\ncurrentPageRows\n```\n\n```text\npage\n```\n\n```text\non:click\n```\n\n========================================\n\nComments:\n- Figured that out. Thanks a lot anyway Thomas","metadata":{"transformedAt":"2026-08-18T18:33:40.689Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":302,"estimatedTokens":1349}}389{"id":"stack-56908967","source":"stackoverflow","questionId":56908967,"title":"Svelte: How to stop the {#await} block from getting refreshed every time the bound attribute is changed?","tags":["svelte","svelte-component"],"text":"Title: Svelte: How to stop the {#await} block from getting refreshed every time the bound attribute is changed?\nTags: svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI'm trying to initialize a `` input with the data obtained from a Promise based function. After the input initializes the options (each option gets the value and label from the resolved data), an attribute is bound to the ``. \n\nBut every time I change the option (with the attribute binding), everything inside the `{#await}` block gets reloaded (seems like its resolving the same Promise and resetting the options). \n\nThis doesn't happen when I remove the binding. \n\nI have tried the following: \n\nTried binding an attribute to the select.\n\n```\n`...`\n```\n\nTried binding an event that gets the selected option from the list.\n\n```\n`...`\n```\n\nTried making another button to get the selected option.\n\n```\n...\nSet`\n```\n\nThis is the snippet of the current state:\n\nThe Await Block:\n\n```\n\n {#await VoiceStreamingService.get_microhpones()}\n\n {:then devices}\n \n Select an Option...\n {#each devices as device (device.deviceId)}\n {device.label}\n {/each}\n \n {:catch}\n\n {/await}\n Connect To\n\n```\n\nThe set_selected_device function:\n\n```\nfunction set_selected_device() {\n let d = document.getElementById(\"device-options\");\n selected_device = d.options[d.selectedIndex].value;\n console.log(selected_device);\n }\n```\n\nAm I missing something important, or is it a bug?\n\n========================================\n\nTop Answer:\nI tried to resolve the promise once component was mounted and then pushed the options to the select object. \n\nSharing the code below: \n\n```\nonMount(() => {\n (async () => {\n let select = document.getElementById(\"device-options\");\n try {\n (await VoiceStreamingService.get_microhpones()).forEach(device => {\n let option = document.createElement(\"option\");\n option.value = device.deviceId;\n option.innerHTML = device.label;\n select.appendChild(option);\n });\n } catch (e) {\n console.log(e);\n }\n })();\n});\n```\n\n========================================\n\nCode:\n```text\n`<select bind:value={selected_device}>...`\n```\n\n```text\n`<select on:change={set_selected_device}>...`\n```\n\n```text\n<select>...</select>\n<button on:click={set_selected_device}>Set</button>`\n```\n\n```text\n<div class=\"device-select container\">\n {#await VoiceStreamingService.get_microhpones()}\n\n {:then devices}\n <select id=\"device-options\">\n <option selected disabled>Select an Option...</option>\n {#each devices as device (device.deviceId)}\n <option value={device.deviceId}>{device.label}</option>\n {/each}\n </select>\n {:catch}\n\n {/await}\n <button on:click={set_selected_device}>Connect To</button>\n</div>\n```\n\n```text\nfunction set_selected_device() {\n let d = document.getElementById(\"device-options\");\n selected_device = d.options[d.selectedIndex].value;\n console.log(selected_device);\n }\n```\n\n```text\n<select/>\n```\n\n```text\n<select/>\n```\n\n```text\n{#await}\n```\n\n```text\nlet promise = VoiceStreamingService.get_microhpones();\n```\n\n```text\nonMount(() => {\n (async () => {\n let select = document.getElementById(\"device-options\");\n try {\n (await VoiceStreamingService.get_microhpones()).forEach(device => {\n let option = document.createElement(\"option\");\n option.value = device.deviceId;\n option.innerHTML = device.label;\n select.appendChild(option);\n });\n } catch (e) {\n console.log(e);\n }\n })();\n});\n```\n\n========================================\n\nComments:\n- Thank you Rich for your suggestion. I tried that. I'll post my answer.\n- You'd be better off using Svelte's data binding, rather than querying and manipulating the DOM. The `onMount` function itself can be async, so you could do something like `let devices; onMount(async () => devices = await ...)`\n- That's much better regarding the onMount part. But could you explain about the data binding? Because I could not understand how to bind the resolved array to a ` select ` object. (the {#each} directive gets called before the devices get resolved)\n- I should have said `let devices = [];` — i.e. initialise it to an empty array, which gets replaced with the list of devices once the promise resolves","metadata":{"transformedAt":"2026-08-18T18:33:40.689Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":174,"estimatedTokens":1050}}390{"id":"stack-62010385","source":"stackoverflow","questionId":62010385,"title":"How to call svelte:component current component method?","tags":["svelte"],"text":"Title: How to call svelte:component current component method?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI have this basic app, with some components that have a public `load` method. On some actions, I'd like to call that method on the current svelte:component, but I have no idea how to get a reference to the component instance. How can one do that?\n\n```\n\n import router from 'page'\n import Wines from './pages/Wines.svelte'\n import Entry from './pages/Entry.svelte'\n import TitleBar from './components/TitleBar.svelte'\n\n let page,\n params\n\n router('/', () => page = Wines)\n router('/wines', () => page = Wines)\n router('/entry/:id?', (ctx, next) => {\n params = ctx.params\n next()\n }, () => page = Entry)\n\n async function forceSync(){\n // how to call current component instance?\n }\n\n \n\n \n \n \n \n```\n\n========================================\n\nTop Answer:\nI'm pretty sure that we can't access functions on the component scripts. I didn't find any hint on the API and couldn't find any of the methods via devTools.\n\n**See the edit below**\n\nBut we can send functions via custom events and you could solve your requirement like this:\n\nApp.svelte\n\n```\n\n import A from './A.svelte'\n const syncMethods = []\n\n function sync() {\n syncMethods.forEach(f => f());\n }\n\n function storeSyncHandler(event) {\n syncMethods.push(event.detail);\n }\n\nSync Components\n\n```\n\nA.svelte\n\n```\n\n import { createEventDispatcher, onMount} from 'svelte';\n const dispatch = createEventDispatcher();\n\n let synced = ''\n\n function sync() {\n synced = '[SYNCED]';\n }\n\n onMount(() => {\n dispatch('mounted', sync)\n })\n\nSyncable Component {synced}\n```\n\nThe child component sends a 'mounted' event with it's 'sync' method. The parent stores that and can call it when ever needed. Hope it helps or gives some ideas.\n\nHere's the REPL: https://svelte.dev/repl/6bc923a8326643cca79a6a2f8ee0ffe0?version=3.22.3\n\nEdit:\n\nIt works like a charm when we export the function on the other component.\n\nHere's the working REPL to call methods on mounted components:\n\nhttps://svelte.dev/repl/8ba4270a9e334f35a591cdbfbac70e8e?version=3.22.3\n\n========================================\n\nCode:\n```text\n<script>\n import router from 'page'\n import Wines from './pages/Wines.svelte'\n import Entry from './pages/Entry.svelte'\n import TitleBar from './components/TitleBar.svelte'\n\n let page,\n params\n\n router('/', () => page = Wines)\n router('/wines', () => page = Wines)\n router('/entry/:id?', (ctx, next) => {\n params = ctx.params\n next()\n }, () => page = Entry)\n\n async function forceSync(){\n // how to call current component instance?\n }\n\n </script>\n\n <main>\n <TitleBar on:sync-request={forceSync}></TitleBar>\n <svelte:component this={page} params={params}/>\n </main>\n```\n\n```text\nload\n```\n\n```html\n<script>\n import Child from './Child.svelte'\n\n let cmp\n\n const func = () => {\n // use cmp here: cmp.load()\n }\n</script>\n\n<svelte:component this=\"{Child}\" bind:this=\"{cmp}\" />\n```\n\n```text\nbind:this\n```\n\n```text\n<svelte:component>\n```\n\n```text\n<script>\n import A from './A.svelte'\n const syncMethods = []\n\n function sync() {\n syncMethods.forEach(f => f());\n }\n\n function storeSyncHandler(event) {\n syncMethods.push(event.detail);\n }\n</script>\n\n<button on:click={sync}>Sync Components</button>\n<A on:mounted={storeSyncHandler}/>\n```\n\n```text\n<script>\n import { createEventDispatcher, onMount} from 'svelte';\n const dispatch = createEventDispatcher();\n\n let synced = ''\n\n function sync() {\n synced = '[SYNCED]';\n }\n\n onMount(() => {\n dispatch('mounted', sync)\n })\n</script>\n\n<div>Syncable Component {synced}</div>\n```\n\n========================================\n\nComments:\n- We can get a component reference but that does not allow us to use functions, that are defined on the component. svelte only provides a `$set` to update props but no `$get` to read the state (and probably execute an exported arrow function)\n- At least, if you do export a function on the component\n- Ahh, I failed first for whatever reason with my REPL. Now I got it. Yay!! Thanks!! svelte.dev/repl/8ba4270a9e334f35a591cdbfbac70e8e?version=3.2‌​2.3\n- right, I had tried to replace this={child} with bind:this but the compiler complained. I didn't think we could use both, as it seems to me that `this` is bound twice.\n- How can I pass $event to the child so as to prevent default?","metadata":{"transformedAt":"2026-08-18T18:33:40.689Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":199,"estimatedTokens":1130}}391{"id":"stack-73370235","source":"stackoverflow","questionId":73370235,"title":"supabaseUrl is required sveltekit","tags":["javascript","svelte","sveltekit","supabase"],"text":"Title: supabaseUrl is required sveltekit\nTags: javascript, svelte, sveltekit, supabase\nSource: Stack Overflow\n\nQuestion:\nI'm having this problem for quite a while and want to solve this:\nAccording to supbase documentation you create a **.env** file\n\n```\nVITE_SUPABASE_URL=\"YOUR_SUPABASE_URL\"\nVITE_SUPABASE_ANON_KEY=\"YOUR_SUPABASE_KEY\"\n```\n\nthen you call them in supabaseClient.js:\n\n```\nimport { createClient } from '@supabase/supabase-js'\n\nconst supabaseUrl = import.meta.env.VITE_SUPABASE_URL\nconst supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY\n\nexport const supabase = createClient(supabaseUrl, supabaseAnonKey)\n```\n\nHowever this doesnt work,I get **supabaseUrl is required.** and the env variables are not getting exported.\n\nDoes anyone know why and how to solve it?\n\nDo I need to install any additional lib?\n\nThank you in advance\n\n========================================\n\nCode:\n```text\nVITE_SUPABASE_URL=\"YOUR_SUPABASE_URL\"\nVITE_SUPABASE_ANON_KEY=\"YOUR_SUPABASE_KEY\"\n```\n\n```text\nimport { createClient } from '@supabase/supabase-js'\n\nconst supabaseUrl = import.meta.env.VITE_SUPABASE_URL\nconst supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY\n\nexport const supabase = createClient(supabaseUrl, supabaseAnonKey)\n```\n\n```text\n# .env file\nPUBLIC_SUPABASE_URL=\"YOUR_SUPABASE_URL\"\nPUBLIC_SUPABASE_ANON_KEY=\"YOUR_SUPABASE_KEY\"\n```\n\n```text\n// supabaseClient.js\n\nimport { createClient } from '@supabase/supabase-js' \nimport {PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY} from '$env/static/public'\n\nexport const supabase = createClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY)\n```\n\n```text\n$env/static/private\n```\n\n```text\nPUBLIC_\n```\n\n```text\n$env/static/private\n```\n\n```text\nPUBLIC_\n```\n\n```text\nVITE_SUPABASE_URL\n```\n\n```text\nimport.meta.env.VITE_SUPABASE_URL\n```\n\n```text\nimport.meta.env.VITE_SUPABASE_URL\n```\n\n```text\nenvPrefix\n```\n\n========================================\n\nComments:\n- the PUBLIC_ is not something to be taken in consideration, although it is a solution to importing variables. I just tested them and again something might be wrong from my side. If I go to my .env file I do have `VITE_SUPABASE_URL & VITE_SUPABASE_ANON_KEY&PRIVATE_SUPABASE_URL` and I call them at supabaseclient.js like this `import { createClient } from '@supabase/supabase-js' import { PRIVATE_SUPABASE_URL } from '$env/static/private'; const supabaseUr = env.PRIVATE_SUPABASE_URL console.log(supabaseUr)` **env is not defined** Please let me know what I doing wrong\n- @equi: Your env variables names need to match. Right now, you're using `VITE_SUPABASE_URL` in your .env file but trying to import `PRIVATE_SUPABASE_URL`. Also `env.PRIVATE_SUPABASE_URL` is for dynamic env variables. For static env variables you import them directly like my example in my answer. I suggest you first get my PUBLIC_ example working, then modify the working project to use private env variables.\n- so I figured out where the problem is....the .env should not be inside src/ directory but in your main project directory...this fixes everything.thank you for your help.please add one more line to your answer","metadata":{"transformedAt":"2026-08-18T18:33:40.689Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":102,"estimatedTokens":780}}392{"id":"stack-75378794","source":"stackoverflow","questionId":75378794,"title":"anchor link in Svelte app using page.js routing","tags":["anchor","svelte","page.js"],"text":"Title: anchor link in Svelte app using page.js routing\nTags: anchor, svelte, page.js\nSource: Stack Overflow\n\nQuestion:\nI have an anchor tag on a page in my Svelte app. The link to the anchor works on the page itself, but I can't link to the anchor from another page. And when I enter the URL with the anchor, the page doesn't scroll down. I need to be able to give people a link and have them go to a specific part of the page.\n\nHere's the relevant code:\n\n```\n\n function scrollIntoView({ target }) {\n const el = document.querySelector(target.getAttribute(\"href\"));\n if (!el) return;\n el.scrollIntoView({\n behavior: \"smooth\",\n });\n }\n \n\n \n go to anchor\n \n\n \n \n ... lots of lorem ipsum ...\n \n \n \n\n### anchor\n\n```\n\nAnd I have a REPL here: https://svelte.dev/repl/e651218bdb47455d9cafe8bff27c8d7b?version=3.24.0\n\nI'm using page.js for my routing to components -- I haven't found anything specific about targeting anchor tags in the documentation.\n\nAny help would be greatly appreciated.\n\n========================================\n\nTop Answer:\nIt looks like the only other answer solved the original problem. This is my first post here, so forgive me if this is poor etiquette, but I wound up here by having the same general problem (cross-page anchor links not scrolling to their id'ed elements) but by different mechanics, so I'm posting this for the next person who winds up reading this thread in case the cause of their problem matches mine.\n\nUsing CSS to set my scrolling behavior, and using just the element's href attribute to set cross-page anchor links, I was having the problem that I would click the cross-page anchor link and, upon arrival on the target page, the window would scroll a few pixels and then hang up.\n\nI tried a variety of Svelte and JS workarounds and, although logging key variables to the console showed that the related data was changing as intended, the broken behavior persisted.\n\nIn my case, the problem turned out to be that, on the target page for the cross-page anchor links, I was tracking the vertical scroll with...\n\n```\nsvelte:window(bind:scrollY)\n```\n\nThat's Pug syntax, but you get the point.\n\nGetting rid of that special element (and, of course, all related code) un-broke the cross-page anchor links. Bringing it back broke them again. So far, over a period of days, I've re-tested this observation and it's one-to-one.\n\nI don't understand the deeper mechanics, but I'm fairly confident that this vertical scroll binding to the svelte:window element is the isolated x-factor because I found a workaround with vanilla JS to accomplish what I was doing with the binding, and the cross-page anchor links still work with the workaround in place.\n\n========================================\n\nCode:\n```text\n<script>\n function scrollIntoView({ target }) {\n const el = document.querySelector(target.getAttribute(\"href\"));\n if (!el) return;\n el.scrollIntoView({\n behavior: \"smooth\",\n });\n }\n </script>\n\n <nav>\n <a href=\"#here\" on:click|preventDefault={scrollIntoView}>go to anchor</a>\n </nav>\n\n <main>\n <section id=\"section-1\">\n ... lots of lorem ipsum ...\n </section>\n <section>\n <h2 id=\"here\">anchor</h2>\n```\n\n```css\n/* :global if in component */\n:global(html) {\n scroll-behavior: smooth;\n}\n```\n\n```js\nonMount(() => {\n const { hash } = document.location;\n const scrollTo = hash && document.getElementById(hash.slice(1));\n if (scrollTo)\n scrollTo.scrollIntoView();\n});\n```\n\n```text\nonMount\n```\n\n```text\nsvelte:window(bind:scrollY)\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.689Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":111,"estimatedTokens":892}}393{"id":"stack-63859576","source":"stackoverflow","questionId":63859576,"title":"Sapper/Svelte possible to conditionally import components?","tags":["svelte","sapper"],"text":"Title: Sapper/Svelte possible to conditionally import components?\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nIn Sapper I am trying to import a component only if being rendered client side (using `onMount`). Is there something similar to React `Suspense` and `React.lazy`? Or is there another approach?\n\n========================================\n\nCode:\n```text\nonMount\n```\n\n```text\nSuspense\n```\n\n```text\nReact.lazy\n```\n\n```html\n<script>\n import { onMount } from 'svelte';\n \n let Thing;\n \n onMount(async () => {\n Thing = (await import('./Thing.svelte')).default;\n });\n</script>\n\n<svelte:component this={Thing} answer={42}>\n <p>some slotted content</p>\n</svelte:component>\n```\n\n```html\n<!-- Loader.svelte -->\n<script>\n import { onMount } from 'svelte';\n \n let loader;\n let Component;\n \n onMount(async () => {\n Component = (await loader()).default;\n });\n \n export { loader as this };\n</script>\n\n<svelte:component this={Component} {...$$restProps}>\n <slot></slot>\n</svelte:component>\n\n{#if !Component}\n <slot name=\"fallback\"></slot>\n{/if}\n```\n\n```html\n<Loader\n this={() => import('./Thing.svelte')}\n answer={42}\n>\n <p>some slotted content</p>\n <p slot=\"fallback\">loading...</p>\n</Loader>\n```\n\n```text\ndefault\n```\n\n========================================\n\nComments:\n- I know a library called svelte-lazy which enable to do lazy loading.\n- is there any way to make it SSR? That would be very useful for web apps where UI depends on the existence of auth cookies for example. Currently, with CSR only import, it's causing Layout Shift.","metadata":{"transformedAt":"2026-08-18T18:33:40.689Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":81,"estimatedTokens":395}}394{"id":"stack-62903705","source":"stackoverflow","questionId":62903705,"title":"Style children from parent using a class","tags":["javascript","svelte"],"text":"Title: Style children from parent using a class\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nIn Svelte I can pass a custom class to a children component like that:\n\n*Icon.svelte*\n\n```\n\n export { className as class };\n \n let className = '';\n\n```\n\n*App.svelte*\n\n```\n\n import Icon from './Icon/Icon'\n\n \n\n```\n\nIf I inspect the rendered DOM I see that the class is successfully given to the `Icon` component:\n\n```\n\n```\n\nBut if I define some style for `.custom-icon` in `App.svelte` they are not applied:\n\n```\n\n import Icon from './Icon/Icon'\n\n .custom-icon {\n border: solid 2px red;\n }\n\n \n\n```\n\nCheck the codesandbox.\n\nSo has someone an idea how I can style a children component from the parent using a class?\n\n========================================\n\nTop Answer:\nI think there's a way to get the best of both worlds.\n\n```\n* :global(.custom-icon) {\n border: solid 2px red;\n}\n```\n\nThis will output a CSS like this:\n\n```\n.svelte-5z4ccp .custom-icon {\n border: solid 2px red;\n}\n```\n\nThis will allow you to have scoped CSS for the descendants of your component. It's not possible to scope it only for the immediate child, though, only to all the descendants.\n\n========================================\n\nCode:\n```html\n<script>\n export { className as class };\n \n let className = '';\n</script>\n\n<img src='...' class={className} />\n```\n\n```html\n<script>\n import Icon from './Icon/Icon'\n</script>\n\n<div id='app'>\n <Icon class='custom-icon' />\n</div>\n```\n\n```html\n<img src='...' class='custom-icon' />\n```\n\n```html\n<script>\n import Icon from './Icon/Icon'\n</script>\n\n<style>\n .custom-icon {\n border: solid 2px red;\n }\n</style>\n\n<main>\n <Icon class='custom-icon' /> <!-- Icon has no red border -->\n</main>\n```\n\n```text\nIcon\n```\n\n```text\n.custom-icon\n```\n\n```text\nApp.svelte\n```\n\n```text\n:global\n```\n\n```text\n:global(.custom-icon) {\n border: solid 2px red;\n}\n```\n\n```css\n* :global(.custom-icon) {\n border: solid 2px red;\n}\n```\n\n```css\n.svelte-5z4ccp .custom-icon {\n border: solid 2px red;\n}\n```\n\n========================================\n\nComments:\n- Does this answer your question? How to target a component in svelte with css?\n- Hey thanks for your response. Not a fan from you first point since I want the parent to fully customize the children (so I'm not supposed to predict it). For the second option you didn't mention that it makes styles available to all the app, not just the `descendants of the component`. So if I have an other `.custom-icon` in my app it will also be impacted.\n- Yes, that was implied by '*these styles are unscoped*'. I pointed out that the styles would be available to all descendants because that's where you would want to use them, but they will indeed be available throughout the app, sorry if this was not clear.\n- Just to be clear, you cannot have the best of both worlds. Either your styles are scoped, but then they must be known at build-time, *or* you want to define them during run-time, in which case they cannot be scoped and you risk name collision.\n- An alternate solution to style at run-time while avoiding name collision issues would be to use inline styles rather than CSS classes.\n- Thats sad concerning svelte but seems to have no choice. I will use the global solution. Thanks again for your help.\n- Great suggestions if this works! Wouldn't something like `* > :global(.custom-icon)` work for immediate descendants?","metadata":{"transformedAt":"2026-08-18T18:33:40.689Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":159,"estimatedTokens":846}}395{"id":"stack-65653715","source":"stackoverflow","questionId":65653715,"title":"How to pass classes from components with already existing styles in Svelte?","tags":["svelte"],"text":"Title: How to pass classes from components with already existing styles in Svelte?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI have two components called `One.svelte` and `Two.svelte`\n\nThis is how `One.svelte` looks like:\n\n```\n //example tailwind classes\n```\n\nHow `Two.svelte` looks like:\n\n```\n...\n```\n\nI want the `main` element of `Two.svelte` to use the classes passed from the `One.svelte` without removing the existing classes on `Two.svelte` like `mt-6 bg-red-500` etc.\n\nWhat I tried:\n\n`Two.svelte`\n\n```\n...\n```\n\nThis does not seem to work, what is the right way to approach this issue?\n\n========================================\n\nCode:\n```text\n<Two class=\"mt-8 border\"/> //example tailwind classes\n```\n\n```text\n<main class=\"mt-6 bg-red-500\">...</main>\n```\n\n```text\n<main class=\"mt-6 bg-red-500 {{$$props.class}}\">...</main>\n```\n\n```text\nOne.svelte\n```\n\n```text\nTwo.svelte\n```\n\n```text\nOne.svelte\n```\n\n```text\nTwo.svelte\n```\n\n```text\nmain\n```\n\n```text\nTwo.svelte\n```\n\n```text\nOne.svelte\n```\n\n```text\nTwo.svelte\n```\n\n```text\nmt-6 bg-red-500\n```\n\n```text\nTwo.svelte\n```\n\n```text\n<main class={`mt-6 bg-red-500 ${$$props.class}`}>\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.689Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":89,"estimatedTokens":285}}396{"id":"stack-60851390","source":"stackoverflow","questionId":60851390,"title":"Svelte bundle.js is large, full of @license comments, even in production mode","tags":["svelte","rollupjs"],"text":"Title: Svelte bundle.js is large, full of @license comments, even in production mode\nTags: svelte, rollupjs\nSource: Stack Overflow\n\nQuestion:\n`>npm run build` on a modest sized Svelte project produces a large public/build/bundle.js file. The Javascript code is minimized into a series of one-liners\n\n`function(t){return new qr((function(e){...`\n\nbut in between (or sometimes in the middle of) every line is a large comment block for licenses\n\n```\n* @license\n * Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n ... 9 more lines\n * limitations under the License.\n```\n\nThe date varies, 2017-2019. There are also a few Microsoft Licenses. There are roughly 70 of these licenses sprinkled in the code, making it bloat up to 800kb.\n\nI haven't messed with rollup config or anything.\nHere's package.json relevant sections:\n\n```\n\"scripts\": {\n \"build\": \"rollup -c\",\n \"dev\": \"rollup -c -w\",\n \"start\": \"sirv public\"\n },\n \"devDependencies\": {\n \"@rollup/plugin-commonjs\": \"^11.0.0\",\n \"@rollup/plugin-node-resolve\": \"^7.0.0\",\n \"rollup\": \"^1.20.0\",\n \"rollup-plugin-livereload\": \"^1.0.0\",\n \"rollup-plugin-svelte\": \"^5.0.3\",\n \"rollup-plugin-terser\": \"^5.1.2\",\n \"svelte\": \"^3.0.0\",\n \"svelte-mui\": \"^0.3.3\"\n },\n```\n\nI've tried deleting node_modules and redoing `npm install` to no effect. I\"m running on Windows 10 if that matters.\n\n========================================\n\nCode:\n```text\n* @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n ... 9 more lines\n * limitations under the License.\n```\n\n```text\n\"scripts\": {\n \"build\": \"rollup -c\",\n \"dev\": \"rollup -c -w\",\n \"start\": \"sirv public\"\n },\n \"devDependencies\": {\n \"@rollup/plugin-commonjs\": \"^11.0.0\",\n \"@rollup/plugin-node-resolve\": \"^7.0.0\",\n \"rollup\": \"^1.20.0\",\n \"rollup-plugin-livereload\": \"^1.0.0\",\n \"rollup-plugin-svelte\": \"^5.0.3\",\n \"rollup-plugin-terser\": \"^5.1.2\",\n \"svelte\": \"^3.0.0\",\n \"svelte-mui\": \"^0.3.3\"\n },\n```\n\n```text\n>npm run build\n```\n\n```text\nfunction(t){return new qr((function(e){...\n```\n\n```text\nnpm install\n```\n\n```text\n--comments [filter] Preserve copyright comments in the output. By\n default this works like Google Closure, keeping\n JSDoc-style comments that contain \"@license\" or\n \"@preserve\". You can optionally pass one of the\n following arguments to this flag:\n - \"all\" to keep all comments\n - `false` to omit comments in the output\n - a valid JS RegExp like `/foo/` or `/^!/` to\n keep only matching comments.\n Note that currently not *all* comments can be\n kept when compression is on, because of dead\n code removal or cascading statements into\n sequences.\n```\n\n```js\nproduction && terser({ output: { comments: false } })\n```\n\n```text\nnpm run build\n```\n\n```text\nterser\n```\n\n```text\n@license\n```\n\n========================================\n\nComments:\n- Managed to strip out the comments, and the file is still ~700kB, so the added size isn't a huge issue, it's just weird that all the license comments get in there.\n- Thanks! On my setup, the proper line in rollup.config.js is actually `production && terser({ output: { comments: false } })`\n- Thanks, I'm fixing the answer for future visitors.\n- The net effect is small, but noticeable. My bundle.js drops from 830KB to 785KB with comments removed.","metadata":{"transformedAt":"2026-08-18T18:33:40.689Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":126,"estimatedTokens":907}}397{"id":"stack-60591927","source":"stackoverflow","questionId":60591927,"title":"Svelte user registration issue with setting store value","tags":["svelte","svelte-store"],"text":"Title: Svelte user registration issue with setting store value\nTags: svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\nhelo :)\n\nI'm trying to register an user and after success, setContext to newly registered user and then navigate to home. Server properly responds and registers user, but when setContext is called i get the following error: \"index.mjs:552 Uncaught (in promise) Error: Function called outside component initialization\"\n\n```\n\n import { setContext } from 'svelte'\n\n async function handleRegistration(e) {\n let user = {\n firstname: e.target.firstname.value,\n lastname: e.target.lastname.value,\n }\n\n fetch('http://localhost:3001/api/auth/register', {\n method: 'POST',\n headers: {'Content-Type':'application/json'},\n body: JSON.stringify(user)\n })\n .then(res => res.json())\n .then(res => {\n if(res.accessToken) {\n user.accessToken = res.accessToken\n user.refreshToken = res.refreshToken\n setContext('userData', user)\n navigate(\"/\", { replace: true })\n }\n })\n\n updateContext(user)\n }\n }\n\n```\n\nWhat am I doing wrong?\n\n========================================\n\nCode:\n```text\n<script>\n import { setContext } from 'svelte'\n\n async function handleRegistration(e) {\n let user = {\n firstname: e.target.firstname.value,\n lastname: e.target.lastname.value,\n }\n\n fetch('http://localhost:3001/api/auth/register', {\n method: 'POST',\n headers: {'Content-Type':'application/json'},\n body: JSON.stringify(user)\n })\n .then(res => res.json())\n .then(res => {\n if(res.accessToken) {\n user.accessToken = res.accessToken\n user.refreshToken = res.refreshToken\n setContext('userData', user)\n navigate(\"/\", { replace: true })\n }\n })\n\n updateContext(user)\n }\n }\n</script>\n\n<form class=\"registration\" on:submit|preventDefault=\"{handleRegistration}\">\n</form>\n```\n\n```html\n<script>\n import { setContext } from 'svelte'\n\n console.log('init')\n\n setContext(...) // OK\n\n setTimeout(() => {\n setContext(...) // Not OK (we're not synchronous anymore)\n }, 0)\n<script>\n\n<h1>My Svelte Component</h1>\n```\n\n```html\n<script>\n import { getContext } from 'svelte'\n\n const userData = getContext('userData')\n\n function handleRegistration(e) {\n doSuperApiCall()\n .then(data => {\n userData.set(data)\n // or fancy:\n $userData = data\n })\n .catch(...)\n }\n</script>\n...\n```\n\n```html\n<script>\n import { setContext } from 'svelte'\n import { writable } from 'svelte/store'\n\n const userData = writable(null)\n\n setContext('userData', userData)\n</script>\n\n<slot />\n```\n\n```text\nsetContext\n```\n\n```text\n<script>\n```\n\n```text\nonMount\n```\n\n```text\nonDestroy\n```\n\n```text\nsetContext\n```\n\n```text\nsetContext\n```\n\n```text\ngetContext\n```\n\n```text\nsetContext\n```\n\n```text\n<App>\n```\n\n```text\ngetContext\n```\n\n```text\n<App>\n```\n\n========================================\n\nComments:\n- Searched a long time for this answer, thanks!","metadata":{"transformedAt":"2026-08-18T18:33:40.689Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":175,"estimatedTokens":798}}398{"id":"stack-75045021","source":"stackoverflow","questionId":75045021,"title":"Cookies are not getting set when running with --host option in official SvelteKit example","tags":["javascript","node.js","cookies","svelte","sveltekit"],"text":"Title: Cookies are not getting set when running with --host option in official SvelteKit example\nTags: javascript, node.js, cookies, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am trying offical SvelteKit example https://realworld.svelte.dev/.\n\nIts code is hosted at https://github.com/sveltejs/realworld\n\nlogin and everything works fine when I run `npm run dev`\nbut when I run `npm run dev -- --host` then login does not work.\n\n```\ncookies.set('jwt', value, { path: '/' });\n```\n\nThis is not working so cookies are not getting set so login is not working.\n\nHow can I make login working when using `--host` option?\n\n========================================\n\nCode:\n```text\ncookies.set('jwt', value, { path: '/' });\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run dev -- --host\n```\n\n```text\n--host\n```\n\n```text\ncookies.set('jwt', value, { secure: false, path: '/' });\n```\n\n```text\nlocalhost\n```\n\n```text\nhttp\n```\n\n```text\nsecure\n```\n\n```text\ntrue\n```\n\n```text\nlocalhost\n```\n\n```text\nsecure\n```\n\n```text\nfalse\n```\n\n```text\nsecure\n```\n\n```text\ntrue\n```\n\n```text\nsrc/routes/login/+page.server.js\n```\n\n```text\nsecure\n```\n\n```text\nsecure\n```\n\n```text\ntrue\n```\n\n```text\nhttps\n```\n\n========================================\n\nComments:\n- Can you answer stackoverflow.com/q/75087582/1762051\n- Anyone struggling with setting the cookie in expressjs server, this is the right answer. Change the flag to false and cookie will be set. In sveltekit load, log fetch headers.headersList and cookies are the first entry in headersList. Note the capitalized L in list.","metadata":{"transformedAt":"2026-08-18T18:33:40.689Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":104,"estimatedTokens":390}}399{"id":"stack-76097296","source":"stackoverflow","questionId":76097296,"title":"Missing lifecycle specifier in svelte package. SvelteKit","tags":["typescript","svelte","sveltekit"],"text":"Title: Missing lifecycle specifier in svelte package. SvelteKit\nTags: typescript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am currently using svelte's context api to pass user data through out my application. Suddenly I came across this error that has practically no documentation anywhere that I could find. The error message is as follows. `Missing \"./types/runtime/internal/lifecycle\" specifier in \"svelte\" package`. By the looks of the complete console output which I will also post, it is coming from this file here:\n\n```\n\n import { getContext } from 'svelte';\n import HtmlGenerator from './generate_html';\n import type { Field } from './generate_html';\n import { setContext } from 'svelte/types/runtime/internal/lifecycle';\n import { UserContext } from '../../context';\n\n setContext('UserContext', UserContext);\n\n const { is_logged_in, user } = getContext('UserContext');\n\n```\n\nFor simplicity I have omitted unrelated code. I did not start getting this error until I tried to use the context Api. Here is the full console output:\n\n```\nInternal server error: Missing \"./types/runtime/internal/lifecycle\" specifier in \"svelte\" package\n Plugin: vite:import-analysis\n File: C:/javascript_projects/svelte_projects/reactable/src/routes/dashboard/form-builder/+page.svelte\n at e (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:16638:25)\n at n (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:16638:627)\n at o (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:16638:1297)\n at resolveExportsOrImports (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:23396:20)\n at resolveDeepImport (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:23415:31)\n at tryNodeResolve (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:23104:20)\n at Context.resolveId (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:22865:28)\n at Object.resolveId (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:42793:46)\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\n at async TransformContext.resolve (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:42521:23)\nError: Missing \"./types/runtime/internal/lifecycle\" specifier in \"svelte\" package\n at e (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:16638:25)\n at n (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:16638:627)\n at o (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:16638:1297)\n at resolveExportsOrImports (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:23396:20)\n at resolveDeepImport (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:23415:31)\n at tryNodeResolve (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:23104:20)\n at Context.resolveId (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:22865:28)\n at Object.resolveId (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:42793:46)\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\n at async TransformContext.resolve (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:42521:23)\n```\n\nThis code even works in another project and I have checked to see that my configuration files are all good and they all seem fine. Maybe this project is corrupted?\n\nI tried going through config files: All seem to be fine.\nTried turning off typescript for the file: Still nothing.\nRestarted development server: Same issue.\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n import { getContext } from 'svelte';\n import HtmlGenerator from './generate_html';\n import type { Field } from './generate_html';\n import { setContext } from 'svelte/types/runtime/internal/lifecycle';\n import { UserContext } from '../../context';\n\n setContext('UserContext', UserContext);\n\n const { is_logged_in, user } = getContext('UserContext');\n</script>\n```\n\n```text\nInternal server error: Missing \"./types/runtime/internal/lifecycle\" specifier in \"svelte\" package\n Plugin: vite:import-analysis\n File: C:/javascript_projects/svelte_projects/reactable/src/routes/dashboard/form-builder/+page.svelte\n at e (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:16638:25)\n at n (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:16638:627)\n at o (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:16638:1297)\n at resolveExportsOrImports (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:23396:20)\n at resolveDeepImport (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:23415:31)\n at tryNodeResolve (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:23104:20)\n at Context.resolveId (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:22865:28)\n at Object.resolveId (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:42793:46)\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\n at async TransformContext.resolve (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:42521:23)\nError: Missing \"./types/runtime/internal/lifecycle\" specifier in \"svelte\" package\n at e (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:16638:25)\n at n (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:16638:627)\n at o (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:16638:1297)\n at resolveExportsOrImports (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:23396:20)\n at resolveDeepImport (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:23415:31)\n at tryNodeResolve (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:23104:20)\n at Context.resolveId (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:22865:28)\n at Object.resolveId (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:42793:46)\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\n at async TransformContext.resolve (file:///C:/javascript_projects/svelte_projects/reactable/node_modules/vite/dist/node/chunks/dep-24daf00c.js:42521:23)\n```\n\n```text\nMissing \"./types/runtime/internal/lifecycle\" specifier in \"svelte\" package\n```\n\n```text\nimport { setContext } from 'svelte';\n```\n\n```text\nsetContext\n```\n\n```text\n'svelte'\n```\n\n========================================\n\nComments:\n- Dang auto imports","metadata":{"transformedAt":"2026-08-18T18:33:40.689Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":120,"estimatedTokens":2015}}400{"id":"stack-73353392","source":"stackoverflow","questionId":73353392,"title":"Cannot access \"buffer.Buffer\" in client code (Svelte with Userbase)","tags":["typescript","svelte","sveltekit","svelte-3"],"text":"Title: Cannot access \"buffer.Buffer\" in client code (Svelte with Userbase)\nTags: typescript, svelte, sveltekit, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI'm writing an application using Svelte 3.44 and SvelteKit.\nI want to use Userbase (https://userbase.com/) for user authentication and data storage.\n\nI have a component *Login.svelte* in which I want to call Userbase API for signing up and logging in. The relevant code is:\n\n```\n\n import userbase from 'userbase-js';\n /* Irrelevant code here */\n\n```\n\nWhen I try to run this using `vite dev`, then instead of my Login component I see:\n\n```\n500\n\nModule \"buffer\" has been externalized for browser compatibility. Cannot access \"buffer.Buffer\" in client code.\n\nget@http://localhost:5173/node_modules/.vite/deps/userbase-js.js?v=b25ad0c3:151:17\nnode_modules/safe-buffer/index.js@http://localhost:5173/node_modules/.vite/deps/userbase-js.js?v=b25ad0c3:162:19\n__require@http://localhost:5173/node_modules/.vite/deps/chunk-TWLJ45QX.js?v=b25ad0c3:8:50\nnode_modules/randombytes/browser.js@http://localhost:5173/node_modules/.vite/deps/userbase-js.js?v=b25ad0c3:225:19\n__require@http://localhost:5173/node_modules/.vite/deps/chunk-TWLJ45QX.js?v=b25ad0c3:8:50\nnode_modules/diffie-hellman/lib/generatePrime.js@http://localhost:5173/node_modules/.vite/deps/userbase-js.js?v=b25ad0c3:3272:23\n__require@http://localhost:5173/node_modules/.vite/deps/chunk-TWLJ45QX.js?v=b25ad0c3:8:50\nnode_modules/diffie-hellman/browser.js@http://localhost:5173/node_modules/.vite/deps/userbase-js.js?v=b25ad0c3:3554:25\n__require@http://localhost:5173/node_modules/.vite/deps/chunk-TWLJ45QX.js?v=b25ad0c3:8:50\n@http://localhost:5173/node_modules/.vite/deps/userbase-js.js?v=b25ad0c3:6166:37\n```\n\nBrowsing for solutions I found two and none worked:\n\nUsing dynamic import with OnMount() seems to work, but I can't use the imported module anywhere else outside of OnMount() because of TypeScript type checking.\n\nAdding Userbase SDK from index.html and calling it with `window.userbase` didn't work, because I got `ReferenceError: window is not defined`. If I only use it inside OnMount(), then I'm back with problem number one.\n\nTo sum up:\nIf anyone has overcome the `Cannot access \"buffer.Buffer\" in client code` problem, please tell me how you did that.\nExcuse me if this is a stupid question, I'm an embedded developer, this is one of my first encounters with Web Development.\n\n========================================\n\nTop Answer:\nI cannot reproduce this exact issue, maybe you are using a different version of Vite. You could try to prevent `buffer` from being externalized by adding it to `ssr.noExternal`.\n\nI get a different error which also suggests that the module should be imported only in the browser.\n\nAccessing something outside of `onMount` is only a typing or scoping issue. If you import it in a component you can declare a variable outside of `onMount`. It will be undefined until the import has completed:\n\n```\n\n import { onMount } from 'svelte';\n import type { Userbase } from 'userbase-js';\n\n let userbase: Userbase | undefined;\n\n onMount(async () => {\n window.global = window; // If you get a \"global is not defined error\"\n userbase = await import('userbase-js').then(x => x.default);\n });\n\n```\n\nIf you import the script elsewhere globally, you should be able to access `window.userbase`, the type declaration files of the module already define this :\n\n```\n// Expose as userbase when loaded in an IIFE environment\nexport as namespace userbase\n```\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n import userbase from 'userbase-js';\n /* Irrelevant code here */\n</script>\n```\n\n```text\n500\n\nModule \"buffer\" has been externalized for browser compatibility. Cannot access \"buffer.Buffer\" in client code.\n\nget@http://localhost:5173/node_modules/.vite/deps/userbase-js.js?v=b25ad0c3:151:17\nnode_modules/safe-buffer/index.js@http://localhost:5173/node_modules/.vite/deps/userbase-js.js?v=b25ad0c3:162:19\n__require@http://localhost:5173/node_modules/.vite/deps/chunk-TWLJ45QX.js?v=b25ad0c3:8:50\nnode_modules/randombytes/browser.js@http://localhost:5173/node_modules/.vite/deps/userbase-js.js?v=b25ad0c3:225:19\n__require@http://localhost:5173/node_modules/.vite/deps/chunk-TWLJ45QX.js?v=b25ad0c3:8:50\nnode_modules/diffie-hellman/lib/generatePrime.js@http://localhost:5173/node_modules/.vite/deps/userbase-js.js?v=b25ad0c3:3272:23\n__require@http://localhost:5173/node_modules/.vite/deps/chunk-TWLJ45QX.js?v=b25ad0c3:8:50\nnode_modules/diffie-hellman/browser.js@http://localhost:5173/node_modules/.vite/deps/userbase-js.js?v=b25ad0c3:3554:25\n__require@http://localhost:5173/node_modules/.vite/deps/chunk-TWLJ45QX.js?v=b25ad0c3:8:50\n@http://localhost:5173/node_modules/.vite/deps/userbase-js.js?v=b25ad0c3:6166:37\n```\n\n```text\nvite dev\n```\n\n```text\nwindow.userbase\n```\n\n```text\nReferenceError: window is not defined\n```\n\n```text\nCannot access \"buffer.Buffer\" in client code\n```\n\n```html\n<script>\n/**\n * this is a hack for error: global is not defined\n */\nvar global = global || window\n</script>\n```\n\n```text\n<script>\n import { onMount } from 'svelte';\n import userbase from 'userbase-js';\n\n onMount(() => {\n userbase.init({ appId: '...' })\n });\n</script>\n```\n\n```text\n\"@sveltejs/kit\": \"next\"\n \"svelte\": \"^3.44.0\",\n \"typescript\": \"^4.7.4\",\n \"vite\": \"^3.0.4\"\n```\n\n```text\nbuffer\n```\n\n```text\n$ npm i buffer\n```\n\n```text\nindex.html\n```\n\n```html\n<script lang=\"ts\">\n import { onMount } from 'svelte';\n import type { Userbase } from 'userbase-js';\n\n let userbase: Userbase | undefined;\n\n onMount(async () => {\n window.global = window; // If you get a \"global is not defined error\"\n userbase = await import('userbase-js').then(x => x.default);\n });\n</script>\n```\n\n```js\n// Expose as userbase when loaded in an IIFE environment\nexport as namespace userbase\n```\n\n```text\nbuffer\n```\n\n```text\nssr.noExternal\n```\n\n```text\nonMount\n```\n\n```text\nonMount\n```\n\n```text\nwindow.userbase\n```\n\n```js\nexport default defineConfig({\n resolve: {\n alias: {\n util: 'util/',\n },\n },\n})\n```\n\n========================================\n\nComments:\n- I added `ssr: { noExternal: true,}` in `vite.config.js` to prevent anything from being externalized and used your code snippet, first importing type and then inside `onMount()` importing the userbase object. There is some progress - I can see my Login component now. Unfortunately, when I open the browser console I still see `Uncaught (in promise) Error: Module \"buffer\" has been externalized for browser compatibility. Cannot access \"buffer.Buffer\" in client code.` and I can see that the userbase variable is still undefined.\n- As I do not get the buffer error at all, I unfortunately cannot help with that\n- I just tested it and it works! Thank you. I wound up using a different architecture (my own server instead of Userbase) but hopefully this will help somebody else in the future.\n- Indeed, this pointed me out in the right direction. First installed buffer module `npm i buffer` then added the alias in `vite.config.ts` as described (replace `util` by `buffer`) above ! But this still lacks some explanation on why this problem occurs and why we need an alias ?","metadata":{"transformedAt":"2026-08-18T18:33:40.689Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":214,"estimatedTokens":1808}}401{"id":"stack-65198268","source":"stackoverflow","questionId":65198268,"title":"What is a svelte approach to showing a loader after a time of waiting?","tags":["svelte"],"text":"Title: What is a svelte approach to showing a loader after a time of waiting?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nTo show a loading spinner while waiting for a web request response, I'd use the following very simple if statement with my spinner component:\n\n```\n{#if waitingForAPIResponse}\n \n{/if}\n```\n\nWhat is a good approach to only show the Spinner component after, say, 200ms of waiting? I intuitively want to set up a timer, but I bet there's a better svelte approach.\n\n========================================\n\nTop Answer:\nYou could also include the waiting logic inside a `Loader` component\n\n```\n\n import { onDestroy } from \"svelte\";\n\n let show = false;\n const timeoutId = setTimeout(()=>show=true, 400);\n onDestroy(()=>clearTimeout(timeoutId));\n\n{#if show}\n \n{/if}\n```\n\nand then just use it like this\n\n```\n{#if waitingForAPIResponse}\n \n{/if}\n```\n\nit won't render the `` until the timeout is completed.\n\nYou can customize lots of things with this approach.\n\nYou could make the inner `` dynamic by using slots\n\n```\n...\n\n{#if show}\n \n \n \n{/if}\n```\n\nand now you could use it like this\n\n```\n{#if waitingForAPIResponse}\n \n \n \n{/if}\n```\n\nOf course, it would not be a *\"Loader\"* anymore, more like a *\"DelayedRenderer\"*\n\n========================================\n\nCode:\n```text\n{#if waitingForAPIResponse}\n <Spinner></Spinner>\n{/if}\n```\n\n```html\n<script>\n const wait = () => new Promise((res) => setTimeout(res , 1000))\n</script>\n\n{#await APIRequest}\n {#await wait()}\n <span>Not going to take long</span>\n {:then a}\n <span>Taking a while</span>\n {/await}\n{:then data}\n ...\n{/await}\n```\n\n```js\nconst wait = delay => new Promise((res) => setTimeout(res, delay))\n```\n\n```text\nwait\n```\n\n```html\n<script>\n import {onMount} from 'svelte'\n\n let response = null\n let timerOK = false\n \n $: isLoading = !(response && timerOK)\n \n onMount(() => {\n setTimeout(() => { \n timerOK = true\n }, 1200)\n\n fetch('...').then(callResponse => {\n // do your stuffs\n response = 'OK'\n })\n })\n</script>\n\n{#if isLoading}\n ...Loading\n{:else}\n {response}\n{/if}\n```\n\n```text\nsetTimeout\n```\n\n```text\ntimerOK\n```\n\n```text\nfalse\n```\n\n```text\ntrue\n```\n\n```html\n<!-- Loader.svelte -->\n\n<script>\n import { onDestroy } from \"svelte\";\n\n let show = false;\n const timeoutId = setTimeout(()=>show=true, 400);\n onDestroy(()=>clearTimeout(timeoutId));\n</script>\n\n{#if show}\n <Spinner/>\n{/if}\n```\n\n```html\n{#if waitingForAPIResponse}\n <Loader/>\n{/if}\n```\n\n```html\n...\n\n{#if show}\n <slot>\n <Spinner/>\n </slot>\n{/if}\n```\n\n```html\n{#if waitingForAPIResponse}\n <Loader>\n <Spinnerv2/>\n </Loader>\n{/if}\n```\n\n```text\nLoader\n```\n\n```text\n<Spinner/>\n```\n\n```text\n<Spinner/>\n```\n\n========================================\n\nComments:\n- Thank you, a second variable at least looks neater than what I was planning. But still, it doesn't look very svelte for what I'd think is a common situation!\n- How would you manage this with several promises or reactive blocks on a single page?","metadata":{"transformedAt":"2026-08-18T18:33:40.689Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":203,"estimatedTokens":774}}402{"id":"stack-67135169","source":"stackoverflow","questionId":67135169,"title":"How to initialize ApolloClient in SvelteKit to work on both SSR and client side","tags":["apollo","svelte","sveltekit"],"text":"Title: How to initialize ApolloClient in SvelteKit to work on both SSR and client side\nTags: apollo, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI tried but didn't work. Got an error: Error when evaluating SSR module /node_modules/cross-fetch/dist/browser-ponyfill.js:\n\n```\n\nimport fetch from 'cross-fetch';\nimport { ApolloClient, InMemoryCache, HttpLink } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n ssrMode: true,\n link: new HttpLink({ uri: '/graphql', fetch }),\n uri: 'http://localhost:4000/graphql',\n cache: new InMemoryCache()\n });\n\n```\n\n========================================\n\nTop Answer:\nTwo things to have in mind when using phaleth solution above: caching and authenticated requests.\n\nSince the client is used in the endpoint /qry/test.js, the singleton pattern with the caching behavior makes your server stateful. So if A then B make the same query B could end up seeing some of A data.\n\nSame problem if you need authorization headers in your query. You would need to set this up in the setupClient method like so\n\n```\nsetupClient(sometoken) {\n ...\n\n const authLink = setContext((_, { headers }) => {\n return {\n headers: {\n ...headers,\n authorization: `Bearer ${sometoken}`\n }\n };\n });\n\n const client = new ApolloClient({\n credentials: 'include',\n link: authLink.concat(link),\n cache: new InMemoryCache()\n });\n}\n```\n\nBut then with the singleton pattern this becomes problematic if you have multiple users.\n\nTo keep your server stateless, a work around is to avoid the singleton pattern and create a `new Client(sometoken)` in the endpoint.\n\nThis is not an optimal solution: it recreates the client on each request and basically just erases the cache. But this solves the caching and authorization concerns when you have multiple users.\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\nimport fetch from 'cross-fetch';\nimport { ApolloClient, InMemoryCache, HttpLink } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n ssrMode: true,\n link: new HttpLink({ uri: '/graphql', fetch }),\n uri: 'http://localhost:4000/graphql',\n cache: new InMemoryCache()\n });\n</script>\n```\n\n```sh\nnpm init svelte@next demo-app\ncd demo-app\n```\n\n```json\n{\n \"name\": \"demo-app\",\n \"version\": \"0.0.1\",\n \"scripts\": {\n \"dev\": \"svelte-kit dev\",\n \"build\": \"svelte-kit build --verbose\",\n \"preview\": \"svelte-kit preview\"\n },\n \"devDependencies\": {\n \"@apollo/client\": \"^3.3.15\",\n \"@sveltejs/adapter-node\": \"next\",\n \"@sveltejs/kit\": \"next\",\n \"graphql\": \"^15.5.0\",\n \"node-fetch\": \"^2.6.1\",\n \"svelte\": \"^3.37.0\"\n },\n \"type\": \"module\",\n \"dependencies\": {\n \"@fontsource/fira-mono\": \"^4.2.2\",\n \"@lukeed/uuid\": \"^2.0.0\",\n \"cookie\": \"^0.4.1\"\n }\n}\n```\n\n```js\nimport node from '@sveltejs/adapter-node';\n\nexport default {\n kit: {\n // By default, `npm run build` will create a standard Node app.\n // You can create optimized builds for different platforms by\n // specifying a different adapter\n adapter: node(),\n\n // hydrate the <div id=\"svelte\"> element in src/app.html\n target: '#svelte'\n }\n};\n```\n\n```js\nimport fetch from 'node-fetch';\nimport { ApolloClient, HttpLink } from '@apollo/client/core/core.cjs.js';\nimport { InMemoryCache } from '@apollo/client/cache/cache.cjs.js';\n\nclass Client {\n constructor() {\n if (Client._instance) {\n return Client._instance\n }\n Client._instance = this;\n\n this.client = this.setupClient();\n }\n\n setupClient() {\n const link = new HttpLink({\n uri: 'http://localhost:4000/graphql',\n fetch\n });\n\n const client = new ApolloClient({\n link,\n cache: new InMemoryCache()\n });\n return client;\n }\n}\n\nexport const client = (new Client()).client;\n```\n\n```js\nimport { client } from '$lib/Client.js';\nimport { gql } from '@apollo/client/core/core.cjs.js';\n\nexport const post = async request => {\n const { num } = request.body;\n\n try {\n const query = gql`\n query Doubled($x: Int) {\n double(number: $x)\n }\n `;\n const result = await client.query({\n query,\n variables: { x: num }\n });\n\n return {\n status: 200,\n body: {\n nodes: result.data.double\n }\n }\n } catch (err) {\n return {\n status: 500,\n error: 'Error retrieving data'\n }\n }\n}\n```\n\n```js\ntry {\n const res = await fetch('/qry/test', {\n method: 'POST',\n credentials: 'same-origin',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n num: 19\n })\n });\n const data = await res.json();\n console.log(data);\n } catch (err) {\n console.error(err);\n }\n```\n\n```text\n.js\n```\n\n```text\nsrc/routes\n```\n\n```text\n.js\n```\n\n```text\n@apollo/client\n```\n\n```text\nreact\n```\n\n```text\n@apollo/client/core\n```\n\n```text\n@apollo/client\n```\n\n```text\nN\n```\n\n```text\npackage.json\n```\n\n```text\nnpx npm-check-updates -u\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nsrc/lib/Client.js\n```\n\n```text\nsrc/routes/qry/test.js\n```\n\n```text\ndouble\n```\n\n```text\nload\n```\n\n```text\nroutes/todos/index.svelte\n```\n\n```text\n<script context=\"module\">...</script>\n```\n\n```text\nnpm install\n```\n\n```text\nnpm run dev\n```\n\n```text\nTODOS\n```\n\n```text\ntest\n```\n\n```text\nclient\n```\n\n```js\nsetupClient(sometoken) {\n ...\n\n const authLink = setContext((_, { headers }) => {\n return {\n headers: {\n ...headers,\n authorization: `Bearer ${sometoken}`\n }\n };\n });\n\n const client = new ApolloClient({\n credentials: 'include',\n link: authLink.concat(link),\n cache: new InMemoryCache()\n });\n}\n```\n\n```text\nnew Client(sometoken)\n```\n\n========================================\n\nComments:\n- thanks!, the imports didnt really work for me like you had them. I simply have `import { ApolloClient, HttpLink, InMemoryCache } from \"@apollo/client/core\";`\n- In that kind of scenario I'd recommend switching from the `@apollo/client/core` package to the `@urql/core` package as `urql` holds onto the client instance by itself. The `urql` API is not that different from `apollo`'s. In case you're interested have a look at their addAuthToOperation.","metadata":{"transformedAt":"2026-08-18T18:33:40.689Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":323,"estimatedTokens":1622}}403{"id":"stack-74220753","source":"stackoverflow","questionId":74220753,"title":"Svelte path to a static folder","tags":["path","svelte","sveltekit"],"text":"Title: Svelte path to a static folder\nTags: path, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI use Sveltekit and put some images in my static folder. Static > images > image1.png etc.\n\nWithin source, src, I have a folder called `lib` and inside `lib` a folder called `components` and in there a file `Footer.svelte`. In that file I want to reference to my image1 (which has an absolute path of `~/myapp/static/images/image1.png`. Even when I try this path it throws me an error.\n\nSo:\n`src > lib > components > Footer.svelte`\n\n`static > images > image1.png`\n\nBoth `src` and `static` are in root dir of `myapp`.\n\nAnd this line in my `Footer.svelte`:\n`import Image from '~/myapp/static/images/image1.png';`\n\nWhats the correct line in my `Footer.svelte` for grabbing `image1.png`?\n\nSee in problem description.\n\n========================================\n\nCode:\n```text\nlib\n```\n\n```text\nlib\n```\n\n```text\ncomponents\n```\n\n```text\nFooter.svelte\n```\n\n```text\n~/myapp/static/images/image1.png\n```\n\n```text\nsrc > lib > components > Footer.svelte\n```\n\n```text\nstatic > images > image1.png\n```\n\n```text\nsrc\n```\n\n```text\nstatic\n```\n\n```text\nmyapp\n```\n\n```text\nFooter.svelte\n```\n\n```text\nimport Image from '~/myapp/static/images/image1.png';\n```\n\n```text\nFooter.svelte\n```\n\n```text\nimage1.png\n```\n\n```html\n<img src=\"/images/image1.png\" />\n```\n\n```js\nimport image from '$lib/.../image1.png';\n```\n\n```html\n<img src={image} ... />\n```\n\n```text\nstatic\n```\n\n```text\nsrc/lib\n```\n\n```text\nrobots.txt\n```\n\n```text\n$lib\n```\n\n```text\nfiles\n```\n\n```text\nlib\n```\n\n========================================\n\nComments:\n- How to access via API though or application code?\n- What exactly do you mean? (If you are talking about dynamic files (upload/download) that is completely different beast.)","metadata":{"transformedAt":"2026-08-18T18:33:40.689Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":123,"estimatedTokens":443}}404{"id":"stack-71573868","source":"stackoverflow","questionId":71573868,"title":"Svelte alias/rename props","tags":["svelte","svelte-component"],"text":"Title: Svelte alias/rename props\nTags: svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nIs there any way to rename/alias props in svelte?\n\nFor example, if I have a component which takes a `foo` prop but I also want a `foo` local variable for the current state, is there any way to rename the incoming prop a bit like this:\n\n```\nexport let foo as forceFoo;\nlet foo = forceFoo | null;\n```\n\nNormally the correct answer is one of these two:\n\n- Rename the prop to something like `initialFoo`\n\n- Rename the state\n\nRenaming the prop is not appropriate in this case - it's the public API of the component and it's not an initial state, it's an optional override that forces the value of that field.\n\nRenaming the state is ok for a single field and usually works well for generic components, but becomes horrible and unwieldy when the component is a form with many fields and has to pass those fields on to a save function that expects them to have the right names.\n\n========================================\n\nCode:\n```text\nexport let foo as forceFoo;\nlet foo = forceFoo | null;\n```\n\n```text\nfoo\n```\n\n```text\nfoo\n```\n\n```text\ninitialFoo\n```\n\n```html\n<script>\n // aliased prop\n let forceFoo\n export { forceFoo as foo }\n\n // local state\n let foo = forceFoo\n</script>\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":54,"estimatedTokens":319}}405{"id":"stack-70099100","source":"stackoverflow","questionId":70099100,"title":"How would i make an each loop in svelte reactive","tags":["javascript","svelte"],"text":"Title: How would i make an each loop in svelte reactive\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\ni have this svelte code:\n\n```\n\n {#await connectprom}\n \n \n Username\n \n \n {:then}\n \n Welcome, {username}\n\n \n \n Message:\n \n \n {#each messages as msg}\n \n {/each}\n {/await}\n```\n\nIs It Possible for the #each statement to run reactively? If not is there a workaround to do so?\n\n========================================\n\nCode:\n```html\n<!--connectprom is a Promise that resolves when connect is ran--->\n {#await connectprom}\n <!--User hasnt yet connected to the server-->\n <form on:submit|preventDefault={connect}>\n <label for=\"un\">Username</label>\n <input type=\"text\" id=\"un\">\n </form>\n {:then}\n <!--After the form was submited (user is connected)--> \n Welcome, <p class=\"name text-blue-300\">{username}</p>\n <!--When send is ran it sends the data from the form to the socket.io server-->\n <form class=\"shadow-lg rounded-lg\" on:submit|preventDefault={send} align=\"center\">\n <label for=\"msg\">Message:</label>\n <input type=\"text\" id=\"msg\">\n </form>\n {#each messages as msg}\n <Message username=msg.username content=msg.content/>\n {/each}\n {/await}\n```\n\n```js\nnumbers = [] //TODO: We want a function that adds an item to the end of the array, that is the array Length + 1, so after a few runs it should look like this: [1,2,3,4, ...]\n\n//This doesn't work\nfunction addNumber() {\n numbers.push(numbers.length + 1); //The variable is not reassigned\n}\n\n//This does work!\nfunction addNumber() {\n numbers.push(numbers.length + 1);\n numbers = numbers; //This is the reassignment\n}\n\n// OR\nfunction addNumber() {\n numbers = [...numbers, numbers.length + 1]; //And this is also the reassignment\n}\n```\n\n```js\nmessages = [] //TODO: Have a function that appends a message to the array and forces the {#each} \"loop\" to update\n\n//This doesn't work\nfunction addMessage(newMessage) {\n messages.push(newMessage); // It's just adding to the array but the array isn't \"registered\" as updated\n}\n\n//This does work!\nfunction addMessage(newMessage) {\n messages.push(newMessage);\n messages = messages; //This is the reassignment and causes the update\n}\n\n// OR\nfunction addMessage(newMessage) {\n messages = [...messages, newMessage]; //Another way to add to it and reassign it to also cause an update\n}\n```\n\n```text\n{#each}\n```\n\n```text\nmessages\n```\n\n```text\nmessages\n```\n\n========================================\n\nComments:\n- Hi. Don't forget to accept the answer if it solved your problem.\n- **Thanks so much!, My code works now.**\n- Can you mark your question as answered, so that it gets closed ?\n- yes sorry im kinda new to stackoverflow","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":116,"estimatedTokens":679}}406{"id":"stack-68455191","source":"stackoverflow","questionId":68455191,"title":"Svelte how to get text value after click on element ('li')?","tags":["svelte"],"text":"Title: Svelte how to get text value after click on element ('li')?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nhow can i get text value in Svelte if i click on element ?\n\nI need update variable if i click on element - li item.\n\nmy code :\n\n```\n\n let languages = ['sk','cz','en','at']\n let activeLang = 'en'\n\n {#each languages as language }\n \n- {language}\n {/each}\n\n```\n\nmany thanks for your help.\n\n========================================\n\nCode:\n```text\n<script>\n let languages = ['sk','cz','en','at']\n let activeLang = 'en'\n</script>\n<ul>\n {#each languages as language }\n <li on:click={activeLang = ???} >{language}</li>\n {/each}\n</ul>\n```\n\n```js\n<script>\n let languages = ['sk','cz','en','at']\n let activeLang = 'en'\n</script>\n\n<ul>\n {#each languages as language }\n <li on:click={(event) => activeLang = event.target.innerText} >{language}</li>\n {/each}\n</ul>\n```\n\n```html\n<script>\n let languages = ['sk','cz','en','at']\n let activeLang = 'en'\n</script>\n\n<ul>\n {#each languages as language }\n <li on:click={() => activeLang = language} >{language}</li>\n {/each}\n</ul>\n```\n\n```text\non:click\n```\n\n```text\nevent\n```\n\n```text\ninnerText\n```\n\n```text\nli\n```\n\n```text\nevent.target.innerText\n```\n\n```text\nlanguage\n```\n\n```text\nactiveLang\n```\n\n========================================\n\nComments:\n- Perfect @johannchopin, works correctly. Many thanks","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":98,"estimatedTokens":348}}407{"id":"stack-69228124","source":"stackoverflow","questionId":69228124,"title":"How to get params of a POST endpoint with SvelteKit?","tags":["svelte","sveltekit"],"text":"Title: How to get params of a POST endpoint with SvelteKit?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nThe SvelteKit documentation gives an example for how to write GET endpoints with parameters...\n\n```\nexport async function get({ params }) { /* [...] */ }\n```\n\n...and how to write POST endpoints without parameters...\n\n```\nexport function post(request) { /* [...] */ }\n```\n\nHow do I write POST endpoints with parameters? More precisely: What is the function signature that I have to use if I want to access both the parameters and the request body in my endpoint?\n\n========================================\n\nTop Answer:\nFor anyone else who might be stuck with the GET method.\nThe parameters for the GET request has changed.\n**Params** has been replaced by **url**.\n\n```\nexport async function GET({url}) {...}\n```\n\nThe query parameters can then be extracted from the searchParams objects.\n\n```\nconst text = url.searchParams.get('text');\n```\n\n========================================\n\nCode:\n```text\nexport async function get({ params }) { /* [...] */ }\n```\n\n```text\nexport function post(request) { /* [...] */ }\n```\n\n```js\nexport function post({ params, body }) { /* [...] */ }\n```\n\n```text\nPOST\n```\n\n```text\nRequestHandler\n```\n\n```text\nServerRequest\n```\n\n```text\nPOST\n```\n\n```text\nbody\n```\n\n```text\nContent-Type\n```\n\n```text\nexport async function GET({url}) {...}\n```\n\n```text\nconst text = url.searchParams.get('text');\n```\n\n========================================\n\nComments:\n- How do I actually get the body, or the formdata?? everything i try fails. Even if I what it says in the error it fails...... THE ERROR: To access the request body use the text/json/arrayBuffer/formData methods, e.g. `body = await request.json()`","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":87,"estimatedTokens":435}}408{"id":"stack-75041833","source":"stackoverflow","questionId":75041833,"title":"Is it possible to not reset an enhanced SvelteKit form after successful submit?","tags":["svelte","sveltekit"],"text":"Title: Is it possible to not reset an enhanced SvelteKit form after successful submit?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have the following enhanced SvelteKit form:\n\n```\n\n import { enhance } from '$app/forms';\n\n \n\n```\n\nWhen it is submitted successfully the form is reset. Is there any way to avoid this?\n\n========================================\n\nTop Answer:\nIf you (like me) want to have an action that works like `enhance` but that never resets the entered values in the ``, I think you can use the following `customEnhance` that I just wrote for this specific purpose:\n\n**custom-enhance.js**\n\n```\nimport { enhance } from '$app/forms';\n\nexport function customEnhance(form, submitFunction) {\n\n function customSubmitFunction() {\n return async (actionResult) => {\n await actionResult.update({reset: false})\n if(submitFunction){\n await submitFunction(actionResult)\n }\n }\n }\n\n return enhance(form, customSubmitFunction)\n\n}\n```\n\n**+page.svelte**\n\n```\n\nimport { customEnhance } from './custom-enhance'\n\n \n ...\n\n```\n\nI haven't tested it much yet, so no guarantees I got the implementation right, but works good for me so far :)\n\n========================================\n\nCode:\n```html\n<script>\n import { enhance } from '$app/forms';\n</script>\n\n<form method=\"POST\" use:enhance>\n <input name=\"name\" />\n</form>\n```\n\n```html\n<script>\n import { enhance } from '$app/forms';\n\n function handleSubmit() {\n // ...\n\n return async ({ update }) => {\n await update({ reset: false });\n };\n }\n</script>\n\n<form method=\"POST\" use:enhance={handleSubmit}>\n <input name=\"name\" />\n</form>\n```\n\n```text\nenhance\n```\n\n```text\nsubmit function\n```\n\n```text\nupdate\n```\n\n```text\nreset\n```\n\n```js\nimport { enhance } from '$app/forms';\n\nexport function customEnhance(form, submitFunction) {\n\n function customSubmitFunction() {\n return async (actionResult) => {\n await actionResult.update({reset: false})\n if(submitFunction){\n await submitFunction(actionResult)\n }\n }\n }\n\n return enhance(form, customSubmitFunction)\n\n}\n```\n\n```html\n<script>\nimport { customEnhance } from './custom-enhance'\n</script>\n<form method=\"POST\" use:customEnhance>\n <!-- Does never reset form values, but does otherwise work like \"enhance\". -->\n ...\n</form>\n```\n\n```text\nenhance\n```\n\n```text\n<form>\n```\n\n```text\ncustomEnhance\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":143,"estimatedTokens":597}}409{"id":"stack-72816085","source":"stackoverflow","questionId":72816085,"title":"Deploy static Svelte-Kit app with AWS Amplify","tags":["amazon-web-services","aws-amplify","svelte","sveltekit"],"text":"Title: Deploy static Svelte-Kit app with AWS Amplify\nTags: amazon-web-services, aws-amplify, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm trying to deploy my Svelte app on AWS Amplify, I push the commits, Amplify builds and verifies the app, but then if I visit the app URL it's just a blank page, it might be an adapter problem? I tried the node.js and static ones but no luck\n\n========================================\n\nTop Answer:\nIf you want to deploy a Sveltekit application to AWS Amplify. You need to use the `@sveltejs/adapter-static`, since it will serve your app via a static CDN.\n\nOnce you change the adapter, make sure to add a fallback in `svelte.config.js`:\n\n```\n// svelte.config.js\nimport adapter from '@sveltejs/adapter-static';\n\nexport default {\n kit: {\n adapter: adapter({\n fallback: 'index.html'\n })\n }\n};\n```\n\n========================================\n\nCode:\n```js\nimport adapter from '@sveltejs/adapter-static';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n kit: {\n adapter: adapter(),\n prerender: {\n default: true\n }\n }\n};\n\nexport default config;\n```\n\n```js\n// svelte.config.js\nimport adapter from '@sveltejs/adapter-static';\n\nexport default {\n kit: {\n adapter: adapter({\n fallback: 'index.html'\n })\n }\n};\n```\n\n```text\n@sveltejs/adapter-static\n```\n\n```text\nsvelte.config.js\n```\n\n========================================\n\nComments:\n- It works without but without the fallback and it needs \"prerender default\" to true","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":71,"estimatedTokens":379}}410{"id":"stack-69295473","source":"stackoverflow","questionId":69295473,"title":"Svelte/SvelteKit: Dynamic import of components with variable","tags":["import","svelte","dynamic-import","sveltekit"],"text":"Title: Svelte/SvelteKit: Dynamic import of components with variable\nTags: import, svelte, dynamic-import, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI want to dynamically import components without importing a specific component.\nI want to set the component name with a variable, received from the store:\n\n```\n\n // SVELTE\n import { onMount } from 'svelte';\n\n // STORE\n import { dynamicComponent } from '$stores/dynamicTitle';\n\n $: $dynamicComponent;\n console.log($dynamicComponent)\n\n \n let renderDynamicComponent\n \n\n onMount(async () => { \n const importValue = (await import(`../../lib/components/Home/DynamicComponents/${String($dynamicComponent)}.svelte`)).default;\n // const importValue = (await import(`../../lib/components/Home/DynamicComponents/IntroSectionCustom.svelte`)).default;\n renderDynamicComponent = importValue\n });\n\n```\n\nBut I get:\n\n```\nUncaught (in promise) TypeError: Failed to fetch dynamically imported module: http://localhost:3000/src/lib/components/Home/DynamicComponents/Intro-Section-Custom.svelte\n```\n\nI do not understand. From the error, it seems to be the right path ...\n\n========================================\n\nTop Answer:\nThe Rollup plugin @rollup/plugin-dynamic-import-vars might be of help here. I haven't used it with SvelteKit specifically, but it worked fine with standard Svelte with Vite as bundler.\n\n```\n// Example.svelte\nfunction importLocale(locale) {\n return import(`./locales/${locale}.js`);\n}\n```\n\n```\n// vite.config.js\nimport dynamicImportVars from '@rollup/plugin-dynamic-import-vars';\n\nexport default (mode) =>\n defineConfig({\n plugins: [\n dynamicImportVars({\n include: './src/Example.svelte'\n })\n ]\n});\n```\n\nSvelteKit uses Vite behind the scenes, but has its own configuration format. In `svelte.config.js`, pass `dynamicImportVars()` to the `config.vite.plugins` key:\n\n```\n// svelte.config.js\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n vite: {\n plugins: [\n dynamicImportVars({\n include: './src/Example.svelte'\n })\n ]\n }\n};\n\nexport default config;\n```\n\nPlease take note of the limitations mentioned in the README of the Rollup plugin.\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n // SVELTE\n import { onMount } from 'svelte';\n\n // STORE\n import { dynamicComponent } from '$stores/dynamicTitle';\n\n\n $: $dynamicComponent;\n console.log($dynamicComponent)\n\n \n let renderDynamicComponent\n \n\n onMount(async () => { \n const importValue = (await import(`../../lib/components/Home/DynamicComponents/${String($dynamicComponent)}.svelte`)).default;\n // const importValue = (await import(`../../lib/components/Home/DynamicComponents/IntroSectionCustom.svelte`)).default;\n renderDynamicComponent = importValue\n });\n\n<svelte:component this={renderDynamicComponent}/>\n```\n\n```text\nUncaught (in promise) TypeError: Failed to fetch dynamically imported module: http://localhost:3000/src/lib/components/Home/DynamicComponents/Intro-Section-Custom.svelte\n```\n\n```js\nlet thing = 'Thing';\nThing = (await import(`./${thing}.svelte`)).default; // this won't work\nThing = (await import(`./Thing.svelte`)).default; // this will work\n```\n\n```js\n// Example.svelte\nfunction importLocale(locale) {\n return import(`./locales/${locale}.js`);\n}\n```\n\n```js\n// vite.config.js\nimport dynamicImportVars from '@rollup/plugin-dynamic-import-vars';\n\nexport default (mode) =>\n defineConfig({\n plugins: [\n dynamicImportVars({\n include: './src/Example.svelte'\n })\n ]\n});\n```\n\n```js\n// svelte.config.js\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n vite: {\n plugins: [\n dynamicImportVars({\n include: './src/Example.svelte'\n })\n ]\n }\n};\n\nexport default config;\n```\n\n```text\nsvelte.config.js\n```\n\n```text\ndynamicImportVars()\n```\n\n```text\nconfig.vite.plugins\n```\n\n```js\nlet renderDynamicComponent\n```\n\n```html\n$: renderDynamicComponent = null\n```\n\n```text\nrenderDynamicComponent\n```\n\n```text\nsvelte:component\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":187,"estimatedTokens":999}}411{"id":"stack-71003501","source":"stackoverflow","questionId":71003501,"title":"SvelteKit: config.kit.target is no longer required, and should be removed","tags":["svelte","sveltekit"],"text":"Title: SvelteKit: config.kit.target is no longer required, and should be removed\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nCompile time error - config.kit.target is no longer required, and should be removed\n\nWhen you runs the svelteKit app.","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":8,"estimatedTokens":64}}412{"id":"stack-67379787","source":"stackoverflow","questionId":67379787,"title":"Get/Read Value From Svelte Store","tags":["svelte","svelte-3","svelte-store"],"text":"Title: Get/Read Value From Svelte Store\nTags: svelte, svelte-3, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI want to read svelte store value at any given time. I understand subscribe method gets called when the value is updated. I want to read store even if there is no update on store.\n\n========================================\n\nTop Answer:\nIn `.svelte` files, see @Shriji's answer. In TypeScript/JavaScript, use the `get` function\n\n```\nimport { get } from 'svelte/store';\n\nconst value = get(store);\n```\n\nNote (from the Svelte docs):\n\nThis works by creating a subscription, reading the value, then unsubscribing. It's therefore not recommended in hot code paths.\n\nSo if you do this often, create a subscription and keep a local variable, that stores the current value:\n\n```\nlet currentValue: number = -1;\n\nconst unsubscribe = store.subscribe((value) => {\n currentValue= value;\n});\n\n// example usage, e.g. in a websocket handler:\nconst onmessage = async (event: MessageEvent) => {\n console.debug(\"Current count:\", currentValue);\n}\n\n// TODO: use `unsubscribe` function, if required\n```\n\n========================================\n\nCode:\n```html\n<script>\n import { count } from './stores.js';\n</script>\n\n<h1>\n {$count}\n</h1>\n```\n\n```js\nimport { writable } from 'svelte/store';\n\nexport const count = writable(0);\n```\n\n```text\n$\n```\n\n```js\nimport { get } from 'svelte/store';\n\nconst value = get(store);\n```\n\n```js\nlet currentValue: number = -1;\n\nconst unsubscribe = store.subscribe((value) => {\n currentValue= value;\n});\n\n// example usage, e.g. in a websocket handler:\nconst onmessage = async (event: MessageEvent<any>) => {\n console.debug(\"Current count:\", currentValue);\n}\n\n// TODO: use `unsubscribe` function, if required\n```\n\n```text\n.svelte\n```\n\n```text\nget\n```\n\n========================================\n\nComments:\n- I'm going to add the text 'what does $ in front of a variable mean in Svelte' so other people find this answer. There, done!","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":95,"estimatedTokens":489}}413{"id":"stack-67943713","source":"stackoverflow","questionId":67943713,"title":"Svelte - hide and show nav on scroll","tags":["javascript","svelte"],"text":"Title: Svelte - hide and show nav on scroll\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI want the nav to hide scrolling down 60px and to show when scrolling up 60px, no matter in which part of the page.\n\nI did this, but it's incomplete, what am I missing?\n\n```\n\n let y = 0;\n\n 60}>\n \n \n- link\n \n\nnav {\n position: fixed;\n top: 0;\n}\n\n.hideNav {\n top: -70px;\n}\n\n```\n\n========================================\n\nTop Answer:\nThe answers here couldn't help me. So here's a REPL I made for what I'm using to achieve this in `svelte:window`.\nHow I did it;\n\n- Create a variable that will store the scroll position (in `px`) at the end of the scroll event - [let's call it `lastScrollPosition`].\n\n\r\n\r\n\n```\nlet lastScrollPosition = 0\n```\n\n\r\n\r\n\r\n\n- At the beginning of a scroll event; inside `svelte:window`, get and compare the current scroll position to the last scroll position variable we created in [1.] (`lastScrollPosition`)\n\n\r\n\r\n\n```\n{\n var currentScrollposition = window.pageYOffset || document.documentElement.scrollTop; //Get current scroll position\n if (currentScrollposition > lastScrollPosition) {\n showNav = false\n }else{ \n showNav = true\n }\n lastScrollPosition = currentScrollposition;\n }}>\n```\n\n\r\n\r\n\r\n\nIf current scroll Position is greater than `lastScrollPosition`, `showNav` is false else, true.\nNB: You can use `CSS` or Svelte Conditional (`{#if}`) to achieve the hide on scroll down and show on scroll up (This example shows CSS..).\n\n\r\n\r\n\n```\n\n Nav bar\n\n \n Content\n \n\n .nav{\n background-color: gray;\n padding: 6px;\n position: fixed;\n top: 0;\n width: 100%;\n }\n .content{\n background-color: green;\n margin-top: 25px;\n padding: 6px;\n width: 100%;\n height: 2300px;\n }\n .hide{\n display: none;\n }\n .show{\n display: unset;\n }\n\n```\n\n========================================\n\nCode:\n```text\n<script>\n let y = 0;\n</script>\n\n<svelte:window bind:scrollY=\"{y}\" />\n\n<nav class:hideNav={y > 60}>\n <ul>\n <li>link</li>\n </ul>\n</nav>\n\n<style>\nnav {\n position: fixed;\n top: 0;\n}\n\n.hideNav {\n top: -70px;\n}\n</style>\n```\n\n```svelte\n<script>\n import {onMount, onDestroy} from 'svelte'\n const scrollNavBar = 60\n let show = false\n onMount(() => {\n window.onscroll = () => {\n if (window.scrollY > scrollNavBar) {\n show = true\n } else {\n show = false\n }\n }\n })\n \n onDestroy(() => {\n window.onscroll = () => {}\n })\n</script>\n\n<style>\n\n .scrolled {\n \n transform: translate(0,calc(-100% - 1rem))\n }\n \n nav {\n width: 100%;\n position: fixed;\n box-shadow: 0 -0.4rem 0.9rem 0.2rem rgb(0 0 0 / 50%);\n padding: 10px;\n transition: 0.5s ease\n \n }\n :global(body) {\n margin: 0;\n padding: 0;\n height: 200vh;\n }\n</style>\n\n<nav class:scrolled={show}>\n elemnt\n</nav>\n```\n\n```text\n// Hide Header on on scroll down\nvar didScroll;\nvar lastScrollTop = 0;\nvar delta = 5;\nvar navbarHeight = $('header').outerHeight();\n\n$(window).scroll(function(event){\n didScroll = true;\n});\n\nsetInterval(function() {\n if (didScroll) {\n hasScrolled();\n didScroll = false;\n }\n}, 250);\n\nfunction hasScrolled() {\n var st = $(this).scrollTop();\n \n // Make sure they scroll more than delta\n if(Math.abs(lastScrollTop - st) <= delta)\n return;\n \n // If they scrolled down and are past the navbar, add class .nav-up.\n // This is necessary so you never see what is \"behind\" the navbar.\n if (st > lastScrollTop && st > navbarHeight){\n // Scroll Down\n $('header').removeClass('nav-down').addClass('nav-up');\n } else {\n // Scroll Up\n if(st + $(window).height() < $(document).height()) {\n $('header').removeClass('nav-up').addClass('nav-down');\n }\n }\n \n lastScrollTop = st;\n}\n```\n\n```js\nlet lastScrollPosition = 0\n```\n\n```js\n<svelte:window on:scroll={()=>{\n var currentScrollposition = window.pageYOffset || document.documentElement.scrollTop; //Get current scroll position\n if (currentScrollposition > lastScrollPosition) {\n showNav = false\n }else{ \n showNav = true\n }\n lastScrollPosition = currentScrollposition;\n }}></svelte:window>\n```\n\n```html\n<main>\n<div class=\"nav {showNav == true? \"show\": \"hide\" }\" >\n Nav bar\n</div>\n <div class=\"content\">\n Content\n </div>\n</main>\n\n<style>\n .nav{\n background-color: gray;\n padding: 6px;\n position: fixed;\n top: 0;\n width: 100%;\n }\n .content{\n background-color: green;\n margin-top: 25px;\n padding: 6px;\n width: 100%;\n height: 2300px;\n }\n .hide{\n display: none;\n }\n .show{\n display: unset;\n }\n</style>\n```\n\n```text\nsvelte:window\n```\n\n```text\npx\n```\n\n```text\nlastScrollPosition\n```\n\n```text\nsvelte:window\n```\n\n```text\nlastScrollPosition\n```\n\n```text\nlastScrollPosition\n```\n\n```text\nshowNav\n```\n\n```text\nCSS\n```\n\n```text\n{#if}\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":308,"estimatedTokens":1247}}414{"id":"stack-70875634","source":"stackoverflow","questionId":70875634,"title":"How to setup turborepo with sveltekit and pnpm","tags":["svelte","monorepo","sveltekit","turborepo"],"text":"Title: How to setup turborepo with sveltekit and pnpm\nTags: svelte, monorepo, sveltekit, turborepo\nSource: Stack Overflow\n\nQuestion:\nI am trying to add Turborepo to my Svelte apps but looks like the `npx create-turbo@latest` command and also the examples currently only support NextJs. How can I configure it to work Svelte and Sveltekit apps?\n\n========================================\n\nCode:\n```text\nnpx create-turbo@latest\n```\n\n```text\n{\n“name”: “uikit”,\n“version”: “0.0.0\",\n“main”: “./index.svelte”,\n“types”: “./index.svelte”,\n“devDependencies”: {\n “svelte”: “^3.44.0”\n}\n```\n\n```text\n{\n “pipeline”: {\n “build”: {\n “dependsOn”: [“^build”],\n “outputs”: [“dist/**“, “.svelte-kit/**“, “.svelte/**“]\n },\n “lint”: {\n “outputs”: []\n },\n “dev”: {\n “cache”: false\n }\n }\n}\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run build\n```\n\n========================================\n\nComments:\n- Sounds like this could be of interest reddit.com/r/sveltejs/comments/sd9meg/…\n- There is an open issue here: github.com/sveltejs/kit/issues/2973","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":55,"estimatedTokens":268}}415{"id":"stack-59166364","source":"stackoverflow","questionId":59166364,"title":"Svelte: Using reactive statement based on module context variable","tags":["svelte","svelte-component"],"text":"Title: Svelte: Using reactive statement based on module context variable\nTags: svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI want to use code shared across multiple instances of a component to initiate code within each component.\n\nI've attempted to do this using a reactive statement:\n\n```\n\n let what = 0;\n\n export let number;\n $: if (what === number) [...]\n\n```\n\nBut changes to `what` don't trigger a re-run of that reactive statement.\n\nWhy doesn't this REPL work, and how can I fix it?\n\nhttps://svelte.dev/repl/38b94490982f4f3c80644fd364b50723?version=3.16.0\n\n========================================\n\nCode:\n```js\n<script context=\"module\">\n let what = 0;\n</script>\n\n<script>\n export let number;\n $: if (what === number) [...]\n</script>\n```\n\n```text\nwhat\n```\n\n```js\n<script context=\"module\">\n import { writable } from 'svelte/store';\n const what = writable(0);\n</script>\n\n<script>\n export let number;\n $: if ($what === number) [...]\n</script>\n```\n\n```text\nwhat\n```\n\n```text\nwritable\n```\n\n========================================\n\nComments:\n- Using a store in a `context=\"module\"` script is indeed the recommended way to do this. \"Variables defined in `module` scripts are not reactive — reassigning them will not trigger a rerender even though the variable itself will update. For values shared between multiple components, consider using a `store`.\"","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":66,"estimatedTokens":347}}416{"id":"stack-69091120","source":"stackoverflow","questionId":69091120,"title":"How to add Google Adsense to a Svelte/Sapper web app?","tags":["svelte","adsense","sapper"],"text":"Title: How to add Google Adsense to a Svelte/Sapper web app?\nTags: svelte, adsense, sapper\nSource: Stack Overflow\n\nQuestion:\nI am trying to get AdSense setup in my Sapper built website but I have had no success. I have added the code to the template.html file and it works, but I will like to show this on a specific page using a component.\n\nThe goal is to show the Ad in the Resource page, on the sidebar (see image). The widget above it, is a component that is loaded by the index.svelte page, so I'll like to do the same for the Ad.\n\nresource page\n\nAt the moment, I have the following:\n\n- The AdSense script in the template.html file, and then\n\n- On the component OnMount function, I am grabbing the Adsense code from the template.html file and placing it on the component inside a div, then removing it from the template.html file.\n\ntemplate.html\n\n```\n\n \n \n \n \n \n \n (adsbygoogle = window.adsbygoogle || []).push({});\n \n \n\n```\n\nadswidget.svelte\n\n```\n\n import { onMount } from 'svelte';\n\nonMount(() => {\n\n window.addEventListener( 'load', () => {\n //get ads-widget div\n let adWidget = document.getElementById('ads-widget');\n let adCode = document.getElementById('gAdsense-code');\n let adHtml = adCode.innerHTML;\n\n adCode.remove();\n \n //append Adsence code from the head on resources index file\n adWidget.innerHTML = adHtml;\n });\n});\n\n```\n\nThis will place the Adsense code in the right place, but the Ad will not display.\nThe error I get on the console is: \"adsbygoogle.push() error: No slot size for availableWidth=0\" (see image)\nconsole error\n\nI have also referenced this article w/o success.\n\nAny help would be greatly appreciated :)\n\n========================================\n\nCode:\n```text\n<footer>\n <!-- GoogleAdsence Script. -->\n <div id=\"gAdsense-code\" style=\"display: none;\">\n <script async src=\"https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-X0X0X0X0X0X0X\" crossorigin=\"anonymous\"></script>\n <!-- Resource page Ad -->\n <ins class=\"adsbygoogle\"\n style=\"display:block\"\n data-ad-client=\"ca-pub-X0X0X0X0X0X0X\"\n data-ad-slot=\"X0X0X0X0X0X0\"\n data-ad-format=\"auto\"\n data-full-width-responsive=\"true\"></ins>\n <script>\n (adsbygoogle = window.adsbygoogle || []).push({});\n </script> \n </div>\n</footer>\n```\n\n```text\n<script>\n\n import { onMount } from 'svelte';\n\nonMount(() => {\n\n window.addEventListener( 'load', () => {\n //get ads-widget div\n let adWidget = document.getElementById('ads-widget');\n let adCode = document.getElementById('gAdsense-code');\n let adHtml = adCode.innerHTML;\n\n adCode.remove();\n \n //append Adsence code from the head on resources index file\n adWidget.innerHTML = adHtml;\n });\n});\n</script>\n\n<div id=\"ads-widget\"><!-- Adsence code inserted onMount --></div>\n```\n\n```text\n... \n <script async src=\"https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-X0X0X0X0X0X0X\" crossorigin=\"anonymous\"></script>\n </body>\n</html>\n```\n\n```text\n<script>\n onMount(() => {\n (window.adsbygoogle = window.adsbygoogle || []).push({});\n });\n</script>\n\n<style>\n...\n</style>\n\n<div class=\"ads-widget-container\">\n <ins class=\"adsbygoogle\"\n style=\"display:block\"\n data-ad-client=\"ca-pub-X0X0X0X0X0X0X\"\n data-ad-slot=\"X0X0X0X0X0X0\"\n data-ad-format=\"auto\"\n data-full-width-responsive=\"true\"></ins>\n</div>\n```\n\n```text\n(adsbygoogle = window.adsbygoogle ...)\n```\n\n```text\n(window.adsbygoogle = window.adsbygoogle ...)\n```\n\n```text\n<ins>\n```\n\n========================================\n\nComments:\n- Is this answer still up to date?","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":154,"estimatedTokens":936}}417{"id":"stack-61452073","source":"stackoverflow","questionId":61452073,"title":"Is it possible to render SVG elements directly in Svelte?","tags":["javascript","svg","svelte","rollup"],"text":"Title: Is it possible to render SVG elements directly in Svelte?\nTags: javascript, svg, svelte, rollup\nSource: Stack Overflow\n\nQuestion:\nI am trying to import and render SVG's in Svelte.\n\nI am using @rollup/plugin-url to import the SVG code like so:\n\n```\n\n import arrowCircle from \"heroicons/dist/solid-sm/sm-arrow-circle-up.svg\"\n\n \n\n```\n\nNow this works (in terms of the SVG content getting brought in) but it renders the following screen:\n\nhttps://i.sstatic.net/t9EnU.png\n\nhttps://i.sstatic.net/Bs1Ir.png\n\nIdeally I would like to use the `` element so I can apply classes to the SVG but given the error I thought I would have a go with the `` tag to see if this would at least render the SVG, but instead got this:\n\n```\n\n```\n\nI also tried just `{arrowCircle}` but that rendered the above image `src` as plain text.\n\nFrom what I can tell it is to do with the `data` prefix that is part of the raw import.\n\nI am aware of the codefeathers/rollup-plugin-svelte-svg plugin but would like to be able to do be able to do this without another plugin if possible, or at least understand what is going on.\n\nFor reference SVG are valid in both `` tags as well as `` as per this article.\n\n========================================\n\nCode:\n```text\n<script>\n import arrowCircle from \"heroicons/dist/solid-sm/sm-arrow-circle-up.svg\"\n</script>\n\n<main>\n <object title=\"Arrow Circle\" type=\"image/svg+xml\" data={arrowCircle}></object>\n</main>\n```\n\n```text\n<img src=\"data:image/svg+xml,%3Csvg%20viewBox%3D%220%200%2020%2020%22%20fill%3D%22currentColor%22%3E%20%20%3Cpath%20fill-rule%3D%22evenodd%22%20d%3D%22M10%2018a8%208%200%20100-16%208%208%200%20000%2016zm3.707-8.707l-3-3a1%201%200%2000-1.414%200l-3%203a1%201%200%20001.414%201.414L9%209.414V13a1%201%200%20102%200V9.414l1.293%201.293a1%201%200%20001.414-1.414z%22%20clip-rule%3D%22evenodd%22%2F%3E%3C%2Fsvg%3E\">\n```\n\n```text\n<object />\n```\n\n```text\n<img />\n```\n\n```text\n{arrowCircle}\n```\n\n```text\nsrc\n```\n\n```text\ndata\n```\n\n```text\n<img />\n```\n\n```text\n<object />\n```\n\n```html\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" ...>...</svg>\n```\n\n========================================\n\nComments:\n- Did you try adding the missing namespaces? developer.mozilla.org/en-US/docs/Web/SVG/…\n- @RobertLongson do you mean to the SVG's themselves?\n- Yes, they are not valid SVG without namespces.\n- If an option you can rename your files to `.svelte` and use them as any other component, it will inline the SVG.\n- Hmmm I can see that they don't have the namespaces but I am also able to paste the raw SVG input in and they work...\n- I've since realized the SVG's I want to load are intended for inline use only, which means I could use something like github.com/sionzeecz/rollup-plugin-inline-svg#readme or find another library, in terms of fixing the issue at hand your answer is correct.","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":96,"estimatedTokens":714}}418{"id":"stack-58527265","source":"stackoverflow","questionId":58527265,"title":"Redirect the user after a form submission","tags":["svelte","sapper"],"text":"Title: Redirect the user after a form submission\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI have an `` as a search bar inside a ``.\n\nBecause it's a search bar the user should be redirected to a route similar to : `/search?q=thingIWantToSearch` when the form is submited.\n\nCurrently I'm doing with a `location.href` but I don't think this is a good way of doing it (or is it?)\n\nHere's my code :\n\n```\n\n let inputValue = '';\n\n const handleSubmit = () => {\n // there should be some parsing before putting it in the url, but it's not the subject\n location.href = `/search?q=${inputValue}`;\n }\n\n \n submit\n\n```\n\nSo how can I properly redirect the user on form submission?\n\n========================================\n\nCode:\n```text\n<script>\n let inputValue = '';\n\n const handleSubmit = () => {\n // there should be some parsing before putting it in the url, but it's not the subject\n location.href = `/search?q=${inputValue}`;\n }\n</script>\n\n<form on:submit|preventDefault={handleSubmit}>\n <input type=\"text\" bind:value={inputValue} />\n <button type=\"submit\">submit</button>\n</form>\n```\n\n```text\n<input type=\"text\" />\n```\n\n```text\n<form>\n```\n\n```text\n/search?q=thingIWantToSearch\n```\n\n```text\nlocation.href\n```\n\n```text\n<script>\n import { goto } from '$app/navigation';\n\n let inputValue = '';\n\n const handleSubmit = () => {\n // there should be some parsing before putting it in the url, but it's not the subject\n goto(`/search?q=${inputValue}`);\n };\n</script>\n\n<form on:submit|preventDefault=\"{handleSubmit}\">\n <input type=\"text\" bind:value=\"{inputValue}\" />\n <button type=\"submit\">submit</button>\n</form>\n```\n\n```text\ngoto\n```\n\n```text\n$app/navigation\n```\n\n========================================\n\nComments:\n- Look into the History API, specifically the `replaceState()` function.\n- @BennyHinrichs is this \"friendly\" for sapper's router ?\n- @BennyHinrichs sapper seems to give an `id` property to `history.state` that increment every time something is pushed to the history. That mean a `replaceState()` should manually increment the `id` to keep the history intact. The issue is if sapper change his way to manage the history, it could create some unexpected bugs and force me to update every redirections.\n- Oh, I didn't see the Sapper tag!\n- This is what I needed. Thanks you !\n- |preventDefault did the trick for me! Thanks a lot <3\n- this works in sveltekit as well\n- In SvelteKit use: import { goto } from '$app/navigation';","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":101,"estimatedTokens":619}}419{"id":"stack-76352088","source":"stackoverflow","questionId":76352088,"title":"Sveltekit is not intercepting fetch call in handleFetch hook","tags":["javascript","svelte","fetch-api","sveltekit","svelte-3"],"text":"Title: Sveltekit is not intercepting fetch call in handleFetch hook\nTags: javascript, svelte, fetch-api, sveltekit, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI recently discovered the `handleFetch` hook in Sveltekit. Now I'm trying to use it to intercept calls to my backend (written in Go) but doesn't seem to work (unless I'm missing something).\n\nThe documentation reads:\n\nThis function allows you to modify (or replace) a fetch request that happens inside a load or action function that runs on the server (or during pre-rendering).\n\nI've got `src\\hooks.server.js`:\n\n```\n/** @type {import('@sveltejs/kit').HandleFetch} */\nexport async function handleFetch({ request, fetch }) {\n console.log(\"HERE IN --------> HANDLE FETCH HOOK\")\n\n return fetch(request);\n}\n```\n\nAs you can see I'm just trying to make sure the hooks is called by printing a message on the terminal.\n\nI've got a `load` function in `src\\routes\\records\\+page.server.js`:\n\n```\nexport async function load() {\n console.log(\"HERE IN LOAD\")\n // const records = await getAllRecords(1, 10);\n const response = await fetch(`http://127.0.0.1:8080/api/v1/records?page=1&per_page=2`);\n const records = await response.json();\n console.log(await records);\n return records;\n}\n```\n\nAlthough I see the `HERE IN LOAD` message and the response being printed I never see the message that indicates that the hook was hit.\n\nWhat am I missing?\n\nThanks\n\n========================================\n\nCode:\n```text\n/** @type {import('@sveltejs/kit').HandleFetch} */\nexport async function handleFetch({ request, fetch }) {\n console.log(\"HERE IN --------> HANDLE FETCH HOOK\")\n\n return fetch(request);\n}\n```\n\n```text\nexport async function load() {\n console.log(\"HERE IN LOAD\")\n // const records = await getAllRecords(1, 10);\n const response = await fetch(`http://127.0.0.1:8080/api/v1/records?page=1&per_page=2`);\n const records = await response.json();\n console.log(await records);\n return records;\n}\n```\n\n```text\nhandleFetch\n```\n\n```text\nsrc\\hooks.server.js\n```\n\n```text\nload\n```\n\n```text\nsrc\\routes\\records\\+page.server.js\n```\n\n```text\nHERE IN LOAD\n```\n\n```js\nexport async function load({ fetch }) { // destructure `fetch` from the first argument\n console.log(\"HERE IN LOAD\")\n // const records = await getAllRecords(1, 10);\n const response = await fetch(`http://127.0.0.1:8080/api/v1/records?page=1&per_page=2`);\n const records = await response.json();\n console.log(await records);\n return records;\n}\n```\n\n```text\nfetch\n```\n\n```text\nload\n```\n\n```text\nload\n```\n\n========================================\n\nComments:\n- Yes, that did work. Thanks Patrick. It's a bit of a let down, I was expecting to intercept any fetch. As you can see, my original call is to `const records = await getAllRecords(1, 10);` which lives in a separate file where I grouped all the API calls to the backend for `records`. That file structure won't work anymore, either I change it or pass `fetch` into that `getAllRecords` call (which doesn't look neat to me)\n- @MrCujo This is unfortunately a pain point when dealing with common api functions that should work in both client and server. The svelte repo has a discussion opened for about 3 years about this exact issue github.com/sveltejs/kit/discussions/5173","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":114,"estimatedTokens":816}}420{"id":"stack-69654704","source":"stackoverflow","questionId":69654704,"title":"How do I create a custom input svelte component and reuse prop types?","tags":["typescript","svelte"],"text":"Title: How do I create a custom input svelte component and reuse prop types?\nTags: typescript, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a wrapped version of an input component with a label, I want it to have all the same attributes as the normal input field, as well as the \"label\".\n\nI'm slightly confused about how to import the type definition and to type the attributes properly.\n\n```\n\n input {\n width: 100%;\n display: block;\n }\n\n import { SvelteInputProps } from 'svelte'\n export let label: string = '' \n type $$Props = SvelteInputProps;\n\n {label}\n \n\n```\n\nlike this in react:\n\n```\ninterface Props extends React.InputHTMLAttributes {\n label: string\n}\n\nexport default function Input (props: Props) {\n const { label, ...inputProps } = props;\n return (\n \n {label}\n \n \n )\n}\n```\n\n========================================\n\nTop Answer:\nIf you use svelte for vscode, there's a namespace already declared in the global scope (pretty much like the HTML typings provided by vscode), which is `svelte.JSX.SvelteInputProps`, I think that's what you're looking for. If you don't like the idea of rely on in-editor types (which is pretty reasonable) you can install the types directly in your project. If you wan't the very same interface, this is the project, but there are alternatives on definetely typed or go for js-dom types.\n\n========================================\n\nCode:\n```text\n<style>\n input {\n width: 100%;\n display: block;\n }\n</style>\n\n<script lang=\"typescript\">\n import { SvelteInputProps } from 'svelte'\n export let label: string = '' \n type $$Props = SvelteInputProps;\n</script>\n\n<label>\n {label}\n <input {...$$props} />\n</label>\n```\n\n```text\ninterface Props extends React.InputHTMLAttributes<HTMLInputElement> {\n label: string\n}\n\nexport default function Input (props: Props) {\n const { label, ...inputProps } = props;\n return (\n <label>\n {label}\n <input {...inputProps}></input>\n </label>\n )\n}\n```\n\n```html\n<style>\n input {\n width: 100%;\n display: block;\n }\n</style>\n\n<script lang=\"ts\">\n import type { SvelteInputProps } from './filepath-to-your-typings'\n export let label: string = '' \n interface $$Props extends SvelteInputProps {\n label: string;\n }\n</script>\n\n<label>\n {label}\n <input {...$$restProps} />\n</label>\n```\n\n```text\n$$props\n```\n\n```text\n$$restProps\n```\n\n```text\n$$restProps\n```\n\n```text\nexport\n```\n\n```text\nlabel\n```\n\n```text\nlang=\"typescript\"\n```\n\n```text\nlang=\"ts\"\n```\n\n```text\ninterface $$Props extends .. { label: string }\n```\n\n```text\n..\n```\n\n```text\n<script lang=\"ts\"> //here I use ts\n\n export enum TextType { text = \"text\", email = \"email\", password = \"password\" } // svelte creats differently input when it is type text and differently when type is a number. Probably it is due to propreties \"max\" and \"min\" \n\n //here are exported props \n export let type: TextType;\n export let label: string | null = null;\n export let placeholder: string | null = null;\n export let value: string | null = null;\n\n function typeAction(node: HTMLInputElement) {\n node.type = type\n }//this function helps to define type of input \n\n</script>\n\n<div class=\"myInput\">\n <label class=\"myLabel\">{label}\n <input on:input bind:value type=\"text\" placeholder={ placeholder } \n use:typeAction/>\n </label>\n</div>\n```\n\n```text\nsvelte.JSX.SvelteInputProps\n```\n\n========================================\n\nComments:\n- This makes a lot of sense thanks for the `import type` nod as well. Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":178,"estimatedTokens":892}}421{"id":"stack-64627741","source":"stackoverflow","questionId":64627741,"title":"How to remove livereload on production?","tags":["github-pages","svelte","livereload"],"text":"Title: How to remove livereload on production?\nTags: github-pages, svelte, livereload\nSource: Stack Overflow\n\nQuestion:\nI managed to deploy my first Svelte app using Github Pages. Only a problem remains is that the **livereload script** is still loading but the path to the script cannot be found and causes the slow finishing load as you can see in the live site.\n\nIs there any way to fix this?\n\nThank you for your help in advance.\n(The source code if it helps)\n\n========================================\n\nCode:\n```text\nnpm run dev\n```\n\n```text\nnpm run build\n```\n\n```text\nrollup.config.js\n```\n\n```text\nproduction\n```\n\n========================================\n\nComments:\n- Hello rixo, you're absolutely right. Thank you for your help.\n- Does the same thing apply to react apps? I've been scouring the internet and tons of purple links later, I still cant seem to figure out why I'm getting livereload?snipver=1 when I deploy a production build using npm run build. I know this is a couple years old now but any bit of help is greatly appreciated!","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":36,"estimatedTokens":262}}422{"id":"stack-57385113","source":"stackoverflow","questionId":57385113,"title":"Call the javascript function and render element in Svelte","tags":["svelte","svelte-component"],"text":"Title: Call the javascript function and render element in Svelte\nTags: svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nHow do I add a custom function call in svelte code? Eg. in the DataTableTest.svelte, I want to add the cellFormatter function and make it call automatically and render the div inside the . Following are code :\n\nABC.svelte\n \n\n```\nimport DataTableTest from \"./DataTableTest.svelte\";\n\nlet columns = [\n {\n label: \"ABC\",\n property: \"abc\"\n },\n {\n label: \"Items\",\n property: \"items\"\n },\n {\n label: \"cellFormatter\",\n formatter: function(rowIndex, rowData) {\n return \"\" + rowData[rowIndex] + \"\";\n }\n }\n ];\n\nlet data = [\n {\n \"abc\": \"dsaaads\",\n \"items\": \"dsadsads\",\n }\n\n```\n\nDataTableTest.svelte\n\n```\n\n export let title;\n export let data;\n export let columns = [];\n\n{title}\n\n {#if columns}\n \n {#each columns as c}\n {c.label}\n {/each}\n \n {/if}\n {#if data}\n \n {#each data as d, i}\n \n {#each columns as c}\n {#if c.formatter}\n \n {:else}\n \n {@html d[c.property] ? d[c.property] : ''}\n \n {/if}\n {/each}\n \n {/each}\n \n {/if}\n\n```\n\nI gave a try with \n\n```\n\n```\n\nBut this does not work? Can someone tell how can I do that here?\n\n========================================\n\nTop Answer:\nAs @morphyish mentioned, you can use the `@html` template syntax to insert arbitrary html into the DOM.\n\nThis is useful if the html for your table items is dynamically fetched from an API at runtime for example – when your web app is not in control of the generation of that html.\n\nIf that's not the case, and your web app is in control of generating the html, then instead of constructing a html string, I would recommend creating separate components and referencing those, utilising the `` special element to render the components. That way everything in your table is actually a svelte component rather than some arbitrary html, and you get all the goodies that svelte offers.\n\nHere's an example of something along those lines: https://svelte.dev/repl/e38138607bc445ea95754de83e5e0b8d?version=3.8.0\n\n========================================\n\nCode:\n```text\nimport DataTableTest from \"./DataTableTest.svelte\";\n\nlet columns = [\n {\n label: \"ABC\",\n property: \"abc\"\n },\n {\n label: \"Items\",\n property: \"items\"\n },\n {\n label: \"cellFormatter\",\n formatter: function(rowIndex, rowData) {\n return \"<div>\" + rowData[rowIndex] + \"</div>\";\n }\n }\n ];\n\n\nlet data = [\n {\n \"abc\": \"dsaaads\",\n \"items\": \"dsadsads\",\n }\n\n</script>\n\n\n<DataTableTest title=\"Test\" {data} {columns} />\n```\n\n```text\n<script>\n export let title;\n export let data;\n export let columns = [];\n</script>\n\n{title}\n<table>\n {#if columns}\n <tr>\n {#each columns as c}\n <td>{c.label}</td>\n {/each}\n </tr>\n {/if}\n {#if data}\n <tbody>\n {#each data as d, i}\n <tr>\n {#each columns as c}\n {#if c.formatter}\n <td on:load=c.formatter(i, d)></td>\n {:else}\n <td>\n {@html d[c.property] ? d[c.property] : ''}\n </td>\n {/if}\n {/each}\n </tr>\n {/each}\n </tbody>\n {/if}\n</table>\n```\n\n```text\n<td on:load=c.formatter(i, d)></td>\n```\n\n```html\n{#if c.formatter}\n <td>\n {@html c.formatter(i, d)}\n </td>\n{:else}\n <td>\n {@html d[c.property] ? d[c.property] : ''}\n </td>\n{/if}\n```\n\n```text\n@html\n```\n\n```text\n@html\n```\n\n```text\n<svelte:component>\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":193,"estimatedTokens":855}}423{"id":"stack-66818754","source":"stackoverflow","questionId":66818754,"title":"Svelte store subscribed function should not be invoked on subscription","tags":["svelte","svelte-store"],"text":"Title: Svelte store subscribed function should not be invoked on subscription\nTags: svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI don't understand this. I am trying to subscribe to a svelte store. But the closure function which is being passed to ***subscribe*** is being immediately invoked. Even though the value of the store hasn't changed.\n\nHere's a svelte REPL **example**\n\nwith the following code:\n\n```\n\n import { onDestroy } from 'svelte';\n import { writable } from 'svelte/store';\n \n const store = writable({ givenName: '', familyName: '' });\n \n const unsubscribe = store.subscribe( state => {\n console.log('This function shouldn\\'t have been invoked on subscription.');\n });\n onDestroy(unsubscribe);\n\n Please check the console output ...\n\n```\n\nIMHO, the closure function should be fired on change and not on subscriptionn or is there something I am missing?\n\n========================================\n\nTop Answer:\nSome other obervations.\n\nA javasript function always returns a value. Even if you don't return a value the function returns undefined.\n\nA store always returns \"**the current value**\" when you subscribe. So the store always returns a value when you subscribe. Or do you like to wait for the next change if you are the first subscriber. Or wait forever if you missed the first one. Maybe the next change will never arrive.\n\nOfcourse it's quite easy to skip the initial value. Or a special initial value.\n\n========================================\n\nCode:\n```js\n<script>\n import { onDestroy } from 'svelte';\n import { writable } from 'svelte/store';\n \n const store = writable({ givenName: '', familyName: '' });\n \n const unsubscribe = store.subscribe( state => {\n console.log('This function shouldn\\'t have been invoked on subscription.');\n });\n onDestroy(unsubscribe);\n</script>\n\n<h1>\n Please check the console output ...\n</h1>\n```\n\n```js\nfunction subscribeIgnoreFirst(store, fn) {\n let firedFirst = false;\n return store.subscribe(state => {\n if (!firedFirst) {\n firedFirst = true;\n } else {\n fn(state);\n }\n })\n }\n```\n\n```text\nwritable\n```\n\n```text\nsubscribe\n```\n\n========================================\n\nComments:\n- Thanks very much! So that's intended behaviour. I hate it when my intuition leads me down the wrong path.","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":86,"estimatedTokens":593}}424{"id":"stack-60118489","source":"stackoverflow","questionId":60118489,"title":"Svelte/Sapper How to fetch data from internal api without giving absolute URL","tags":["svelte","sapper"],"text":"Title: Svelte/Sapper How to fetch data from internal api without giving absolute URL\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI am using svelte/sapper with express. \n\nI have an api in `routes/billing/index.js` \n\nIt needs to fetch data from `customers/[customernumber]/detections.js`\n\nMy question is how to fetch data from internal apis with in the routes folder using relative URLs\n\n```\nasync function getDataFromGateway(customerNumber) {\n if (typeof fetch !== 'function') {\n global.fetch = require('node-fetch')\n }\n const data = await fetch(`http://localhost:19052/customers/${customerNumber}/detections`)\n .then(res => res.json())\n .catch(error => {\n console.log(error)\n return error\n }\n )\n return data\n}\n```\n\nIs there a way to do this using relative url\n\n========================================\n\nCode:\n```text\nasync function getDataFromGateway(customerNumber) {\n if (typeof fetch !== 'function') {\n global.fetch = require('node-fetch')\n }\n const data = await fetch(`http://localhost:19052/customers/${customerNumber}/detections`)\n .then(res => res.json())\n .catch(error => {\n console.log(error)\n return error\n }\n )\n return data\n}\n```\n\n```text\nroutes/billing/index.js\n```\n\n```text\ncustomers/[customernumber]/detections.js\n```\n\n```html\n<script context=\"module\">\n export async function preload(page, session) {\n const r = await this.fetch(`customers/${getCustomerNumber(session)}/detections`);\n const data = await r.json();\n\n return {\n foo: data.foo\n };\n }\n</script>\n```\n\n```js\nasync function getDataFromGateway(customerNumber) {\n if (typeof fetch !== 'function') {\n global.fetch = require('node-fetch')\n }\n const data = await fetch(`${process.env.BASE_URL}/customers/${customerNumber}/detections`)\n .then(res => res.json())\n .catch(error => {\n console.log(error)\n return error\n }\n )\n return data\n}\n```\n\n```text\npreload\n```\n\n```text\nthis.fetch\n```\n\n```text\nBASE_URL\n```\n\n========================================\n\nComments:\n- Thanks Harris. Appreciate your time. But is there a way we can use `this.fetch` outside ``, in a javaScript file\n- No, because it's contextual — it resolves URLs relative to the route that's being prepared\n- Been discussing this in sapper discord channel. Isn't making an http request a bit of an unnecessary overhead and inefficient / slow? What about calling into the same code that `/customers/${customerNumber}/detections` triggers if you know you are on the server, and do the fetch if you know you are on the client?\n- I'll be writing an RFC soon that addresses this very topic","metadata":{"transformedAt":"2026-08-18T18:33:40.690Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":106,"estimatedTokens":653}}425{"id":"stack-70570231","source":"stackoverflow","questionId":70570231,"title":"How to load Google API client library with SvelteKit","tags":["google-api","svelte","workbox","sveltekit"],"text":"Title: How to load Google API client library with SvelteKit\nTags: google-api, svelte, workbox, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm new to SvelteKit and trying to find out how to load the Google client library for Javascript.\n\nGoogle tells me to do it like this:\n\n```\n\n \n \n function start() {\n // Initializes the client with the API key and the Translate API.\n gapi.client.init({\n 'apiKey': 'YOUR_API_KEY',\n 'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/translate/v2/rest'],\n }).then(function() {\n // Executes an API request, and returns a Promise.\n // The method name `language.translations.list` comes from the API discovery.\n return gapi.client.language.translations.list({\n q: 'hello world',\n source: 'en',\n target: 'de',\n });\n }).then(function(response) {\n console.log(response.result.data.translations[0].translatedText);\n }, function(reason) {\n console.log('Error: ' + reason.result.error.message);\n });\n };\n\n // Loads the JavaScript client library and invokes `start` afterwards.\n gapi.load('client', start);\n \n \n```\n\nThe problem is that SvelteKit doesn't allow 2 or more script tags on a page (I don't want it to be the layout page).\n\n```\n\n import { onMount } from 'svelte';\n \n gapi.client.init({...\n\n```\n\nThis results in follwing error message:\n\n```\nA component can only have one instance-level element\n```\n\nAs my intention is to create a progressive web app (PWA) using Workbox I don't want to import the Google library as described here because the package containing this library would become too heavy.\n\nAny ideas how to load the Google client library? Maybe there's a Workbox way to do it? Couldn't find a SvelteKit example on Google or YouTube.\n\nThanks in advance\n\n========================================\n\nTop Answer:\nI've made something like this.\nSave it as GoogleMap.svelte to your lib folder. and use it like this;\n\n```\n {\n console.log('MAP SAYS IM LOADED');\n }}\n/>\n```\n\n- Map is a reference object\n\n- `globally` defines it to `window.map`\n\n```\n\n import { onMount } from 'svelte';\n import { createEventDispatcher } from 'svelte';\n const dispatch = createEventDispatcher();\n \n //import mapStyles from './map-styles'; // optional\n \n export let globally = false;\n export let map;\n\n let src = '';\n const key = ''; \n \n // @ts-ignore\n let container;\n let zoom = 8;\n let center = { lat: 37.5742776, lng: 43.7260158 };\n \n onMount(() => {\n Object.assign(window, {\n mapLoaded: () => {\n // @ts-ignore\n map = new google.maps.Map(container, {\n zoom,\n center\n // styles: mapStyles\n });\n dispatch('load', true);\n if (globally) {\n Object.assign(window, { map });\n }\n }\n });\n\n //Assign\n src = `https://maps.googleapis.com/maps/api/js?key=${key}&callback=mapLoaded`;\n });\n \n \n\n \n \n {#if src}\n \n {/if}\n \n```\n\n========================================\n\nCode:\n```text\n<head>\n <script src=\"https://apis.google.com/js/api.js\"></script>\n <script>\n function start() {\n // Initializes the client with the API key and the Translate API.\n gapi.client.init({\n 'apiKey': 'YOUR_API_KEY',\n 'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/translate/v2/rest'],\n }).then(function() {\n // Executes an API request, and returns a Promise.\n // The method name `language.translations.list` comes from the API discovery.\n return gapi.client.language.translations.list({\n q: 'hello world',\n source: 'en',\n target: 'de',\n });\n }).then(function(response) {\n console.log(response.result.data.translations[0].translatedText);\n }, function(reason) {\n console.log('Error: ' + reason.result.error.message);\n });\n };\n\n // Loads the JavaScript client library and invokes `start` afterwards.\n gapi.load('client', start);\n </script>\n </head>\n```\n\n```text\n<script src=\"https://apis.google.com/js/api.js\"></script>\n<script>\n import { onMount } from 'svelte';\n \n gapi.client.init({...\n</script>\n```\n\n```text\nA component can only have one instance-level <script> element\n```\n\n```text\n<script>\n const start = async () => {\n // Initializes the client with the API key and the Translate API.\n // @ts-ignore\n gapi.client.init({\n 'apiKey': 'YOUR_API_KEY',\n 'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/translate/v2/rest'],\n }).then(function() {\n // Executes an API request, and returns a Promise.\n // The method name `language.translations.list` comes from the API discovery.\n return gapi.client.language.translations.list({\n q: 'hello world',\n source: 'en',\n target: 'de',\n });\n }).then(function(response) {\n console.log(response.result.data.translations[0].translatedText);\n }, function(reason) {\n console.log('Error: ' + reason.result.error.message);\n });\n };\n\n const initializeGapi = async () => {\n gapi.load('client', start);\n }\n</script>\n\n<svelte:head>\n <script src=\"https://apis.google.com/js/api.js\" on:load={initializeGapi}></script>\n</svelte:head>\n```\n\n```text\nsvelte:head\n```\n\n```text\n<GoogleMap\n {map}\n globally\n on:load={() => {\n console.log('MAP SAYS IM LOADED');\n }}\n/>\n```\n\n```text\n<script>\n import { onMount } from 'svelte';\n import { createEventDispatcher } from 'svelte';\n const dispatch = createEventDispatcher();\n \n //import mapStyles from './map-styles'; // optional\n \n export let globally = false;\n export let map;\n\n let src = '';\n const key = ''; \n \n // @ts-ignore\n let container;\n let zoom = 8;\n let center = { lat: 37.5742776, lng: 43.7260158 };\n \n onMount(() => {\n Object.assign(window, {\n mapLoaded: () => {\n // @ts-ignore\n map = new google.maps.Map(container, {\n zoom,\n center\n // styles: mapStyles\n });\n dispatch('load', true);\n if (globally) {\n Object.assign(window, { map });\n }\n }\n });\n\n //Assign\n src = `https://maps.googleapis.com/maps/api/js?key=${key}&callback=mapLoaded`;\n });\n </script>\n \n<!-- This is tailwind css class change with whatever fits to your case. -->\n <div class=\"w-full h-full\" bind:this={container} />\n <svelte:head>\n {#if src}\n <script {src}></script>\n {/if}\n </svelte:head>\n```\n\n```text\nglobally\n```\n\n```text\nwindow.map\n```\n\n========================================\n\nComments:\n- Thanks for your reply! When doing a build I get following error: \"'initializeGapi' is not defined\". The on:load part can't reference to the const initializeGapi\n- I am not sure what you copied. But if you insert this into your index.svelte it runs fine. At least it does on my PC.\n- Strange. Have to figure out what the problem is on my side. I don't have the code on index.svelte but on another page but that shouldn't make a difference imho\n- I got it working by adding this at the top of the .svelte file ` export const ssr = false `","metadata":{"transformedAt":"2026-08-18T18:33:40.691Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":284,"estimatedTokens":1801}}426{"id":"stack-77934659","source":"stackoverflow","questionId":77934659,"title":"How can I dynamically import images stored in $lib within a component in Svelte?","tags":["image","dynamic","vite","svelte","sveltekit"],"text":"Title: How can I dynamically import images stored in $lib within a component in Svelte?\nTags: image, dynamic, vite, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm using an array of dummy data to test how I could display information from an api. In that data, I have a relative image path, for some images I've stored locally in `$lib` for simplicity in testing.\n\nI loop through each object in this dataset, and create a component with the relative image path passed to the object. In my testing the relative paths are resolving correctly, but I'm unable to load the images dynamically.\n\nAfter doing a bit of digging, it seems that this is because of the file structure and permissions with `$lib`. It seems that image import is easy to do if I use a static solution with the images, and just dynamically adjust the relative url, but I want to be able to use Vite's performance improvements when it comes to images. Indeed, Sveltekit documentation recommends storing images in a directory within `$lib` for this exact reason.\n\nIn the component I can manually import each image from `$lib` and it works as expected like so:\n\n```\n\nimport img from '$lib/assets/sample-image.jpg'; \n\n```\n\nBut for the life of me I can't figure out how I can change the import path using a dynamic prop. I imagine it would look something like this:\n\n```\nimport img from '$lib/assets/{object.imageUrlProp}';\n```\n\nOr some type of direct access in the image `src` similar to how static usage would look like:\n\n```\n\n```\n\nBut neither of these are valid syntax.\n\nHow can I dynamically import images stored in `$lib` within a component in Svelte?\n\n### Edit\n\nBrunnerh's answer works great for files with the same extension. As he explains in the comments, for files with differing extensions, a glob import is required. Here is the specific implementation solution I was able to get working. I had some trouble understanding how to access the modules structure normally passed back from the import, so using `as: url` simplified that process for me. Here is the specific implementation solution I was able to get working:\n\n### General Implementation\n\n```\n\nconst images: any = import.meta.glob(['$lib/assets/**.jpg', '$lib/assets/**.png', '$lib/assets/**.svg'], { eager: true, as: 'url' });\n\n```\n\n### My Specific Use Case Implementation\n\nI was trying to iterate through JSON data containing relative image URLs:\n\n```\n\n import { pages } from '$lib/data/sample_data.json';\n const images: any = import.meta.glob(['$lib/images/**.jpg', '$lib/images/**.png', '$lib/images/**.svg'], { eager: true, as: 'url' });\n\n{#each Object.entries(pages) as [key, page], index (key)}\n \n \n \n\n### {page.title}\n\n \n{/each}\n\n{\n \"pages\": [\n {\n \"title\": \"First Page\",\n \"featured_image\": \"image.png\",\n \"image_alt\": \"alt for page 1\"\n },\n {\n \"title\": \"Second Page\",\n \"featured_image\": \"image2.jpg\",\n \"image_alt\": \"alt for page 2\"\n },\n {\n \"title\": \"Third Page\",\n \"featured_image\": \"image3.svg\",\n \"image_alt\": \"alt for page 3\"\n },\n ]\n}\n```\n\n========================================\n\nCode:\n```text\n<script>\nimport img from '$lib/assets/sample-image.jpg'; \n</script>\n\n<img src={img} />\n```\n\n```text\nimport img from '$lib/assets/{object.imageUrlProp}';\n```\n\n```text\n<img src=\"$lib/assets/{object.imageUrlProp}\" alt=\"Image\" />\n```\n\n```text\n<script lang=\"ts\">\nconst images: any = import.meta.glob(['$lib/assets/**.jpg', '$lib/assets/**.png', '$lib/assets/**.svg'], { eager: true, as: 'url' });\n<!--You can change allowed extensions here, or you could do something like '$lib/assets/**' without an extension to allow imports for any file types. The '**' allows for nested folders, so you can replace it with '*' if all assets are directly stored in the assets folder-->\n<script>\n\n<!--imageURL will look something like image1.png or folder1/image1.png-->\n<img src={images[\"/src/lib/assets/\" + imageURL} />\n```\n\n```text\n<script lang=\"ts\">\n import { pages } from '$lib/data/sample_data.json';\n const images: any = import.meta.glob(['$lib/images/**.jpg', '$lib/images/**.png', '$lib/images/**.svg'], { eager: true, as: 'url' });\n</script>\n\n{#each Object.entries(pages) as [key, page], index (key)}\n <div class=\"page\">\n <img src={images[\"/src/lib/images/\" + page.featured_image]} alt={page.image_alt} />\n <h2>{page.title}</h2>\n </div>\n{/each}\n\n<!--Sample JSON Data-->\n{\n \"pages\": [\n {\n \"title\": \"First Page\",\n \"featured_image\": \"image.png\",\n \"image_alt\": \"alt for page 1\"\n },\n {\n \"title\": \"Second Page\",\n \"featured_image\": \"image2.jpg\",\n \"image_alt\": \"alt for page 2\"\n },\n {\n \"title\": \"Third Page\",\n \"featured_image\": \"image3.svg\",\n \"image_alt\": \"alt for page 3\"\n },\n ]\n}\n```\n\n```text\n$lib\n```\n\n```text\n$lib\n```\n\n```text\n$lib\n```\n\n```text\n$lib\n```\n\n```text\nsrc\n```\n\n```text\n$lib\n```\n\n```text\nas: url\n```\n\n```html\n{#await import(`$lib/assets/${object.imageUrlProp}.jpg`) then { default: src }}\n <img {src} alt=\"Image\" />\n{/await}\n```\n\n```js\nconst images = import.meta.glob(\n '$lib/assets/*.jpg',\n { eager: true, import: 'default' },\n);\n```\n\n```html\n<Component imgSrc={images[`$lib/assets/${object.imageName}.jpg`]} />\n```\n\n```text\neager\n```\n\n```text\nawait\n```\n\n```text\nsrc\n```\n\n========================================\n\nComments:\n- This does indeed work, but requires that all my images have the same extension. For now this is not a problem, but ideally I’d like to be able to show any images from that. Also, do await and glob import impact performance? Perhaps I’m going about this in a way that doesn’t make sense?\n- The await is kind of pointless since it imports just a path, not the contents, it will mostly cost the time of a round trip, if the bundler does not inline the path during build. Globbing happens at build time, should not drastically affect runtime as long as you don't have thousands of pictures. You can use multiple patterns to support different locations/extensions.\n- What would the syntax look like using multiple patterns? I imagine the import would look something like const images = import.meta.glob('$lib/assets/*.jpg', '$lib/assets/*.png', '$lib/assets/*.svg', { eager: true }); perhaps? But how do you reference the path in the array call without the extension? Also, what if you're only importing a single image, would you still have to use glob import so you could use different extensions?\n- See docs on multiple patterns, the first argument becomes an array. If you import via a path like `./files/*`, you don't need an extension and the result of the import is a plain object, you can iterate over the imported modules by just getting the values with `Object.values`. You will need a glob import for a single file if the name the file is not fixed.\n- Can I call a glob import in the middle of the svelte file (right now I have an {#each} block iterating through a JSON file and importing data), or does it have to be at the beginning, all at once?\n- Don't know, consult docs or try it.\n- I couldn't find anything in the docs, and nothing I tried worked. For now it will remain a mystery. Thanks again for all your help, the solution I have now works great for my needs! I suppose if someone has to dynamically import different file extensions, and they don't know what the locations will be until after the page is loaded then they may need to find an alternate solution.","metadata":{"transformedAt":"2026-08-18T18:33:40.691Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":218,"estimatedTokens":1858}}427{"id":"stack-75694712","source":"stackoverflow","questionId":75694712,"title":"Get current Value of Svelte Store Variable in Ts/Js File","tags":["typescript","svelte","svelte-store"],"text":"Title: Get current Value of Svelte Store Variable in Ts/Js File\nTags: typescript, svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI've tried to get the current value of a variable in my Svelte Store file in an other TS File with the 'get' Method.\nBut it seems like the 'get' method is only getting the inital value of the variable in the Store and not the current value.\n\n```\n//stores.ts\nexport const variable = writable([]);\n```\n\nThis variable is being changed after a while.\n\n*After* the Variable is being changed by my Application (let's say it got changed to 42) im trying to get it via the 'get' method:\n\n```\n//test_file.ts\nimport { variable } from './stores'\n\nlet value = get(variable)\nconsole.log(value) //[] and not 42\n```\n\nSo it seems like the 'get' Method is just getting the inital Value of the Store Variable and not the current one.\nDoes anyone know how to access the current value?\n\n========================================\n\nTop Answer:\nIt is actually getting the current value at the point those lines are executed. What you probably want to do is read the store value at the point some function is called.\n\n```\nexport function doSomething() {\n const value = get(variable);\n // more code here\n}\n```\n\nNow, every time you call `doSomething` from your components it will read the store and get the current value.\n\n========================================\n\nCode:\n```text\n//stores.ts\nexport const variable = writable([]);\n```\n\n```text\n//test_file.ts\nimport { variable } from './stores'\n\nlet value = get(variable)\nconsole.log(value) //[] and not 42\n```\n\n```text\nlet subscriptedVariable:any;\n\n // \"variable\" is the variable configured in the stores.ts\n variable.subscribe((value) => (subscriptedVariable = value));\n```\n\n```text\nupdate\n```\n\n```js\nexport function doSomething() {\n const value = get(variable);\n // more code here\n}\n```\n\n```text\ndoSomething\n```\n\n========================================\n\nComments:\n- I want to access the store variable and not manually set/update it. My Application is a litte more complex so I can't just simply update the variable. I have to access it via the store.\n- This isn't really an answer; if you need to ask the original poster something, please use the comment function instead. Thanks!\n- I've tried your solution but if I log value I still receive an empty Array. I'm trying to get the Value in a Playwright Test file and at that point where I am calling the doSomething function I get an empty Array. However, when i'm going into that specific state of my application on the Localhost, not in the Playwright Test Enviroment, and I log the store variable 'variable', I get the correct value.","metadata":{"transformedAt":"2026-08-18T18:33:40.691Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":86,"estimatedTokens":665}}428{"id":"stack-67462523","source":"stackoverflow","questionId":67462523,"title":"Svelte - Input value doesn't always update","tags":["svelte","svelte-3"],"text":"Title: Svelte - Input value doesn't always update\nTags: svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create an input component in Svelte where the value is updated by a JavaScript function. However, if the new value is the same as the old value, Svelte will not update the input element.\n\nFor instance, this component should restrict input to only numbers. If you were to type \"123abc\", the input will then display \"123abc\" while the `value` variable is just \"123\".\n\n```\n\n let value = ''\n \n const handleInput = (event) => {\n value = event.currentTarget.value.replace(/[^\\d]/gu, '')\n }\n\n Value: \"{value}\"\n\n```\n\nIs there way to always make the input value to equal the `value` variable?\n\n### Attempted solutions\n\n- Use the HTML `pattern` attribute. While it works for this example, it will not work for the general case I'm trying to solve\n\n- Could just say `event.currentTarget.value = value`. This works perfectly, but it doesn't seem Svelte-like.\n\n- `bind:value` has the same issues as the event listener (e.g., `$: value = value.replace(/[^\\d]/gu, '')`). Also, in the general case, `bind:value` won't work for me as I'm comparing the previous and updated value.\n\nRelated\n\n- How do I make Svelte update input components like React does?\n\n========================================\n\nTop Answer:\nIn your example, you have not used `bind:value` and declares the `value` to its input but instead, you could use this method\n\nREPL\n\n```\n\n let value = ''\n \n $: sanitized = value.replace(/[^\\d]/gu, '')\n\n display value: {value}\n\n display value: {sanitized}\n\n```\n\n========================================\n\nCode:\n```text\n<script>\n let value = ''\n \n const handleInput = (event) => {\n value = event.currentTarget.value.replace(/[^\\d]/gu, '')\n }\n</script>\n\n<input {value} type='text' on:input={handleInput} />\n\n<p>\n Value: \"{value}\"\n</p>\n```\n\n```text\nvalue\n```\n\n```text\nvalue\n```\n\n```text\npattern\n```\n\n```text\nevent.currentTarget.value = value\n```\n\n```text\nbind:value\n```\n\n```text\n$: value = value.replace(/[^\\d]/gu, '')\n```\n\n```text\nbind:value\n```\n\n```text\nevent.currentTarget.value = value\n```\n\n```html\n<script>\n let value = ''\n \n $: sanitized = value.replace(/[^\\d]/gu, '')\n</script>\n\n\n<input bind:value />\n\n<p>\n display value: {value}\n</p>\n\n<p>\n display value: {sanitized}\n</p>\n```\n\n```text\nbind:value\n```\n\n```text\nvalue\n```\n\n```js\nconst handleInput = (event) => {\n value = event.currentTarget.value;\n value = value.replace(/[^\\d]/gu, '');\n}\n```\n\n```text\nevent.currentTarget.value\n```\n\n========================================\n\nComments:\n- I know it's been a while, but I am curious to know why don't you use `` I know you won't be able to display the strings, but I don't think it is that important since it won't be used as value anyways,\n- There's only two differences between `type=\"text\"` and `type=\"number\"`: 1) mobile devices will use the numeric keyboard, 2) desktop devices will display the increment/decrement arrows. I believe best practice for choosing between the two is: want the increment/decrement arrows? Choose `type=\"number\"`. Else, restrict the acceptable characters and set the mobile keyboard. I could be wrong, but that's my thought process.\n- This still has the same issue, though. You're can still type letters into the input. Yes, the sanitized value won't have those letters, but the input will still display them. Didn't mention this in the question (so I'll update it), but I also need to use the event listener in this case and not `bind:value`.\n- It works, but why is it necessary? Is there a principle of Svelte reactivity that would allow us to predict that setting the value variable in the handleInput function would not update the value property of the input? Or is this simply a bug in Svelte?","metadata":{"transformedAt":"2026-08-18T18:33:40.691Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":150,"estimatedTokens":946}}429{"id":"stack-73525363","source":"stackoverflow","questionId":73525363,"title":"how do I use useCallback hook in svelte","tags":["javascript","html","reactjs","typescript","svelte"],"text":"Title: how do I use useCallback hook in svelte\nTags: javascript, html, reactjs, typescript, svelte\nSource: Stack Overflow\n\nQuestion:\nThis is my code block looks line when used with a `useCallback` hook in react but I want to use same function in svelte,but want to add this in useCallback hook. Is there any alternative for svelte.\n\n```\nconst newCancelToken = useCallback(() => {\n axiosSource.current = axios.CancelToken.source();\n return axiosSource.current.token;\n }, []);\n```\n\n========================================\n\nTop Answer:\nThe svelte equivalent of useMemo/useCallback is $:\n\n// react\nconst a = useMemo(() => b + c, [b, c]);\n\n// svelte\n$: a = b + c;\n\nhttps://twitter.com/sveltejs/status/1221788690722304003\n\n========================================\n\nCode:\n```text\nconst newCancelToken = useCallback(() => {\n axiosSource.current = axios.CancelToken.source();\n return axiosSource.current.token;\n }, []);\n```\n\n```text\nuseCallback\n```\n\n```text\nuseMemo\n```\n\n```text\nuseCallback\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.691Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":48,"estimatedTokens":251}}430{"id":"stack-77241807","source":"stackoverflow","questionId":77241807,"title":"How to change the build directory in SvelteKit?","tags":["svelte","vite","sveltekit"],"text":"Title: How to change the build directory in SvelteKit?\nTags: svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nIn SvelteKit, I can't figure out a way to change the path of the actual build directory (not the app or the generated directory) via configuration. I've tried changing it in Vite configuration (1) but I get the message (2).\n\n1.\n\n```\n// vite.config.ts\nimport { sveltekit } from \"@sveltejs/kit/vite\"\nimport { defineConfig } from \"vite\"\n\nexport default defineConfig({\n plugins: [ sveltekit() ],\n build: { outDir: \"builds\" }\n})\n```\n\n- \n\n```\nThe following Vite config options will be overridden by SvelteKit:\n - build.outDir\n```\n\nFor context, I'm making a mono-repo for a cross-platform app with the Vite generated SvelteKit build as a basis for the native platform apps.\n\n========================================\n\nCode:\n```js\n// vite.config.ts\nimport { sveltekit } from \"@sveltejs/kit/vite\"\nimport { defineConfig } from \"vite\"\n\nexport default defineConfig({\n plugins: [ sveltekit() ],\n build: { outDir: \"builds\" }\n})\n```\n\n```bash\nThe following Vite config options will be overridden by SvelteKit:\n - build.outDir\n```\n\n```js\n// svelte.config.js\nimport adapter from \"@sveltejs/adapter-static\"\nimport { vitePreprocess } from \"@sveltejs/kit/vite\"\n\n/** @type {import(\"@sveltejs/kit\").Config} */\nconst config = {\n // Consult https://kit.svelte.dev/docs/integrations#preprocessors\n // for more information about preprocessors\n preprocess: vitePreprocess(),\n\n kit: {\n adapter: adapter({ pages: \"builds\" })\n }\n}\n\nexport default config\n```\n\n```text\npages\n```\n\n========================================\n\nComments:\n- Not sure if this help, you can define your own build route when using sveltekit `adapter-static` kit.svelte.dev/docs/adapter-static","metadata":{"transformedAt":"2026-08-18T18:33:40.691Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":75,"estimatedTokens":445}}431{"id":"stack-76888854","source":"stackoverflow","questionId":76888854,"title":"What is the difference between Skeleton project and Library project when installing SvelteKit template?","tags":["svelte","sveltekit"],"text":"Title: What is the difference between Skeleton project and Library project when installing SvelteKit template?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nWhen installing a SvelteKit app, you get the following options:\n\n```\nWhich Svelte app template?\n│ ○ SvelteKit demo app (A demo app showcasing some of the features of SvelteKit - play a word guessing game that works without JavaScript!)\n│ ● Skeleton project (Barebones scaffolding for your new SvelteKit app)\n│ ○ Library project (Barebones scaffolding for your new Svelte library)\n```\n\nThe first one is an example, and the next two is barebones scaffolding. I don't understand the difference between the two scaffolding options. In what cases should you choose the one over the other?\n\nI would guess SvelteKit app is the most common option, but what is a Svelte Library?\n\nI was not able to google the answere, but it seems like a simple question that a noob like me just dont understand.\n\n========================================\n\nCode:\n```text\nWhich Svelte app template?\n│ ○ SvelteKit demo app (A demo app showcasing some of the features of SvelteKit - play a word guessing game that works without JavaScript!)\n│ ● Skeleton project (Barebones scaffolding for your new SvelteKit app)\n│ ○ Library project (Barebones scaffolding for your new Svelte library)\n```\n\n```text\n@sveltejs/package\n```\n\n```text\npackage\n```\n\n```text\ndist\n```\n\n```text\npackage.json\n```\n\n```text\nexports\n```\n\n```text\nfiles\n```\n\n```text\nsvelte\n```\n\n```text\ntypes\n```\n\n```text\ndist\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.691Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":65,"estimatedTokens":381}}432{"id":"stack-75375799","source":"stackoverflow","questionId":75375799,"title":"How to fetch default action in +page.server.ts file in SvelteKit","tags":["typescript","svelte","sveltekit"],"text":"Title: How to fetch default action in +page.server.ts file in SvelteKit\nTags: typescript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm using SvelteKit and I've a form on my page. As I need to manipulate the data before it is sent, I cannot use the SvelteKit's default behaviour of form submission (using `action` attribute).\n\nSo, according to this part of the documentation, I used a simple event listener and then the `fetch` function :\n\n```\nasync function handleSubmit(e:Event) {\n const formData = new FormData(e.target as HTMLFormElement);\n // ... doing some stuff here\n const res = await fetch(\"?/login\", { /* plenty of stuff there */ });\n}\n```\n\nSo the action named \"login\" in `./+page.server.ts` will be executed.\n\nI have a simple question: **what path do I write (in `fetch`) if I want the default action to be executed, knowing that the current page is in a slug.**\n\nDo I write `fetch(\"?/\")` ? (doesn't work)\n\nDo I write `fetch(\"?\"`) ? (doesn't work)\n\nObviously I could just name it and problem solved. I'm just wondering if there is a solution and if someone has ever thought about this.\n\n========================================\n\nCode:\n```js\nasync function handleSubmit(e:Event) {\n const formData = new FormData(e.target as HTMLFormElement);\n // ... doing some stuff here\n const res = await fetch(\"?/login\", { /* plenty of stuff there */ });\n}\n```\n\n```text\naction\n```\n\n```text\nfetch\n```\n\n```text\n./+page.server.ts\n```\n\n```text\nfetch\n```\n\n```text\nfetch(\"?/\")\n```\n\n```text\nfetch(\"?\"\n```\n\n```html\n<form\n method=\"POST\"\n use:enhance={({ form, data, action, cancel }) => {\n // `form` is the `<form>` element\n // `data` is its `FormData` object\n // `action` is the URL to which the form is posted\n // `cancel()` will prevent the submission\n\n return async ({ result, update }) => {\n // `result` is an `ActionResult` object\n // `update` is a function which triggers the logic that would be triggered if this callback wasn't set\n };\n }}\n>\n```\n\n```html\n<script lang=\"ts\">\n import { enhance, type SubmitFunction } from '$app/forms';\n\n const onSubmit: SubmitFunction = ({ data }) => {\n data.set('test', 'value');\n }\n</script>\n\n<form method=\"POST\" use:enhance={onSubmit}>\n ...\n</form>\n```\n\n```text\nenhance\n```\n\n```text\ntype=hidden\n```\n\n```text\ndocument.location.href\n```\n\n========================================\n\nComments:\n- Thank you, that helps! Although the reason why I am not using `use:enhance` is because I have an input of type `file` that is `multiple` and I want the user to be able to remove a file from the list if he changed his mind. As far as I know it's not possible to manually change the FileList from such input. Does the `SubmitFunction` allows me to change the data **before** it is sent to the server?\n- Also, I think you meant `document.location.href` instead of `document.href` because this is `undefined`. I checked and indeed it triggers the default action\n- Changing data before it is sent is exactly what the example above does. But if you need asynchronous user interaction you should not be triggering the submit at all. Let the user make any changes they want beforehand. You can render a list of files that allows the user to remove items beforehand and then just `append` the files that should be sent to the `data`. (REPL example of file list)","metadata":{"transformedAt":"2026-08-18T18:33:40.691Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":111,"estimatedTokens":834}}433{"id":"stack-73549633","source":"stackoverflow","questionId":73549633,"title":"Vite+SvelteKit Build Failing","tags":["svelte","vite","sveltekit"],"text":"Title: Vite+SvelteKit Build Failing\nTags: svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm building a website using `SvelteKit`, scaffolded using `pnpm create svelte`. However, when I run `pnpm build`, I get the following error:\n\n```\nvite v3.0.9 building for production...\n✓ 77 modules transformed.\n.svelte-kit/output/client/vite-manifest.json 2.96 KiB\n[vite-plugin-svelte-kit] Error running plugin hook writeBundle for vite-plugin-svelte-kit, expected a function hook.\nerror during build:\nError: Error running plugin hook closeBundle for vite-plugin-svelte-kit, expected a function hook.\n at error (file:///home/leo/code/keo-website/node_modules/.pnpm/rollup@2.77.3/node_modules/rollup/dist/es/shared/rollup.js:1858:30)\n at throwInvalidHookError (file:///home/leo/code/keo-website/node_modules/.pnpm/rollup@2.77.3/node_modules/rollup/dist/es/shared/rollup.js:22551:12)\n at file:///home/leo/code/keo-website/node_modules/.pnpm/rollup@2.77.3/node_modules/rollup/dist/es/shared/rollup.js:22692:24\n at async Promise.all (index 0)\n at async Object.close (file:///home/leo/code/keo-website/node_modules/.pnpm/rollup@2.77.3/node_modules/rollup/dist/es/shared/rollup.js:23662:13)\n at async Promise.all (index 0)\n at async build (file:///home/leo/code/keo-website/node_modules/.pnpm/vite@3.0.9_sass@1.54.7/node_modules/vite/dist/node/chunks/dep-0fc8e132.js:43473:13)\n at async CAC. (file:///home/leo/code/keo-website/node_modules/.pnpm/vite@3.0.9_sass@1.54.7/node_modules/vite/dist/node/cli.js:747:9)\n ELIFECYCLE Command failed with exit code 1.\n```\n\nHere is my `svelte.config.js`:\n\n```\nimport adapter from \"@sveltejs/adapter-static\";\nimport preprocess from \"svelte-preprocess\";\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: preprocess({\n scss: { includePaths: [\"./src/styles\"] },\n }),\n\n kit: {\n adapter: adapter({\n pages: \"build\",\n assets: \"build\",\n }),\n },\n};\n\nexport default config;\n```\n\nMost things that I've done here are what I've done in the past. The only difference is that I have a `export const prerender = true;` in `src/routes/+layout.svelte` since it appears that they overhauled their route system.\n\n========================================\n\nCode:\n```text\nvite v3.0.9 building for production...\n✓ 77 modules transformed.\n.svelte-kit/output/client/vite-manifest.json 2.96 KiB\n[vite-plugin-svelte-kit] Error running plugin hook writeBundle for vite-plugin-svelte-kit, expected a function hook.\nerror during build:\nError: Error running plugin hook closeBundle for vite-plugin-svelte-kit, expected a function hook.\n at error (file:///home/leo/code/keo-website/node_modules/.pnpm/rollup@2.77.3/node_modules/rollup/dist/es/shared/rollup.js:1858:30)\n at throwInvalidHookError (file:///home/leo/code/keo-website/node_modules/.pnpm/rollup@2.77.3/node_modules/rollup/dist/es/shared/rollup.js:22551:12)\n at file:///home/leo/code/keo-website/node_modules/.pnpm/rollup@2.77.3/node_modules/rollup/dist/es/shared/rollup.js:22692:24\n at async Promise.all (index 0)\n at async Object.close (file:///home/leo/code/keo-website/node_modules/.pnpm/rollup@2.77.3/node_modules/rollup/dist/es/shared/rollup.js:23662:13)\n at async Promise.all (index 0)\n at async build (file:///home/leo/code/keo-website/node_modules/.pnpm/vite@3.0.9_sass@1.54.7/node_modules/vite/dist/node/chunks/dep-0fc8e132.js:43473:13)\n at async CAC.<anonymous> (file:///home/leo/code/keo-website/node_modules/.pnpm/vite@3.0.9_sass@1.54.7/node_modules/vite/dist/node/cli.js:747:9)\n ELIFECYCLE Command failed with exit code 1.\n```\n\n```js\nimport adapter from \"@sveltejs/adapter-static\";\nimport preprocess from \"svelte-preprocess\";\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: preprocess({\n scss: { includePaths: [\"./src/styles\"] },\n }),\n\n kit: {\n adapter: adapter({\n pages: \"build\",\n assets: \"build\",\n }),\n },\n};\n\nexport default config;\n```\n\n```text\nSvelteKit\n```\n\n```text\npnpm create svelte\n```\n\n```text\npnpm build\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nexport const prerender = true;\n```\n\n```text\nsrc/routes/+layout.svelte\n```\n\n```json\n{\n ...\n \"devDependencies\": {\n ...\n \"vite\": \"^3.1.0-beta.1\"\n }\n}\n```\n\n```text\nnpm update\n```\n\n```text\nimport.meta.glob\n```\n\n```text\nwriteBundle\n```\n\n```text\npackage.json\n```\n\n```text\nnpm update\n```\n\n========================================\n\nComments:\n- It looks like a bug on their part. SvelteKit is going through heavy refactor so turbulence is kinda expected. Try revert to earlier version.","metadata":{"transformedAt":"2026-08-18T18:33:40.691Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":154,"estimatedTokens":1191}}434{"id":"stack-70834359","source":"stackoverflow","questionId":70834359,"title":"Svelte: How to subscribe to store inside a class instance","tags":["javascript","svelte","svelte-3","svelte-store"],"text":"Title: Svelte: How to subscribe to store inside a class instance\nTags: javascript, svelte, svelte-3, svelte-store\nSource: Stack Overflow\n\nQuestion:\nHow do I subscribe to a `writable()` instance of a class?\n\n```\nclass User{\n public money: Writable = writable(0);\n\n public goToJob(){\n money.update(prev => prev + 100);\n }\n}\n```\n\n```\n\n let user = new User();\n\n{user.$money}\n user.goToJob()}>Go to Job\n```\n\nWhen I click on the button, I expect the money to be added and reflected on the div. It doesn't update however, though I'm correctly referencing the `money` store.\n\n========================================\n\nTop Answer:\nNever saw a store as a Class property but instead store is often used as kind of a DTO. I know nothing about typescript but I think the below code is gonna give you a better idea of what I'm talking about:\n\n```\n\n import user from './user-store.js';\n \n {\n $user // This automatically subscribes and unsubscribe to the User store.\n }\n \n $user = {money:100};\n\n{$user.money}\n\n user.goToJob()}>\nGo to Job\n\n```\n\nDisplaying or assigning a value to the store uses the $ prefix ($user.money) but calling a function doesn't (user.goToJob())\n\n```\nimport { writable } from 'svelte/store';\n\nconst user = writable({}); // the store is an empty object by default\n\nconst userStore = {\n subscribe: user.subscribe,\n set: u => {\n user.set(u);\n console.log(u);\n },\n \n delete: () => {\n user.set(null);\n },\n \n goToJob: () => {\n user.update(user => {\n user.money += 100;\n return user;\n });\n }\n};\n\nexport default userStore;\n```\n\nLink here:\n\nhttps://svelte.dev/repl/ec4a3dee9f3c4bbebf929ee5772c48c5?version=3.46.2\n\nBest.\n\n========================================\n\nCode:\n```js\nclass User{\n public money: Writable<number> = writable(0);\n\n public goToJob(){\n money.update(prev => prev + 100);\n }\n}\n```\n\n```html\n<script>\n let user = new User();\n</script>\n\n<div>{user.$money}</div>\n<button on:click={() => user.goToJob()}>Go to Job</button>\n```\n\n```text\nwritable()\n```\n\n```text\nmoney\n```\n\n```html\n<script>\n let user = new User();\n let { money } = user;\n</script>\n\n<div>{$money}</div>\n<button on:click={() => user.goToJob()}>Go to Job</button>\n```\n\n```js\n<script>\n import user from './user-store.js';\n \n {\n $user // This automatically subscribes and unsubscribe to the User store.\n }\n \n $user = {money:100};\n</script>\n\n<div>{$user.money}</div>\n\n<button on:click={() => user.goToJob()}>\nGo to Job\n</button>\n```\n\n```js\nimport { writable } from 'svelte/store';\n\nconst user = writable({}); // the store is an empty object by default\n\nconst userStore = {\n subscribe: user.subscribe,\n set: u => {\n user.set(u);\n console.log(u);\n },\n \n delete: () => {\n user.set(null);\n },\n \n goToJob: () => {\n user.update(user => {\n user.money += 100;\n return user;\n });\n }\n};\n\nexport default userStore;\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.691Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":168,"estimatedTokens":721}}435{"id":"stack-70800012","source":"stackoverflow","questionId":70800012,"title":"How to integrate Svelte in other App Stack","tags":["backend","svelte","svelte-3"],"text":"Title: How to integrate Svelte in other App Stack\nTags: backend, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI would like to know if it's possible to integrate Svelte for the front app with a different backend stack than the default one, with a python, Ruby on Rails or PHP server for instance?\n\nIs it possible to use it for a multi-pages app, or should it be used only for single page apps?\n\n========================================\n\nTop Answer:\nThere is no difference in integrating Svelte with different backends than there would be with any other frontend technology.\n\nFor multipage apps, I recommend using SvelteKit. In this case, there is a special `fetch` HTTP hook that helps integrations on the server-side rendering and it is recommended all backend APIs are exposed as REST/JSON to have the best support for the `fetch` SSR handling.\n\nRead my blog post about how I integrated Svelte with Python backend. You can find the actual frontend source code here.\n\n========================================\n\nCode:\n```html\n<div id=\"svelte-app\"></div>\n<script src=\"dist/main.js\"></script>\n```\n\n```js\n// src/main.js\nimport { mount } from \"svelte\";\nimport App from \"./App.svelte\";\n\nmount(App, {\n target: document.getElementById(\"svelte-app\"),\n props: {\n name: \"world\",\n },\n});\n```\n\n```bash\nnpm install --save-dev vite svelte @sveltejs/vite-plugin-svelte\n```\n\n```js\n// vite.config.js\nimport path from \"path\";\nimport { defineConfig } from \"vite\";\nimport { svelte } from \"@sveltejs/vite-plugin-svelte\";\n\nexport default defineConfig({\n plugins: [svelte()],\n build: {\n lib: {\n formats: [\"es\"],\n fileName: (format) => `main.js`,\n entry: path.resolve(__dirname, \"src/main.js\"),\n },\n },\n});\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\nnpx vite build --watch\n```\n\n```text\nfetch\n```\n\n```text\nfetch\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.691Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":76,"estimatedTokens":456}}436{"id":"stack-64286792","source":"stackoverflow","questionId":64286792,"title":"How to add a .js file to the Svelte REPL?","tags":["svelte"],"text":"Title: How to add a .js file to the Svelte REPL?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nIn the Svelte REPL it is possible to add a new .svelte file but not a new .js file, but samples exist do have .js files:\n\nhttps://svelte.dev/examples#derived-stores\n\nIs it possible for end users to do the same?\n\n========================================\n\nCode:\n```text\n.js\n```\n\n========================================\n\nComments:\n- Seems really obvious when you know about it :)","metadata":{"transformedAt":"2026-08-18T18:33:40.691Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":22,"estimatedTokens":119}}437{"id":"stack-77606638","source":"stackoverflow","questionId":77606638,"title":"Svelte 5 - Uncaught ReferenceError: $state is not defined","tags":["svelte","svelte-5"],"text":"Title: Svelte 5 - Uncaught ReferenceError: $state is not defined\nTags: svelte, svelte-5\nSource: Stack Overflow\n\nQuestion:\nI am trying to make Svelte 5 project (I know it is still in alpha, but I want to play a bit with it), and I am using this as a template for now\n\nMy **App.svelte**\n\n```\n\n import { withPrevSignals } from './withPrev'\n\n const color = withPrevSignals('green')\n\n let inputVal = $state('')\n\n function save() {\n color.curr = inputVal;\n inputVal = ''\n }\n\nPrev: {color.prev}\n\nCurr: {color.curr}\n\nSave\nUndo\n```\n\n**withPrev.js**\n\n```\nexport function withPrevSignals(initialValue) {\n let curr = $state(initialValue)\n let prev = $state(undefined)\n\n function undo() {\n curr = prev\n prev = undefined\n }\n return {\n get curr() { return curr },\n set curr(newValue) {\n prev = curr\n curr = newValue\n },\n get prev() { return prev },\n undo\n }\n}\n```\n\nI keep getting an Uncaught ReferenceError: $state is not defined both in the svelte 5 playground and on the local. What am I doing wrong here?\n\n========================================\n\nTop Answer:\nFor people like me who have googled this error “ReferenceError: $state is not defined”, one cause of this error is that the source code upgraded to svelte 5 but you still have an old svelte 4 installed locally. If this is the case, make sure to install the proper svelte 5 that package.json requires:\n\n- If you are running npm directly, then run `npm ci` again (or whichever package manager the code uses e.g. `yarn install --immutable`).\n\n- Else if you are running docker-compose that contains a `build:` block whose Dockerfile runs `npm ci` or equivalent, then run `docker-compose up --build` to rebuild the image that installs npm dependencies.\n\n========================================\n\nCode:\n```text\n<script>\n import { withPrevSignals } from './withPrev'\n\n const color = withPrevSignals('green')\n\n let inputVal = $state('')\n\n function save() {\n color.curr = inputVal;\n inputVal = ''\n }\n</script>\n\n<p>Prev: {color.prev}</p>\n<p>Curr: {color.curr}</p>\n<input bind:value={inputVal} />\n<button on:click={save}>Save</button>\n<button on:click={color.undo}>Undo</button>\n```\n\n```text\nexport function withPrevSignals(initialValue) {\n let curr = $state(initialValue)\n let prev = $state(undefined)\n\n function undo() {\n curr = prev\n prev = undefined\n }\n return {\n get curr() { return curr },\n set curr(newValue) {\n prev = curr\n curr = newValue\n },\n get prev() { return prev },\n undo\n }\n}\n```\n\n```text\n.svelte.js\n```\n\n```text\n.svelte.ts\n```\n\n```text\n.spec.js\n```\n\n```text\n.test.js\n```\n\n```text\n.svelte\n```\n\n```text\nthing.svelte.spec.js\n```\n\n```text\nnpm ci\n```\n\n```text\nyarn install --immutable\n```\n\n```text\nbuild:\n```\n\n```text\nnpm ci\n```\n\n```text\ndocker-compose up --build\n```\n\n========================================\n\nComments:\n- \"a separate .svelte.js or .svelte.ts module\" what's the bundler doing under the hood? I'm using esbuild-svelte and changing the file extension to .svelte.js or .svelte.ts doesn't fix this for me. As a workaround, I changed the extension to just .svelte and added context=\"module\" to the script tag.\n- @425nesp: If those files are not processed correctly, `esbuild-svelte` might not be fully compatible with Svelte 5 yet.\n- You can enable runes from svelte's config\n- Unfortunately, my js file extension is .svelte.js and I still get this error. Baffling.\n- @DaveMunger: And you have installed Svelte 5 successfully? Is the error an IDE or runtime error?\n- @brunnerh Yes, I'm running Svelte 5.2.8. And it's a runtime error, although the IDE also complains that it doesn't know what $state is. I am using the .svelte.ts extension on source, and I even tried to config rollup to export the rendered file as .svelte.js. It does this fine, but I still get the runtime error, no matter what the source or compiled filename extensions are. Also, I've enabled runes in config and the $props rune works fine in component files. Just not in .svelte.js.\n- @DaveMunger: Rollup? That is pretty low-level, did you set up the Svelte plugin to process JS/TS files? Suspect that more manual setup is necessary if you don't use the Vite plugin. *Edit:* Looks like support for compiling Svelte JS/TS files was added to the Rollup plugin in version 7.2.2.\n- @DaveMunger: Maybe ask a new rollup-specific question and show *all* relevant configs.\n- @brunnerh Got it, thanks. I might even just switch to the Svelte build tool, if that would work better.","metadata":{"transformedAt":"2026-08-18T18:33:40.691Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":165,"estimatedTokens":1130}}438{"id":"stack-74491114","source":"stackoverflow","questionId":74491114,"title":"Svelte: doesn't work inline css animation","tags":["css","animation","svelte","svelte-3"],"text":"Title: Svelte: doesn't work inline css animation\nTags: css, animation, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nDoesn't work inline css animation like this:\n\n```\n\n### Hello {name}!\n\n.test { \n background: yellow;\n}\n\n@keyframes bg {\n from {\n background: red;\n }\n to {\n background: green;\n }\n }\n\n```\n\nhttps://svelte.dev/repl/e32b72cb98cb4b78a47b1bcb1ecab9e9?version=3.53.1\n\nBut if delete style attribute\n\n```\n\n### Hello {name}!\n\n```\n\nand add\n\n```\n.test \n background: yellow;\n animation: bg 2s linear infinite;\n}\n```\n\nIt works!\nBut I want to add animation as inline style.\n\n========================================\n\nCode:\n```text\n<h1 class=\"test\" style=\"animation: bg 2s linear infinite\">Hello {name}!</h1>\n\n<style>\n.test { \n background: yellow;\n}\n\n@keyframes bg {\n from {\n background: red;\n }\n to {\n background: green;\n }\n }\n</style>\n```\n\n```text\n<h1 class=\"test\">Hello {name}!</h1>\n```\n\n```text\n.test \n background: yellow;\n animation: bg 2s linear infinite;\n}\n```\n\n```css\n@keyframes -global-bg { ... }\n```\n\n```text\n@keyframes\n```\n\n```text\n:global()\n```\n\n```text\n@keyframes\n```\n\n```text\n-global-\n```\n\n```text\nbg\n```\n\n========================================\n\nComments:\n- Why exactly do you need the inline style? `animation` is a shorthand property. If you need variance in e.g. just the speed, you could define everything except `animation-duration` in the `` tag.\n- That's so whack lol but just confirming this does work in the latest version of svelte circa Nov 2023","metadata":{"transformedAt":"2026-08-18T18:33:40.691Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":110,"estimatedTokens":377}}439{"id":"stack-66886318","source":"stackoverflow","questionId":66886318,"title":"How do I create a custom event in Svelte?","tags":["svelte"],"text":"Title: How do I create a custom event in Svelte?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI've been using `on:click` and looking for an event using Svelte. How do I trigger a custom event within a child component that I can capture in a parent component? I've seen a tutorial where I can pass in something like this, however, I couldn't get it to hook up.\n\n```\n\n```\n\nThe child component has some logic that looks like this:\n\n```\n \n export let myThing = '';\n \n\n myThing= 'Update'} />\n```\n\nThis does not seem to work, what am I missing?\n\n========================================\n\nTop Answer:\nOr like this (without dispatch):\n\nParent:\n\n```\n\n import Child from \"./Child.svelte\";\n\n let count = 0;\n const handleClick = () => {\n count += 1;\n };\n\n Parent count: {count}\n\n \n\n```\n\nChild:\n\n```\n// child component\n\n export let count;\n\n Clicked {count}\n\n```\n\n========================================\n\nCode:\n```text\n<Component on:customClick={myThing}>\n```\n\n```text\n<script> \n export let myThing = '';\n <script> \n\n<input type=\"text\" onClick={() => myThing= 'Update'} />\n```\n\n```text\non:click\n```\n\n```text\n// children component\n<script>\n import { createEventDispatcher } from \"svelte\";\n\n const dispatch = createEventDispatcher();\n\n let count = 0;\n\n function handleClick() {\n count += 1;\n dispatch(\"customClick\", {\n count\n });\n }\n</script>\n\n<button on:click={handleClick}>\n Clicked {count} {count === 1 ? 'time' : 'times'}\n</button>\n```\n\n```text\n// parent component\n<script>\n import ChildrenComponent from \"./ChildrenComponent.svelte\";\n\n let count;\n\n const handleCustomClick = event => {\n count = event.detail.count;\n };\n</script>\n\n<main>\n <p>Parent count: {count || 0}</p>\n <ChildrenComponent on:customClick={handleCustomClick}/>\n</main>\n```\n\n```text\n<script>\n import Child from \"./Child.svelte\";\n\n let count = 0;\n const handleClick = () => {\n count += 1;\n };\n</script>\n\n<main>\n <p>Parent count: {count}</p>\n <Child {count} on:click={handleClick} />\n</main>\n```\n\n```text\n// child component\n<script>\n export let count;\n</script>\n\n<button on:click>\n Clicked {count}\n</button>\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.691Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":141,"estimatedTokens":538}}440{"id":"stack-75922499","source":"stackoverflow","questionId":75922499,"title":"How do I import a text file in SvelteKit?","tags":["svelte","sveltekit"],"text":"Title: How do I import a text file in SvelteKit?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am trying to import a txt file and print the lines in my SvelteKit app. I tried to fetch it with the server and also I tried to import it straight into the component but I cannot get either to work. I have tried adding the txt file to both the static folder and public. This is how I tried to import it on the component.\n\n```\nonMount(() => {\n loadItems();\n });\n\n const loadItems = async () => {\n const response = await fetch('public/safety.txt');\n const text = await response.text();\n items = text.split('\\n\\n'); // split on double newlines\n };\n\n let currentIndex = 0;\n\n const interval = setInterval(() => {\n currentIndex = Math.floor(Math.random() * items.length);\n }, 5000);\n\n $: currentItem = items[currentIndex];\n\n onDestroy(() => {\n clearInterval(interval);\n });\n```\n\nAnd this is how I tried on the server:\n\n```\nconst safety = await fetch('/public/safety.txt')\n```\n\n========================================\n\nTop Answer:\nIt's not clear what the error is, but here is a working sample repl: https://svelte.dev/repl/650551a080e84d8da8b37a96bf79a089?version=3.58.0\n\n========================================\n\nCode:\n```js\nonMount(() => {\n loadItems();\n });\n\n const loadItems = async () => {\n const response = await fetch('public/safety.txt');\n const text = await response.text();\n items = text.split('\\n\\n'); // split on double newlines\n };\n\n let currentIndex = 0;\n\n const interval = setInterval(() => {\n currentIndex = Math.floor(Math.random() * items.length);\n }, 5000);\n\n $: currentItem = items[currentIndex];\n\n onDestroy(() => {\n clearInterval(interval);\n });\n```\n\n```js\nconst safety = await fetch('/public/safety.txt')\n```\n\n```text\nconst response = await fetch('safety.txt');\n```\n\n```text\n// Load assets as strings\nimport assetAsString from './shader.glsl?raw'\n```\n\n========================================\n\nComments:\n- Use vite: vitejs.dev/guide/assets.html#importing-asset-as-string\n- I am trying import a text file like the repl, only instead of importing the txt file from a website I have the text file. I am unsure what folder to put the text file in and how to reference it.\n- in sveltekit, you can add the file into the public directory and then fetch ('safety.txt'); (exclude the '/static/') or just try browsing to localhost:5173/safety.txt\n- I was able to get it working by adding the static folder to the server allow as shown here.\n- This is the way to go if you want the string to be part of the build.","metadata":{"transformedAt":"2026-08-18T18:33:40.692Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":90,"estimatedTokens":650}}441{"id":"stack-59497908","source":"stackoverflow","questionId":59497908,"title":"Animations in svelte component","tags":["javascript","svelte"],"text":"Title: Animations in svelte component\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm building drag'n'drop component for svelte and would like to add animations.\nI have adapted code from another component, but I cannot make it to work, could you help me pinpoint where the problem is? I don't understand error im getting.\nhere is working REPL\n\nhttps://svelte.dev/repl/acc2c90db2054d89b210f23c026c525e?version=3.16.7\n\nerror shows when I paste:\n\n```\nin:receive={{ key: index }}\nout:send={{ key: index }}\nanimate:flip={{ duration: 300 }}\n```\n\ninto line 130 of component in REPL\n\nfollowing error message i get:\n\"An element that use the animate directive must be the immediate child of a keyed each block (132:8)\"\n\ni have tried to remove \"wrap\" div to move animate one as \"direct child\" of #each but it didnt help\n\n```\n{#if list && list.length}\n\n {#each list as item, index}\n \n { return false }}\n on:touchstart={handleMousedown}\n on:touchmove={handleMousemove}\n on:touchend={handleMouseup}\n on:mousedown={handleMousedown}\n on:mousemove={handleMousemove}\n on:mouseover={HandleMouseover}\n in:receive={{ key: index }}\n out:send={{ key: index }}\n animate:flip={{ duration: 300 }}\n class=\"tobedragged {((index == movingIndex) && moving) ? 'ghost' : ''}\" style=\"top: {m.y}px; left: {m.x}px;\">\n list index: {index}\n\n {item}\n \n \n\n{/each}\n\n{/if}\n```\n\n========================================\n\nCode:\n```text\nin:receive={{ key: index }}\nout:send={{ key: index }}\nanimate:flip={{ duration: 300 }}\n```\n\n```text\n{#if list && list.length}\n<div class=\"cont\">\n {#each list as item, index}\n <div class=\"wrap\">\n <div\n data-index={index}\n id={index}\n on:dragstart={() => { return false }}\n on:touchstart={handleMousedown}\n on:touchmove={handleMousemove}\n on:touchend={handleMouseup}\n on:mousedown={handleMousedown}\n on:mousemove={handleMousemove}\n on:mouseover={HandleMouseover}\n in:receive={{ key: index }}\n out:send={{ key: index }}\n animate:flip={{ duration: 300 }}\n class=\"tobedragged {((index == movingIndex) && moving) ? 'ghost' : ''}\" style=\"top: {m.y}px; left: {m.x}px;\">\n list index: {index}<br>\n {item}\n <slot {item} {index} />\n </div>\n</div>\n{/each}\n</div>\n{/if}\n```\n\n```text\n{#each list as item, index (item)}\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.692Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":94,"estimatedTokens":586}}442{"id":"stack-56010964","source":"stackoverflow","questionId":56010964,"title":"How to use javascript libraries that require binding to DOM nodes","tags":["ag-grid","svelte"],"text":"Title: How to use javascript libraries that require binding to DOM nodes\nTags: ag-grid, svelte\nSource: Stack Overflow\n\nQuestion:\nI have been trying to use Ag-Grid with Svelte. I understand that the main problem with using this grid library is that it needs to bind to a dom element that may not exist at the time of the code executing. For example:\n\n```\n// lookup the container we want the Grid to use\n var eGridDiv = document.querySelector('#myGrid');\n```\n\nIn this case, the #myGrid element does not exist yet.\n\nI have tried creating an element and then placing it on the HTML part of the Svelte component, like this.\n\n```\nlet eGridDiv = document.createElement(\"DIV\"); \nlet gridOptions = { columnDefs: columnDefs, rowData: $orders };\nnew Grid(eGridDiv, gridOptions);\n```\n\nAnd then down on the HTML section\n\n```\n\n```\n\nHowever, the new element does not seem to be initialized by Ag-Grid.\n\nSo what is the recommended way to use these types of libraries in Svelte?\n\nhttps://i.sstatic.net/T4GKc.png\n\n========================================\n\nCode:\n```text\n// lookup the container we want the Grid to use\n var eGridDiv = document.querySelector('#myGrid');\n```\n\n```text\nlet eGridDiv = document.createElement(\"DIV\"); \nlet gridOptions = { columnDefs: columnDefs, rowData: $orders };\nnew Grid(eGridDiv, gridOptions);\n```\n\n```text\n<eGridDiv />\n```\n\n```html\n<script>\n import { onMount } from 'svelte';\n let domNode;\n\n // ...\n\n onMount(() => {\n const gridOptions = { columnDefs: columnDefs, rowData: $orders };\n new Grid(domNode, gridOptions);\n });\n</script>\n\n<div bind:this={domNode} />\n```\n\n```text\nbind:this={domNode}\n```\n\n```text\nonMount\n```\n\n========================================\n\nComments:\n- i'm facing the same challenge to use ag-grid in my svelte project. right now i can't find the proper way to import agGrid correctly. how did you solve that problem? `import {Grid} from '@ag-grid-community/all-modules';` does not seem to work as it throws \"circular dependecies error\"","metadata":{"transformedAt":"2026-08-18T18:33:40.692Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":80,"estimatedTokens":497}}443{"id":"stack-74699456","source":"stackoverflow","questionId":74699456,"title":"Adding a svelte component to DOM at runtime?","tags":["dynamic","svelte","appendchild","svelte-component"],"text":"Title: Adding a svelte component to DOM at runtime?\nTags: dynamic, svelte, appendchild, svelte-component\nSource: Stack Overflow\n\nQuestion:\nAdding a svelte component (Button) statically in the body section works. Adding the Button via appendChild does not?\n\nDetails:\n\nImagine a database table. For each row I add a line into my HTML body.\n\nHow could I add a svelte component (Button.svelte) to each row, too?\n\nThe problem: Standard HTML gets appended, but my svelte Button does not. (Probably because svelte needs to render at compile time.)\n\nFor example in +page.svelte:\n\n```\nconst e = document.getElementById('my_div_container');\nif(e)\n{\n const p = document.createElement(\"p\");\n const txt = document.createTextNode(\"test node\");\n p.appendChild(txt);\n e.appendChild(p); // Example lib/Button.svelte:\n\n```\n\n function on_click()\n {\n console.log('clicked');\n }\n\n on_click()}>Click\n```\n\nFYI: Statically adding a button to the HTML body works of course:\n\n```\nSome text\n\n```\n\n========================================\n\nCode:\n```text\nconst e = document.getElementById('my_div_container');\nif(e)\n{\n const p = document.createElement(\"p\");\n const txt = document.createTextNode(\"test node\");\n p.appendChild(txt);\n e.appendChild(p); // <-- ok, gets displayed\n const b = document.createElement(\"Button\");\n e.appendChild(b); // <-- NOT displayed\n}\n```\n\n```text\n<script>\n function on_click()\n {\n console.log('clicked');\n }\n</script>\n<button on:click={() => on_click()}>Click</button>\n```\n\n```text\n<p>Some text</p>\n<Button />\n```\n\n```js\nimport { mount } from 'svelte';\nimport Button from './Button.svelte';\n\nmount(Button, { target: e });\n\n// In Svelte 3/4, components are constructed as classes instead:\nnew Button({ target: e });\n```\n\n```text\ncreateElement\n```\n\n```text\nmount\n```\n\n```text\ntarget\n```\n\n========================================\n\nComments:\n- The `as custom elements` link is broken (404), should probably be changed to `https://svelte.dev/docs/client-side-component-api#creating-a‌​-component` ?\n- @user2602152: That would be for the second link. I updated both.","metadata":{"transformedAt":"2026-08-18T18:33:40.692Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":101,"estimatedTokens":530}}444{"id":"stack-68688341","source":"stackoverflow","questionId":68688341,"title":"HowTo add another component on button click","tags":["svelte"],"text":"Title: HowTo add another component on button click\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI am creating a data entry table. I wish to add a new row to the table when the AddRow button is clicked.\n\nMy structure is a `` component with a `` subcomponent and one or more `` subcomponents.\n\nHere's my first newbie attempt:\n\n```\nlet numRows = [1,1,1,1,1,1,1];\n\n \n {#each numRows as num}\n \n {/each}\n\n numRows.push(1)}>Add Row\n```\n\nOn initial run, 7 rows are created as specified by the length of the `numRows` array initial value.\n\nHowever, clicking the `AddRow` button does nothing *(console logging shows that the array is being correctly updated. But of course nothing is telling the `#each` loop to re-run.)*\n\nHow should this app be restructured to make the AddRows button work?\n\nThe numRows array seems a klunky way to manage creating new rows. Is there a more Sveltic way to do this?\n\n========================================\n\nCode:\n```text\nlet numRows = [1,1,1,1,1,1,1];\n\n<div class='efContainer'>\n <FormHeader />\n {#each numRows as num}\n <FormRow />\n {/each}\n</div>\n\n<Button on:click={() => numRows.push(1)}>Add Row</Button>\n```\n\n```text\n<DataEntryForm>\n```\n\n```text\n<FormHeader>\n```\n\n```text\n<FormRow>\n```\n\n```text\nnumRows\n```\n\n```text\nAddRow\n```\n\n```text\n#each\n```\n\n```text\nnumRows.push(1)\n```\n\n```text\nnumRows\n```\n\n```text\non:click={() => numRows.push(1)}\n```\n\n```text\non:click={updateArray}\n```\n\n```text\nupdateArray = () => {numRows = [...numRows, 1]}\n```\n\n========================================\n\nComments:\n- Ah, so that was it. I forgot about the need to destructure and re-assign. Actually, this inline code worked: `on:click={() => numRows = [...numRows, 1]}` *Many thanks!*","metadata":{"transformedAt":"2026-08-18T18:33:40.692Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":94,"estimatedTokens":426}}445{"id":"stack-63192792","source":"stackoverflow","questionId":63192792,"title":"Responsive full width canvas in sveltejs","tags":["javascript","html5-canvas","svelte","svelte-3"],"text":"Title: Responsive full width canvas in sveltejs\nTags: javascript, html5-canvas, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI'm quite new to svelte and I'm trying to get a canvas to render on the full screen using svelte. Sounds quite easy to do, but I can't get it to work properly. I'm binding a `width` and `height` variable to the `clientWidth`/`clientHeight` of the parent and using these variables to set the dimensions of the canvas. The issue now is that when `onMount` is called, the `width` and `height` variables are set but they are not applied to the canvas element yet. This means when the canvas renders for the first time, it still has the initial dimensions and not the ones of the parent. Only when I render it a second time it has the proper dimensions. How can get the canvas to have the right dimensions on the first render or render the canvas again when it has the proper dimensions?\n\nHere you can find a \"working\" version.\n\n```\n\n import { onMount } from \"svelte\";\n\n let canvas;\n let ctx;\n let width = 1007;\n let height = 1140;\n\n const draw = () => {\n ctx.clearRect(0, 0, width, height);\n ctx.beginPath();\n ctx.moveTo(width/2 - 50, height/2);\n ctx.arc(width/2, height/2, 50, 0, 2 * Math.PI);\n ctx.fill();\n }\n \n onMount(() => {\n ctx = canvas.getContext(\"2d\");\n draw();\n setTimeout(draw, 5000);\n });\n\n .container {\n width: 100%;\n height: 100%;\n }\n\n \n\n```\n\n========================================\n\nCode:\n```text\n<script>\n import { onMount } from \"svelte\";\n\n let canvas;\n let ctx;\n let width = 1007;\n let height = 1140;\n\n const draw = () => {\n ctx.clearRect(0, 0, width, height);\n ctx.beginPath();\n ctx.moveTo(width/2 - 50, height/2);\n ctx.arc(width/2, height/2, 50, 0, 2 * Math.PI);\n ctx.fill();\n }\n \n onMount(() => {\n ctx = canvas.getContext(\"2d\");\n draw();\n setTimeout(draw, 5000);\n });\n</script>\n\n<style>\n .container {\n width: 100%;\n height: 100%;\n }\n</style>\n\n<div\n class=\"container\"\n bind:clientWidth={width}\n bind:clientHeight={height}>\n <canvas bind:this={canvas} {width} {height} />\n</div>\n```\n\n```text\nwidth\n```\n\n```text\nheight\n```\n\n```text\nclientWidth\n```\n\n```text\nclientHeight\n```\n\n```text\nonMount\n```\n\n```text\nwidth\n```\n\n```text\nheight\n```\n\n```js\nimport { onMount, tick } from 'svelte';\n\nonMount(async () => {\n ctx = canvas.getContext(\"2d\");\n canvas.width = width;\n canvas.height = height;\n await tick()\n draw();\n});\n```\n\n```text\nawait tick()\n```\n\n========================================\n\nComments:\n- Your code seems to be working fine as far as I'm concerned. svelte.dev/repl/49b8091d3d5c400b8c912be90d03c93e?version=3.2‌​4.0 the canvas is always full client width & height, be it on initial load, page refresh or after a resize. I even tried it in different browsers, always worked as expected?\n- Hey, thanks for you comment. Yes the size of the canvas is adjusted correctly. The issue is that when onMount is called the width and height variables are set correctly but they are not applied to the canvas yet. This means that when draw() is called the width/height variables don't correspond to the width/height of the canvas. Only on the next render the dimensions of the canvas are set which causes the black circle from draw() to disappear.\n- Works! Thanks a lot!\n- The `tick()` is unnecessary here, no? The important point is that `canvas.width` and `canvas.height` are set immediately before `draw()` (and `{width} and`{height}` should be removed from the `` accordingly)\n- That is correct, if you remove the `{width}` and `{height}` from the canvas element itself, the tick is not necessary.","metadata":{"transformedAt":"2026-08-18T18:33:40.692Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":135,"estimatedTokens":904}}446{"id":"stack-59994236","source":"stackoverflow","questionId":59994236,"title":"How to integrate Material UI into Svelte project","tags":["material-ui","svelte","rollupjs"],"text":"Title: How to integrate Material UI into Svelte project\nTags: material-ui, svelte, rollupjs\nSource: Stack Overflow\n\nQuestion:\nI want to integrate Material UI into my Svelte project.\n\nI tried to the official documentation from here, but I don't know why I'm getting a strange error while trying to run my project:\n\n```\nloaded rollup.config.js with warnings\n(!) Unused external imports\ndefault imported from external module 'rollup-plugin-postcss' but never used\nrollup v1.27.13\nbundles src/main.js → public/build/bundle.js...\n[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)\nsrc/views/App.css (1:0)\n1: .footer.svelte-1xl6ht0{position:fixed;left:0;bottom:0;width:100%;background-color:#569e3e;color:white;text-align:center;height:15px}.footer.us.svelte-1xl6ht0,.footer.europe.svelte-1xl6ht0,.footer.central.svelte-1xl6ht0,.footer.south.svelte-1xl6ht0,.footer.apac.svelte-1xl6ht0,.footer.baldr.svelte-1xl6ht0{background-color:#ca4a4a}.footer\n....\n```\n\nThe problem seems to be related to CSS.\n\nIn my `src` directory I have a directory called `theme` which contains a file called `_smui-theme.scss` and this is the content of the file:\n\n```\n@import \"@material/theme/color-palette\";\n\n// Svelte Colors!\n$mdc-theme-primary: #ff3e00;\n$mdc-theme-secondary: #676778;\n// Other Svelte color: #40b3ff\n\n$mdc-theme-background: #fff;\n$mdc-theme-surface: #fff;\n\n$mdc-theme-error: $material-color-red-900;\n```\n\nAnd here is my `rollup.config.json` file:\n\n```\nimport svelte from 'rollup-plugin-svelte';\nimport resolve from 'rollup-plugin-node-resolve';\nimport commonjs from 'rollup-plugin-commonjs';\nimport livereload from 'rollup-plugin-livereload';\nimport { terser } from 'rollup-plugin-terser';\nimport json from '@rollup/plugin-json';\n\nconst production = !process.env.ROLLUP_WATCH;\n\nexport default {\n input: 'src/main.js',\n output: {\n sourcemap: true,\n format: 'iife',\n name: 'app',\n file: 'public/build/bundle.js',\n },\n plugins: [\n json(),\n svelte({\n // Enables run-time checks when not in production.\n dev: !production,\n\n // Extracts any component CSS out into a separate file — better for performance.\n css: css => css.write('public/build/bundle.css'),\n\n // Emit CSS as \"files\" for other plugins to process\n emitCss: true,\n }),\n\n resolve({\n browser: true,\n dedupe: importee => importee === 'svelte' || importee.startsWith('svelte/')\n }),\n commonjs(),\n\n // In dev mode, call `npm run start` once the bundle has been generated\n !production && serve(),\n\n // Watches the `public` directory and refresh the browser on changes when not in production.\n !production && livereload('public'),\n\n // Minify for production.\n production && terser()\n ],\n watch: {\n clearScreen: false\n }\n};\n\nfunction serve() {\n let started = false;\n\n return {\n writeBundle() {\n if (!started) {\n started = true;\n\n require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {\n stdio: ['ignore', 'inherit', 'inherit'],\n shell: true\n });\n }\n }\n };\n}\n```\n\n========================================\n\nCode:\n```text\nloaded rollup.config.js with warnings\n(!) Unused external imports\ndefault imported from external module 'rollup-plugin-postcss' but never used\nrollup v1.27.13\nbundles src/main.js → public/build/bundle.js...\n[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)\nsrc/views/App.css (1:0)\n1: .footer.svelte-1xl6ht0{position:fixed;left:0;bottom:0;width:100%;background-color:#569e3e;color:white;text-align:center;height:15px}.footer.us.svelte-1xl6ht0,.footer.europe.svelte-1xl6ht0,.footer.central.svelte-1xl6ht0,.footer.south.svelte-1xl6ht0,.footer.apac.svelte-1xl6ht0,.footer.baldr.svelte-1xl6ht0{background-color:#ca4a4a}.footer\n....\n```\n\n```text\n@import \"@material/theme/color-palette\";\n\n// Svelte Colors!\n$mdc-theme-primary: #ff3e00;\n$mdc-theme-secondary: #676778;\n// Other Svelte color: #40b3ff\n\n$mdc-theme-background: #fff;\n$mdc-theme-surface: #fff;\n\n$mdc-theme-error: $material-color-red-900;\n```\n\n```text\nimport svelte from 'rollup-plugin-svelte';\nimport resolve from 'rollup-plugin-node-resolve';\nimport commonjs from 'rollup-plugin-commonjs';\nimport livereload from 'rollup-plugin-livereload';\nimport { terser } from 'rollup-plugin-terser';\nimport json from '@rollup/plugin-json';\n\nconst production = !process.env.ROLLUP_WATCH;\n\nexport default {\n input: 'src/main.js',\n output: {\n sourcemap: true,\n format: 'iife',\n name: 'app',\n file: 'public/build/bundle.js',\n },\n plugins: [\n json(),\n svelte({\n // Enables run-time checks when not in production.\n dev: !production,\n\n // Extracts any component CSS out into a separate file — better for performance.\n css: css => css.write('public/build/bundle.css'),\n\n // Emit CSS as \"files\" for other plugins to process\n emitCss: true,\n }),\n\n resolve({\n browser: true,\n dedupe: importee => importee === 'svelte' || importee.startsWith('svelte/')\n }),\n commonjs(),\n\n // In dev mode, call `npm run start` once the bundle has been generated\n !production && serve(),\n\n // Watches the `public` directory and refresh the browser on changes when not in production.\n !production && livereload('public'),\n\n // Minify for production.\n production && terser()\n ],\n watch: {\n clearScreen: false\n }\n};\n\nfunction serve() {\n let started = false;\n\n return {\n writeBundle() {\n if (!started) {\n started = true;\n\n require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {\n stdio: ['ignore', 'inherit', 'inherit'],\n shell: true\n });\n }\n }\n };\n}\n```\n\n```text\nsrc\n```\n\n```text\ntheme\n```\n\n```text\n_smui-theme.scss\n```\n\n```text\nrollup.config.json\n```\n\n```text\nimport svelte from 'rollup-plugin-svelte';\nimport resolve from 'rollup-plugin-node-resolve';\nimport commonjs from 'rollup-plugin-commonjs';\nimport livereload from 'rollup-plugin-livereload';\nimport { terser } from 'rollup-plugin-terser';\nimport postcss from 'rollup-plugin-postcss'; <<<------------- Add this\nimport autoPreprocess from 'svelte-preprocess'; <<<------------- Add this\nimport json from '@rollup/plugin-json';\n\nconst production = !process.env.ROLLUP_WATCH;\n\nexport default {\n input: 'src/main.js',\n output: {\n sourcemap: true,\n format: 'iife',\n name: 'app',\n file: 'public/build/bundle.js',\n },\n plugins: [\n json(),\n svelte({\n // Enables run-time checks when not in production.\n dev: !production,\n\n // Extracts any component CSS out into a separate file — better for performance.\n css: css => css.write('public/build/bundle.css'),\n\n // Emit CSS as \"files\" for other plugins to process\n emitCss: true,\n\n preprocess: autoPreprocess() <<<------------- Add this\n }),\n\n resolve({\n browser: true,\n dedupe: importee => importee === 'svelte' || importee.startsWith('svelte/')\n }),\n commonjs(),\n\n postcss({ <<<------------- Add this\n extract: true,\n minimize: true,\n use: [\n ['sass', {\n includePaths: [\n './src/theme',\n './node_modules'\n ]\n }]\n ]\n }),\n\n // In dev mode, call `npm run start` once the bundle has been generated\n !production && serve(),\n\n // Watches the `public` directory and refresh the browser on changes when not in production.\n !production && livereload('public'),\n\n // Minify for production.\n production && terser()\n ],\n watch: {\n clearScreen: false\n }\n};\n\nfunction serve() {\n let started = false;\n\n return {\n writeBundle() {\n if (!started) {\n started = true;\n\n require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {\n stdio: ['ignore', 'inherit', 'inherit'],\n shell: true\n });\n }\n }\n };\n}\n```\n\n```text\npostcss\n```\n\n```text\nnpm\n```\n\n```text\nyarn\n```\n\n```text\nrollup-plugin-postcss\n```\n\n```text\nsvelte-preprocess\n```\n\n```text\nrollup.config.js\n```\n\n========================================\n\nComments:\n- Hi, following your approach I get : ` Unexpected character '@' (Note that you need plugins to import files that are not JavaScript) 1: @import \"smui-theme\";` have you encoutered this error before? how did you get past it?\n- Hi, what is the `@import` ? it does not seems to me a good js syntax\n- I used a template instead. When setting material design on sapper , after following a similar approach as yours ( with the roll-up file) I got that error but there is no where I import like that. Anyways, the issue is now gone","metadata":{"transformedAt":"2026-08-18T18:33:40.692Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":340,"estimatedTokens":2261}}447{"id":"stack-67510948","source":"stackoverflow","questionId":67510948,"title":"importing winston causes 'process is not defined'","tags":["javascript","svelte","winston","sveltekit"],"text":"Title: importing winston causes 'process is not defined'\nTags: javascript, svelte, winston, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am creating an app with sveltekit and am currently adding logging.\n\nSimple enough in the backend with winston as it works pretty much out of the box.\n\nBut I am running into some issues with importing it on the frontend.\n\nmy code is pretty simple\n\n```\n\n import winston from 'winston';\n import { Card } from '../components/issue/';\n\n export let project;\n\n```\n\nbut that simple snippet seems to throw this error\n\n```\n500\nprocess is not defined\n\nReferenceError: process is not defined\n at node_modules/colors/lib/system/supports-colors.js (http://localhost:3000/node_modules/.vite/winston.js?v=b8878498:281:15)\n at __require (http://localhost:3000/node_modules/.vite/chunk-JAKTRAE2.js?v=b8878498:6:44)\n at node_modules/colors/lib/colors.js (http://localhost:3000/node_modules/.vite/winston.js?v=b8878498:714:28)\n at __require (http://localhost:3000/node_modules/.vite/chunk-JAKTRAE2.js?v=b8878498:6:44)\n at node_modules/colors/safe.js (http://localhost:3000/node_modules/.vite/winston.js?v=b8878498:850:18)\n at __require (http://localhost:3000/node_modules/.vite/chunk-JAKTRAE2.js?v=b8878498:6:44)\n at node_modules/logform/dist/colorize.js (http://localhost:3000/node_modules/.vite/winston.js?v=b8878498:881:18)\n at __require (http://localhost:3000/node_modules/.vite/chunk-JAKTRAE2.js?v=b8878498:6:44)\n at node_modules/logform/dist/levels.js (http://localhost:3000/node_modules/.vite/winston.js?v=b8878498:953:20)\n at __require (http://localhost:3000/node_modules/.vite/chunk-JAKTRAE2.js?v=b8878498:6:44)\n```\n\nI honestly have no real idea of what could be wrong other that it possibly being an issue with server/client side rendering.\n\nso I guess the question is: can you import winston in a sveltekit project, and if so how?\nand is there any workarounds to this specific issue?\n\n========================================\n\nCode:\n```html\n<script>\n import winston from 'winston';\n import { Card } from '../components/issue/';\n\n export let project;\n</script>\n```\n\n```text\n500\nprocess is not defined\n\nReferenceError: process is not defined\n at node_modules/colors/lib/system/supports-colors.js (http://localhost:3000/node_modules/.vite/winston.js?v=b8878498:281:15)\n at __require (http://localhost:3000/node_modules/.vite/chunk-JAKTRAE2.js?v=b8878498:6:44)\n at node_modules/colors/lib/colors.js (http://localhost:3000/node_modules/.vite/winston.js?v=b8878498:714:28)\n at __require (http://localhost:3000/node_modules/.vite/chunk-JAKTRAE2.js?v=b8878498:6:44)\n at node_modules/colors/safe.js (http://localhost:3000/node_modules/.vite/winston.js?v=b8878498:850:18)\n at __require (http://localhost:3000/node_modules/.vite/chunk-JAKTRAE2.js?v=b8878498:6:44)\n at node_modules/logform/dist/colorize.js (http://localhost:3000/node_modules/.vite/winston.js?v=b8878498:881:18)\n at __require (http://localhost:3000/node_modules/.vite/chunk-JAKTRAE2.js?v=b8878498:6:44)\n at node_modules/logform/dist/levels.js (http://localhost:3000/node_modules/.vite/winston.js?v=b8878498:953:20)\n at __require (http://localhost:3000/node_modules/.vite/chunk-JAKTRAE2.js?v=b8878498:6:44)\n```\n\n========================================\n\nComments:\n- winston appears to be made for nodejs.","metadata":{"transformedAt":"2026-08-18T18:33:40.692Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":79,"estimatedTokens":832}}448{"id":"stack-63337868","source":"stackoverflow","questionId":63337868,"title":"Svelte TypeScript: Unexpected token when adding type to an event handler","tags":["typescript","svelte"],"text":"Title: Svelte TypeScript: Unexpected token when adding type to an event handler\nTags: typescript, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implement TypeScript into Svelte and has a problem like this: when I try to add type to an event in beneath line:\n\n```\non:click={(e: Event) => onClick(e, data)}\n```\n\nit yells about:\n\nError: ParseError: Unexpected token\n\nIf I remove typing it says that:\n\nParameter 'e' implicitly has an 'any' type.\n\nHow can I add type to this kind of things without an error in Svelte?\n\nEDIT:\nMore complex example:\n\n```\n{#each elementsArray as element}\n doSomething(e, element)}>\n \n {/each}\n```\n\n========================================\n\nTop Answer:\nThere are a number of bugs files on this issue, e.g. svelte/4701\n\n========================================\n\nCode:\n```text\non:click={(e: Event) => onClick(e, data)}\n```\n\n```text\n{#each elementsArray as element}\n <CustomComponent\n on:itemClick={(e: Event) => doSomething(e, element)}>\n </CustomComponent>\n {/each}\n```\n\n```text\n<script lang=\"ts\">\n function onClick(e: MouseEvent) { ... }\n</script>\n<button on:click={onClick}></button>\n```\n\n```text\n<script lang=\"ts\">\n let elems = [1,2,3];\n \n function onClick(e: CustomEvent<{foo: string}>, el: number) {\n console.log(e.detail.name);\n }\n<script>\n{#each elems as el}\n <CustomComponent on:itemClick={e => onClick(e, el)}></CustomComponent>\n{/each}\n```\n\n```text\n<script>\n```\n\n```text\ncreateEventDispatcher\n```\n\n```text\ne\n```\n\n```text\nCustomEvent<any>\n```\n\n```text\n<script>\n```\n\n```text\nnoImplicitAny\n```\n\n```text\ntsconfig.json\n```\n\n```text\nlet elementsArray = [\"foo\", \"bar\", \"lorem\", \"ipsum\"];\n\nfunction doSomething(evt: Event, element: string) {\n console.log(\"doSomething() called\", evt, element);\n}\n\nfunction callbackFactory1(element: string) {\n return (evt: Event) => {\n doSomething(evt, element);\n };\n}\n\nfunction callbackFactory2(callback: Function, ...args: unknown[]) {\n return (evt: Event) => {\n callback(evt, ...args);\n };\n}\n```\n\n```html\n{#each elementsArray as element}\n <p><a on:click={callbackFactory1(element)} href=\"#\">{element}</a></p>\n <p><a on:click={callbackFactory2(doSomething, element)} href=\"#\">{element}</a></p>\n{/each}\n```\n\n```text\nfunction curriedDoSomething(evt: Event) {\n return (element: string) => {\n console.log(\"curriedDoSomething() called\", evt, element);\n // Either call doSomething() or implement logic here\n };\n}\n\nfunction callbackFactory3<TE extends Event, TA extends unknown[]>(callback: (evt: TE) => (...args: TA) => void) {\n return (...args: TA) => {\n return (evt: TE) => {\n callback(evt)(...args);\n };\n };\n}\n```\n\n```html\n<a on:click={callbackFactory3(curriedDoSomething)(element)} href=\"#\">{element}</a>\n```\n\n```text\ncallbackFactory()\n```\n\n```text\ncallbackFactory1()\n```\n\n========================================\n\nComments:\n- But one question about that - what if I have some more properties to pass? Not only an event? Like on:click=((e) => onClick(e, someThing))\n- Where's that `someThing` coming from? is that a prop from the `script`? It seems to me like it's not coming from the template so I think you can just use `someThing` in the `onClick` function as a \"global\". It won't feel as clean, though.\n- Carlo, I've updated original post andd added some more complex code that explains what I'm aiming at. In that case don't know how to pass info about what element I'm clicking.\n- I've updated my answer to handle the more complex case. I'm not getting errors for `e` being `any`.","metadata":{"transformedAt":"2026-08-18T18:33:40.692Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":162,"estimatedTokens":892}}449{"id":"stack-77843430","source":"stackoverflow","questionId":77843430,"title":"What does `svelte-kit sync` do?","tags":["typescript","vite","svelte","sveltekit"],"text":"Title: What does `svelte-kit sync` do?\nTags: typescript, vite, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI've checked the svelte-kit sync docs and the discussion around it and even tried searching Stack Overflow and asking AI.\n\nMy understanding is it generates `tsconfig.json` and is for setting up the project with typescript. When I delete my `tsconfig.json` and run it, nothing seems to happen.\n\n========================================\n\nCode:\n```text\ntsconfig.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\nload\n```\n\n```text\ndata\n```\n\n```text\nform\n```\n\n```text\ntsconfig.json\n```\n\n```text\n.svelte-kit\n```\n\n```text\nsync\n```\n\n========================================\n\nComments:\n- Awesome, thank you! So, when you say \"running separate builds\" you mean it's useful for having a setup where you can build the same project in different ways?\n- I mean e.g. a clean install in a CI pipeline where the dev server is never run at all, so the types would not be there otherwise.\n- You will also want to ensure that your own tsconfig file inherits from the generated one at `./svelte-kit.json` eg: ``` { \"extends\": \"./.svelte-kit/tsconfig.json\", \"compilerOptions\": { \"allowJs\": true, \"checkJs\": true, \"esModuleInterop\": true, \"forceConsistentCasingInFileNames\": true, \"resolveJsonModule\": true, \"skipLibCheck\": true, \"sourceMap\": true, \"strict\": true, \"module\": \"NodeNext\", \"moduleResolution\": \"NodeNext\" } } ```\n- You will also want to ensure that your own tsconfig file inherits from the generated one at `./svelte-kit.json` eg: `{\"extends\": \"./.svelte-kit/tsconfig.json\",\"compilerOptions\": {...}}`\n- @AnthonyHolland: You did not have to list all the other settings and this is set up correctly by default when using `npm create svelte` anyway. (Hence probably only relevant if TS is added manually later.)","metadata":{"transformedAt":"2026-08-18T18:33:40.692Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":52,"estimatedTokens":456}}450{"id":"stack-72587871","source":"stackoverflow","questionId":72587871,"title":"How to include an WASM npm module in svelte with vite?","tags":["svelte","webassembly","vite","wasm-pack"],"text":"Title: How to include an WASM npm module in svelte with vite?\nTags: svelte, webassembly, vite, wasm-pack\nSource: Stack Overflow\n\nQuestion:\nI'm using vite to run a svelte app, and have a WASM package built with `wasm-pack --target web`. If I use the package directly with vanilla JS, I can write something like:\n\n```\n\n import init, { greet } from \"./pkg/compiler.js\";\n\n init().then(() => {\n greet(\"Hello\");\n });\n\n```\n\nin an HTML file where `greet` is one of my `wasm_bindgen` functions, and that works fine.\n\nHowever, my intended pipeline is to publish the `pkg/` folder that `wasm-pack` generates to npm, and then use this package in svelte with vite, something like so:\n\n```\n\n import init, { greet } from \"@ocr-compiler/compiler\";\n \n init().then(() => {\n greet(\"Hello\");\n });\n\n```\n\nHowever, this throws an error:\n`Unknown file extension \".wasm\" for /home/drbracewell/code/ocr/packages/svelte-editor/node_modules/@ocr-compiler/compiler/compiler_bg.wasm`\nDoes anyone know how I can fix this?\nVite docs mention that it will automatically process `.wasm` files, but does this not happen when they're included from npm packages?\n\n========================================\n\nCode:\n```html\n<script type=\"module\">\n import init, { greet } from \"./pkg/compiler.js\";\n\n init().then(() => {\n greet(\"Hello\");\n });\n</script>\n```\n\n```html\n<script lang=\"ts\">\n import init, { greet } from \"@ocr-compiler/compiler\";\n \n init().then(() => {\n greet(\"Hello\");\n });\n</script>\n```\n\n```text\nwasm-pack --target web\n```\n\n```text\ngreet\n```\n\n```text\nwasm_bindgen\n```\n\n```text\npkg/\n```\n\n```text\nwasm-pack\n```\n\n```text\nUnknown file extension \".wasm\" for /home/drbracewell/code/ocr/packages/svelte-editor/node_modules/@ocr-compiler/compiler/compiler_bg.wasm\n```\n\n```text\n.wasm\n```\n\n```text\n--target web\n```\n\n```text\nwasm-pack\n```\n\n```text\nnpm\n```\n\n```text\nmain\n```\n\n```text\npackage.json\n```\n\n```text\nwasm-pack\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.692Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":110,"estimatedTokens":479}}451{"id":"stack-59143965","source":"stackoverflow","questionId":59143965,"title":"Debug Sapper server side","tags":["svelte","sapper"],"text":"Title: Debug Sapper server side\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI am trying to figure it how to debug the server side to do some modifications to the default sapper template, I followed the instructions to debug the server side from the docs, and the ndb opens correctly, but the only file that appears loaded in the gui is the webpack.config.js file:\n\nscreenshot\n\nThere is something else that I need to configure to debug the server.js file?\n\n========================================\n\nTop Answer:\nTo get @rixo's suggestion working on a windows 10 machine I had to do following:\n\nAdd following to scripts section of package.json \n\n```\n\"debug_server\": \"node --inspect-brk node_modules/sapper/sapper dev\"\n```\n\nThen I could run \n\n```\nnpm run debug_server\n```\n\nfrom command line.\n\n========================================\n\nCode:\n```sh\nnode --inspect-brk node_modules/.bin/sapper dev\n```\n\n```text\nndb\n```\n\n```text\npackage.json\n```\n\n```text\nnpm run dev\n```\n\n```text\nsapper dev\n```\n\n```text\nsapper\n```\n\n```text\nnode_modules/.bin\n```\n\n```text\nnode node_modules/.bin/sapper\n```\n\n```text\n--inspect\n```\n\n```text\n--inspect-brk\n```\n\n```text\ndebugger\n```\n\n```text\n\"debug_server\": \"node --inspect-brk node_modules/sapper/sapper dev\"\n```\n\n```text\nnpm run debug_server\n```\n\n```text\nterminal\n```\n\n```text\nnpm run dev\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.692Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":92,"estimatedTokens":332}}452{"id":"stack-72964719","source":"stackoverflow","questionId":72964719,"title":"How to trigger Svelte component update when imported variable changes","tags":["javascript","svelte"],"text":"Title: How to trigger Svelte component update when imported variable changes\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nSvelte allows conditional rendering based on the value of a variable in component scope. However, if a variable is imported, Svelte will not trigger an update upon the value change.\n\nWhat is the proper way to trigger an update in this case ?\n\nExample:\n\n`App.svelte`\n\n```\n\n import {flag, setFlag} from './flag.js'\n\n{#if flag}\n \n\n### Flag present\n\n{/if}\n\nsetFlag()}>Toggle\n```\n\n`flag.js`\n\n```\nexport let flag = false\nexport function setFlag() {\n flag = true;\n}\n```\n\nWhen clicking the button, the variable in `flag.js` changes, but the component does not re-render with the new value.\n\n========================================\n\nCode:\n```text\n<script>\n import {flag, setFlag} from './flag.js'\n</script>\n\n{#if flag}\n <h1>Flag present</h1>\n{/if}\n\n<button on:click={e =>setFlag()}>Toggle</button>\n```\n\n```text\nexport let flag = false\nexport function setFlag() {\n flag = true;\n}\n```\n\n```text\nApp.svelte\n```\n\n```text\nflag.js\n```\n\n```text\nflag.js\n```\n\n```js\nimport { writable } from 'svelte/store';\nexport const flag = writable(false);\nexport function setFlag() {\n flag.set(true);\n}\n```\n\n```html\n<script>\n import {flag, setFlag} from './flag.js'\n</script>\n\n{#if $flag}\n <h1>Flag present</h1>\n{/if}\n\n<button on:click={e =>setFlag()}>Toggle</button>\n```\n\n```html\n<button on:click={() => $flag = true}>Toggle</button>\n```\n\n```text\n$\n```\n\n```text\nsetFlag\n```\n\n========================================\n\nComments:\n- It was quite confusing for me but if you use an object in writable() you don't need to use set etc. functions\n- this is the only pain in svelte particularly when flag.js is a class","metadata":{"transformedAt":"2026-08-18T18:33:40.692Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":109,"estimatedTokens":433}}453{"id":"stack-73244322","source":"stackoverflow","questionId":73244322,"title":"How to specify what will be the export build js and css filenames in svelte","tags":["svelte","vite"],"text":"Title: How to specify what will be the export build js and css filenames in svelte\nTags: svelte, vite\nSource: Stack Overflow\n\nQuestion:\nI am using vite for svelte, I have attached vite.config.js below, I tried looking for references on the web but couldn't find any\n\n```\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n server: {\n port: 4000\n },\n preview: {\n port: 4000\n },\n plugins: [\n svelte({\n compilerOptions: {\n customElement: true,\n }\n }),\n ]})\n```\n\nhttps://i.sstatic.net/oH28m.png\n\n========================================\n\nCode:\n```text\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n server: {\n port: 4000\n },\n preview: {\n port: 4000\n },\n plugins: [\n svelte({\n compilerOptions: {\n customElement: true,\n }\n }),\n ]})\n```\n\n```js\nexport default defineConfig({\n build: {\n rollupOptions: {\n output: {\n entryFileNames: '[name].js',\n assetFileNames: '[name].[ext]',\n },\n },\n },\n plugins: [\n svelte(),\n ],\n});\n```\n\n```text\nbuild > rollupOptions\n```\n\n```text\nbuild.manifest\n```\n\n```text\n<script src=\"...\">\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.692Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":81,"estimatedTokens":334}}454{"id":"stack-76041012","source":"stackoverflow","questionId":76041012,"title":"Web Worker written in Typescript does not get built/compiled (using vite) into Javascript","tags":["javascript","typescript","svelte","vite","web-worker"],"text":"Title: Web Worker written in Typescript does not get built/compiled (using vite) into Javascript\nTags: javascript, typescript, svelte, vite, web-worker\nSource: Stack Overflow\n\nQuestion:\nI am using a Web Worker in typescript the following way:\n\n```\nconst url = new URL(\"src/lib/Functions/CalculateRidge.ts\", import.meta.url);\nconst worker = new Worker(url, { type: 'module' })\n```\n\nIn development, this work perfectly fine, the worker is loaded from the given url, and the worker executes the function and gives the correct result. But when building, all files get converted to .js except my worker file. Then in deployment (Github Pages) when the same code above is being executed, the url request IS succesful (it finds the file and makes a valid/succesful request for it), but the code fails with the following error message:\n\n\"Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of \"video/mp2t\". Strict MIME type checking is enforced for module scripts per HTML spec.\"\n\nI believe this error comes because a typescript file (a file with .ts extentions) cannot be executed or read, so i believe the error lays in that the Web Worker typescript file is not being compiled/transformed into Javascript.\n\nThis is an image of the distribution/build folder:\n\nhttps://i.sstatic.net/Oimck.png\n\nI use \"vite build\" to build the project and \"npx gh-pages -d dist\" to deploy the project to Github Pages. The `vite.config.ts` file looks like this:\n\n```\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\nimport path from 'path';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n base: \"/solar-analysis-faroe-island/\",\n plugins: [svelte()],\n resolve: {\n alias: {\n src: path.resolve('src/'),\n }\n },\n})\n```\n\n`tsconfig.node.json` looks like this:\n\n```\n{\n \"compilerOptions\": {\n \"composite\": true,\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Node\"\n },\n \"include\": [\"vite.config.ts\"]\n}\n```\n\n`tsconfig.json` looks like this:\n\n```\n{\n \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n \"compilerOptions\": {\n \"baseUrl\": \".\",\n \"target\": \"ESNext\",\n \"useDefineForClassFields\": true,\n \"module\": \"ESNext\",\n \"resolveJsonModule\": true,\n \"paths\": {\n \"src/*\": [\n \"src/*\"\n ]\n },\n /**\n * Typecheck JS in `.svelte` and `.js` files by default.\n * Disable checkJs if you'd like to use dynamic types in JS.\n * Note that setting allowJs false does not prevent the use\n * of JS in `.svelte` files.\n */\n \"allowJs\": true,\n \"checkJs\": true,\n \"isolatedModules\": true\n },\n \"include\": [\"src/*.ts\",\"src/**/*.d.ts\", \"src/**/*.ts\", \"src/**/*.js\", \"src/**/*.svelte\"],\n \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\nAnd `svelte.config.js` looks like this:\n\n```\nimport { vitePreprocess } from '@sveltejs/vite-plugin-svelte'\n\nexport default {\n // Consult https://svelte.dev/docs#compile-time-svelte-preprocess\n // for more information about preprocessors\n preprocess: vitePreprocess(),\n\n}\n```\n\n========================================\n\nCode:\n```text\nconst url = new URL(\"src/lib/Functions/CalculateRidge.ts\", import.meta.url);\nconst worker = new Worker(url, { type: 'module' })\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\nimport path from 'path';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n base: \"/solar-analysis-faroe-island/\",\n plugins: [svelte()],\n resolve: {\n alias: {\n src: path.resolve('src/'),\n }\n },\n})\n```\n\n```text\n{\n \"compilerOptions\": {\n \"composite\": true,\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Node\"\n },\n \"include\": [\"vite.config.ts\"]\n}\n```\n\n```text\n{\n \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n \"compilerOptions\": {\n \"baseUrl\": \".\",\n \"target\": \"ESNext\",\n \"useDefineForClassFields\": true,\n \"module\": \"ESNext\",\n \"resolveJsonModule\": true,\n \"paths\": {\n \"src/*\": [\n \"src/*\"\n ]\n },\n /**\n * Typecheck JS in `.svelte` and `.js` files by default.\n * Disable checkJs if you'd like to use dynamic types in JS.\n * Note that setting allowJs false does not prevent the use\n * of JS in `.svelte` files.\n */\n \"allowJs\": true,\n \"checkJs\": true,\n \"isolatedModules\": true\n },\n \"include\": [\"src/*.ts\",\"src/**/*.d.ts\", \"src/**/*.ts\", \"src/**/*.js\", \"src/**/*.svelte\"],\n \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n```\n\n```text\nimport { vitePreprocess } from '@sveltejs/vite-plugin-svelte'\n\nexport default {\n // Consult https://svelte.dev/docs#compile-time-svelte-preprocess\n // for more information about preprocessors\n preprocess: vitePreprocess(),\n\n}\n```\n\n```text\nvite.config.ts\n```\n\n```text\ntsconfig.node.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\nsvelte.config.js\n```\n\n```js\nimport workerUrl from \"src/lib/Functions/CalculateRidge?worker&url\";\nconst worker = new Worker(workerUrl, { type: 'module' })\n```\n\n```text\n?worker&url\n```\n\n========================================\n\nComments:\n- I tried importing the url as you specified, but now i get the following error when deploying: \"Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit: (vite:worker) transform \"project/location/solar-analysis-faroe-island/src/lib/Functi‌​ons/CalculateRidge.t‌​s?worker&url\"\". Your suggested change still works for development though. What could cause this error? And imports only work at the top-level of the code, right? Because i cannot place the import just above the const worker = ...\n- I have unfortunately never seen that error before. And yes, the import should be on the top level, in other places one may use a dynamic import but there is not really any point here as the import just provides a URL (i.e. the import itself does not load a large amount of data that might be worth lazy loading later).\n- Well that's no good... do you have any suggestions on how i could work around this error? I see one suggesting installing older versions of rollup, but that did not work for me...\n- Have you seen the SvelteKit issue referencing the linked Vite issue? Here is a suggested workaround, if that helps I would add that to the answer while the issue is resolved.\n- I'm sorry, i'm looking at my problem right now, and i see that i should had mentioned that i keep both the code that creates the worker and the worker itself inside the same script. The reason: so all worker-code is located in one file. I seperated the file, and i believe that solved the issue. But now a new issue regarding GeoTiff.js in build has emerged, i'll open a new issue.\n- New question: stackoverflow.com/questions/76051452/…","metadata":{"transformedAt":"2026-08-18T18:33:40.692Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":208,"estimatedTokens":1662}}455{"id":"stack-71728342","source":"stackoverflow","questionId":71728342,"title":"Creating SvelteKit library with reusable routes","tags":["svelte","sveltekit"],"text":"Title: Creating SvelteKit library with reusable routes\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'd like to create a SvelteKit library that provides a list of routes that the library user can then add to their Svelte app tree. This would be similar to some web frameworks, like reusable apps in Django.\n\n- Is creating reusable routes in the library currently possible with SvelteKit?\n\n- If it is possible are there any libraries that could be good examples to look upon?\n\n- If this is not possible then what's the next best alternative to provide easy route integrations to library users?\n\n========================================\n\nCode:\n```html\n<script context=\"module\">\n export * from \"your-lib/your-page.svelte\";\n import YourPage from \"your-lib/your-page.svelte\";\n</script>\n\n<YourPage />\n```\n\n```text\nconfig.kit.files.routes\n```\n\n```text\nRequestHandler\n```\n\n========================================\n\nComments:\n- Nice! Does the exported page include `load()` handling and so on, or does this need to be somehow exported separately?\n- `export * from \"your-lib/your-page.svelte\";` would mean `your-page.svelte`'s load function (if it exports one) gets treated as the load function for whichever page has that export statement. I hope that answers your question.","metadata":{"transformedAt":"2026-08-18T18:33:40.692Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":38,"estimatedTokens":322}}456{"id":"stack-72805846","source":"stackoverflow","questionId":72805846,"title":"Why does a derived Svelte store have different behaviour when using `$` vs `subscribe`","tags":["javascript","typescript","svelte","svelte-store"],"text":"Title: Why does a derived Svelte store have different behaviour when using `$` vs `subscribe`\nTags: javascript, typescript, svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI have a data model that I can't change in this project. I'm trying to strip down and simplify the sample code below, so hopefully this still makes sense with what I'm trying to re-produce.\n\nLet's say I have two stores. One store holds \"containers\" and the other store holds \"items\" - each store is independently used throughout the app for various purposes. The Container only holds Item IDs by default. Occasionally, I want to de-normalize the data for use on some pages. I use a derived store and denormalize each of the container objects, turning them into DenormalizedContainers.\n\nLet's say I have a use case where I want to create a new Item object, and then add it to a given Container. As far as I can tell, that will cause the derived store to update twice (once for the change to items and again for a change to containers), and thus anything that uses that derived store will update twice (depending on how it's called).\n\nWhy would the behaviour be different from `subscribe` to `$`?\n\nAlso, while this isn't a huge problem for me, I'm just curious if there is any native Svelte-y way to workaround this without changing the data model (while still being able to use the `subscribe` API?\n\n```\n\n import { derived, writable } from \"svelte/store\";\n\n type Container = {\n id: string;\n itemIds: string[];\n };\n\n type Item = {\n id: string;\n name: string;\n };\n\n type DenormalizedContainer = {\n id: string;\n items: Item[];\n };\n\n const containers = writable([]);\n const items = writable([]);\n\n const denormalizedContainers = derived(\n [containers, items],\n ([$containers, $items]): DenormalizedContainer[] => {\n return $containers.map(({ id, itemIds }) => {\n const denormalizedContainer = {\n id,\n items: itemIds.map((id) =>\n $items.find((item) => {\n item.id === id;\n })\n ),\n };\n return denormalizedContainer;\n });\n }\n );\n\n function handleAddContainer() {\n const value = Math.random() * 1000;\n const newContainer: Container = { id: `new-container-${value}`, itemIds: [] };\n containers.set([...$containers, newContainer]);\n }\n function handleAddItem() {\n const value = Math.random() * 1000;\n const newItem: Item = { id: `new-id-${value}`, name: `new-name-${value}` };\n items.set([...$items, newItem]);\n }\n function handleAddBoth() {\n const value = Math.random() * 1000;\n const newItem: Item = { id: `new-id-${value}`, name: `new-name-${value}` };\n const newContainer: Container = { id: `new-container-${value}`, itemIds: [newItem.id] };\n items.set([...$items, newItem]);\n containers.set([...$containers, newContainer]);\n }\n\n $: console.log(`$: There are ${$containers.length} containers`);\n $: console.log(`$: There are ${$items.length} items`);\n $: console.log(`$: There are ${$denormalizedContainers.length} denormalized containers`);\n\n denormalizedContainers.subscribe((newValue) =>\n console.log(\n `Subscribe: There are ${$denormalizedContainers.length} denormalized containers`\n )\n );\n\n handleAddContainer()}>Add container\n handleAddItem()}>Add item\n handleAddBoth()}>Add container and item\n```\n\n### Results:\n\nUpon clicking each button once, here are the logs:\n\nPage load:\n\n```\nSubscribe: There are 0 denormalized containers\n$: There are 0 containers\n$: There are 0 items\n$: There are 0 denormalized containers\n```\n\nAdd container:\n\n```\nSubscribe: There are 1 denormalized containers\n$: There are 1 containers\n$: There are 1 denormalized containers\n```\n\nAdd item:\n\n```\nSubscribe: There are 1 denormalized containers\n$: There are 1 items\n$: There are 1 denormalized containers\n```\n\nAdd both:\n\n```\nSubscribe: There are 1 denormalized containers\nSubscribe: There are 2 denormalized containers\n$: There are 2 containers\n$: There are 2 items\n$: There are 2 denormalized containers\n```\n\nThe updates handled via `$` are what I would like all the time, but for some reason the manual `subscribe` API shows two updates. I have a couple locations outside of `.svelte` files, where I would need to use the `subscribe` API.\n\n### References:\n\nSimilar to this, but doesn't explain why the `$` behaves differently to the `subscribe`.\n\nSvelte Derived Store atomic / debounced updates\n\nPossibly the underlying problem?\n\nhttps://github.com/sveltejs/svelte/issues/6730\n\nPossibly explained in 3.1/3.2 here. Micro-tasks bundle up reactive statements and apply them at the end of the tick. Whereas `subscribe` handles updates in real-time. Note: Wrapping my `subscribe` code in a `tick` just makes it run twice with the same data.\n\nhttps://dev.to/isaachagoel/svelte-reactivity-gotchas-solutions-if-you-re-using-svelte-in-production-you-should-read-this-3oj3\n\n========================================\n\nCode:\n```html\n<script lang=\"ts\">\n import { derived, writable } from \"svelte/store\";\n\n type Container = {\n id: string;\n itemIds: string[];\n };\n\n type Item = {\n id: string;\n name: string;\n };\n\n type DenormalizedContainer = {\n id: string;\n items: Item[];\n };\n\n const containers = writable<Container[]>([]);\n const items = writable<Item[]>([]);\n\n const denormalizedContainers = derived(\n [containers, items],\n ([$containers, $items]): DenormalizedContainer[] => {\n return $containers.map(({ id, itemIds }) => {\n const denormalizedContainer = {\n id,\n items: itemIds.map((id) =>\n $items.find((item) => {\n item.id === id;\n })\n ),\n };\n return denormalizedContainer;\n });\n }\n );\n\n function handleAddContainer() {\n const value = Math.random() * 1000;\n const newContainer: Container = { id: `new-container-${value}`, itemIds: [] };\n containers.set([...$containers, newContainer]);\n }\n function handleAddItem() {\n const value = Math.random() * 1000;\n const newItem: Item = { id: `new-id-${value}`, name: `new-name-${value}` };\n items.set([...$items, newItem]);\n }\n function handleAddBoth() {\n const value = Math.random() * 1000;\n const newItem: Item = { id: `new-id-${value}`, name: `new-name-${value}` };\n const newContainer: Container = { id: `new-container-${value}`, itemIds: [newItem.id] };\n items.set([...$items, newItem]);\n containers.set([...$containers, newContainer]);\n }\n\n $: console.log(`$: There are ${$containers.length} containers`);\n $: console.log(`$: There are ${$items.length} items`);\n $: console.log(`$: There are ${$denormalizedContainers.length} denormalized containers`);\n\n denormalizedContainers.subscribe((newValue) =>\n console.log(\n `Subscribe: There are ${$denormalizedContainers.length} denormalized containers`\n )\n );\n</script>\n\n<button class=\"block\" on:click={() => handleAddContainer()}>Add container</button>\n<button class=\"block\" on:click={() => handleAddItem()}>Add item</button>\n<button class=\"block\" on:click={() => handleAddBoth()}>Add container and item</button>\n```\n\n```text\nSubscribe: There are 0 denormalized containers\n$: There are 0 containers\n$: There are 0 items\n$: There are 0 denormalized containers\n```\n\n```text\nSubscribe: There are 1 denormalized containers\n$: There are 1 containers\n$: There are 1 denormalized containers\n```\n\n```text\nSubscribe: There are 1 denormalized containers\n$: There are 1 items\n$: There are 1 denormalized containers\n```\n\n```text\nSubscribe: There are 1 denormalized containers\nSubscribe: There are 2 denormalized containers\n$: There are 2 containers\n$: There are 2 items\n$: There are 2 denormalized containers\n```\n\n```text\nsubscribe\n```\n\n```text\n$\n```\n\n```text\nsubscribe\n```\n\n```text\n$\n```\n\n```text\nsubscribe\n```\n\n```text\n.svelte\n```\n\n```text\nsubscribe\n```\n\n```text\n$\n```\n\n```text\nsubscribe\n```\n\n```text\nsubscribe\n```\n\n```text\nsubscribe\n```\n\n```text\ntick\n```\n\n```js\n$$self.$$.update = () => {\n if ($$self.$$.dirty & /*$containers*/ 256) {\n $: console.log(`$: There are ${$containers.length} containers`);\n }\n\n if ($$self.$$.dirty & /*$items*/ 128) {\n $: console.log(`$: There are ${$items.length} items`);\n }\n\n if ($$self.$$.dirty & /*$denormalizedContainers*/ 64) {\n $: console.log(`$: There are ${$denormalizedContainers.length} denormalized containers`);\n }\n };\n```\n\n```js\nfunction debouncedSubscribe(store, callback) {\n let key;\n return store.subscribe(value => {\n key = {};\n const currentKey = key;\n queueMicrotask(() => {\n if (key == currentKey)\n callback(value);\n });\n });\n}\n\ndebouncedSubscribe(denormalizedContainers, value =>\n console.log(\n `Subscribe: There are ${value.length} denormalized containers`\n )\n);\n```\n\n```js\nfunction debouncedSubscribe(store, callback) {\n let timeout;\n return store.subscribe(value => {\n clearTimeout(timeout);\n timeout = setTimeout(() => callback(value));\n });\n}\n```\n\n```text\nupdate\n```\n\n```text\nsetTimeout\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.693Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":346,"estimatedTokens":2295}}457{"id":"stack-71433127","source":"stackoverflow","questionId":71433127,"title":"SvelteKit - Deployment - @sveltejs/adapter-static not updating static paths in fallback page","tags":["typescript","svelte","svelte-3","sveltekit","svelte-component"],"text":"Title: SvelteKit - Deployment - @sveltejs/adapter-static not updating static paths in fallback page\nTags: typescript, svelte, svelte-3, sveltekit, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI'm exploring SvelteKit for the first time, I built my simple first application and I'd like to deploy it to my Apache server as a static page\n\nAs far as I understood adapter-static is the way to go, so I installed it and changed my `svelte.config.js` file to this:\n\n\r\n\r\n\n```\nimport preprocess from 'svelte-preprocess';\nimport adapter from '@sveltejs/adapter-static';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n preprocess: preprocess(),\n\n kit: {\n adapter: adapter({\n paths: { base: \"/PERSONAL_PATH\" },\n fallback: 'index.html',\n precompress: false,\n })\n }\n};\n\nexport default config;\n```\n\n\r\n\r\n\r\n\n**Now:**\n\nThe `npm run build` runs without any error, the thing is that when I check `index.html` all the dependencies of the page *(or the URLs of stylesheets and JS files if you will...)* have 2 problems as you can see below:\n\n- Have an absolute path, which makes it impossible to move the page's sources to any other location\n\n- Are not located in the folder `PERSONAL_PATH` where I'd like them to be\n\n\r\n\r\n\n```\n\n \n \n \n \n \n \n \n \n \n \n \n \n import { start } from \"/_app/start-25574c6c.js\";\n start({\n target: document.querySelector('[data-hydrate=\"45h\"]').parentNode,\n paths: {\"base\":\"\",\"assets\":\"\"},\n session: {},\n route: true,\n spa: true,\n trailing_slash: \"never\",\n hydrate: null\n });\n \n \n\n```\n\n\r\n\r\n\r\n\nWhere am I getting it wrong? I've been trying to figure it out for hours but I'm stuck now.\n\n========================================\n\nCode:\n```js\nimport preprocess from 'svelte-preprocess';\nimport adapter from '@sveltejs/adapter-static';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n preprocess: preprocess(),\n\n kit: {\n adapter: adapter({\n paths: { base: \"/PERSONAL_PATH\" },\n fallback: 'index.html',\n precompress: false,\n })\n }\n};\n\nexport default config;\n```\n\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"description\" content=\"\" />\n <link rel=\"icon\" href=\"./favicon.png\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <meta http-equiv=\"content-security-policy\" content=\"\">\n <link rel=\"modulepreload\" href=\"/_app/start-25574c6c.js\">\n <link rel=\"modulepreload\" href=\"/_app/chunks/vendor-868763d8.js\">\n </head>\n <body>\n <div>\n <script type=\"module\" data-hydrate=\"45h\">\n import { start } from \"/_app/start-25574c6c.js\";\n start({\n target: document.querySelector('[data-hydrate=\"45h\"]').parentNode,\n paths: {\"base\":\"\",\"assets\":\"\"},\n session: {},\n route: true,\n spa: true,\n trailing_slash: \"never\",\n hydrate: null\n });\n </script></div>\n </body>\n</html>\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nnpm run build\n```\n\n```text\nindex.html\n```\n\n```text\nPERSONAL_PATH\n```\n\n```js\nimport preprocess from 'svelte-preprocess';\n import adapter from '@sveltejs/adapter-static';\n\n /** @type {import('@sveltejs/kit').Config} */\n const config = {\n preprocess: preprocess(),\n\n kit: {\n // SET THE PATHS HERE\n paths: { assets: \"\", base: \"/PERSONAL_PATH\" },\n adapter: adapter({\n // NOT HERE!\n // paths: { base: \"/PERSONAL_PATH\" },\n fallback: 'index.html',\n precompress: false,\n })\n }\n };\n\n export default config;\n```\n\n```text\nsvelte.config.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.693Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":177,"estimatedTokens":923}}458{"id":"stack-64862161","source":"stackoverflow","questionId":64862161,"title":"Svelte store function update","tags":["javascript","svelte","svelte-3","svelte-store"],"text":"Title: Svelte store function update\nTags: javascript, svelte, svelte-3, svelte-store\nSource: Stack Overflow\n\nQuestion:\nSvelte store documentation shows String or Integer being updated, but I did not find any dynamic function in store.\n\nI don't understand how to make the `getData` function as a writable in order to notify the html of the change.\n\nIn the following sample, I would like `b` to be shown after the `updateKey` function is called.\n\nYou will find a minimal code in REPL here: https://svelte.dev/repl/3c86bd48d5b5428daee514765c926e58?version=3.29.7\n\nAnd the same code here in case REPL would be down:\n\nApp.svelte:\n\n```\n\nimport { getData } from './store.js';\nimport { updateKey } from './store.js';\nsetTimeout(updateKey, 1000);\n\n### {getData()}!\n\n```\n\nstore.js\n\n```\nimport {setContext} from 'svelte';\nimport {writable} from 'svelte/store';\n\nvar data = {\n 'a': 'a',\n 'b': 'b'\n};\n\nvar key = 'a';\n\nexport const getData = function() {\n return data[key];\n}\n\nexport const updateKey = () => {\n key = 'b';\n}\n```\n\nThe goal is to work with a dynamic function in the store.\n\n========================================\n\nTop Answer:\nif I understood your question correctly, you want to be able to change the function (logic) that is executed by `getData()` and you want on each function change the html to be updated\n\nfor this use case you'll need to create your own custom store\n\nas follows in `store.js`\n\n```\nimport { writable } from 'svelte/store';\n// an object to hold our functions\nconst functions = {\n \"funcA\": () => {\n // do something\n return \"whatevedata for a\"\n },\n \"funcB\": () => {\n // do something\n return \"the data of b\"\n }\n }\n\n// this how to create a custom store, taken from svelte documentation\nfunction createCustomStore(defaultValue) {\n const { subscribe, set, update } = writable(defaultValue);\n return {\n subscribe,\n //custom function change func where suppliedValue the value you input to the store\n // set() is a default function for a store to change it's value\n changeFunc: (suppliedValue) => set(functions[suppliedValue]),\n reset: () => set(defaultValue)\n };\n}\n\nexport const getData = createCustomStore(() => \"default\");\n\nexport const updateKey = () => {\n // this to update which function the store uses\n getData.changeFunc(\"funcB\")\n}\n```\n\nin App.svelte\n\n```\n\n \n import { getData } from './store.js';\n import { updateKey } from './store.js';\n \n setTimeout(function() {\n updateKey()\n }, 1000);\n \n\n### {$getData()}\n\n```\n\nwe added the `$` to `getData` because it's a store that holds reference to functions and the `()` is there to execute any function referenced by `getData` store. since it is a store on each value change (function change) of `getData`, the html will be updated\n\nhere is a repl of the implementation\n\n========================================\n\nCode:\n```text\n<script>\nimport { getData } from './store.js';\nimport { updateKey } from './store.js';\nsetTimeout(updateKey, 1000);\n</script>\n\n<h1>{getData()}!</h1>\n```\n\n```text\nimport {setContext} from 'svelte';\nimport {writable} from 'svelte/store';\n\nvar data = {\n 'a': 'a',\n 'b': 'b'\n};\n\nvar key = 'a';\n\nexport const getData = function() {\n return data[key];\n}\n\nexport const updateKey = () => {\n key = 'b';\n}\n```\n\n```text\ngetData\n```\n\n```text\nb\n```\n\n```text\nupdateKey\n```\n\n```html\n<script>\n import { onMount } from 'svelte'\n import { key, data, updateKey } from './store.js'\n\n onMount(() => {\n // it's not safe to have an unchecked timer running -- problems would\n // occur if the component is destroyed before the timeout has ellapsed,\n // that's why we're using the `onMount` lifecycle function and its\n // cleanup function here\n const timeout = setTimeout(updateKey, 1000);\n \n // this cleanup function is called when the component is destroyed\n return () => {\n clearTimeout(timeout)\n }\n })\n\n // this will log the value of the `key` store each time it changes, using\n // a reactive expression (a Sveltism)\n $: console.log($key)\n</script>\n\n<!--\n NOTE: we're using the $ prefix notation to access _the value_ of the store,\n and not `data`, which would be _the store itself_ (an object with\n subscribe, set, etc.)\n -->\n<h1>{$data}</h1>\n```\n\n```js\nimport { writable, derived } from 'svelte/store'\n\nconst db = {\n 'a': 'a',\n 'b': 'b'\n}\n\n// a writable store with initial value 'a'\nexport const key = writable('a')\n\nexport const updateKey = () => {\n // a writable store has a `set` method to change its value\n key.set('b')\n}\n\n// you can use a derived store to compute derived values from\n// the current value of other stores\n//\n// here, we're getting the value from the db when the value of\n// the `key` store changes\nexport const data = derived([key], ([$key]) => db[$key])\n```\n\n```text\nApp.svelte\n```\n\n```text\nstore.js\n```\n\n```text\nimport { writable } from 'svelte/store';\n// an object to hold our functions\nconst functions = {\n \"funcA\": () => {\n // do something\n return \"whatevedata for a\"\n },\n \"funcB\": () => {\n // do something\n return \"the data of b\"\n }\n }\n\n// this how to create a custom store, taken from svelte documentation\nfunction createCustomStore(defaultValue) {\n const { subscribe, set, update } = writable(defaultValue);\n return {\n subscribe,\n //custom function change func where suppliedValue the value you input to the store\n // set() is a default function for a store to change it's value\n changeFunc: (suppliedValue) => set(functions[suppliedValue]),\n reset: () => set(defaultValue)\n };\n}\n\nexport const getData = createCustomStore(() => \"default\");\n\n\nexport const updateKey = () => {\n // this to update which function the store uses\n getData.changeFunc(\"funcB\")\n}\n```\n\n```text\n<script>\n \n import { getData } from './store.js';\n import { updateKey } from './store.js';\n \n setTimeout(function() {\n updateKey()\n }, 1000);\n \n\n</script>\n\n<h1>{$getData()}</h1>\n```\n\n```text\ngetData()\n```\n\n```text\nstore.js\n```\n\n```text\n$\n```\n\n```text\ngetData\n```\n\n```text\n()\n```\n\n```text\ngetData\n```\n\n```text\ngetData\n```\n\n========================================\n\nComments:\n- Thank you for this answer. This does exactly what I had in mind with great comments. I will take a moment to understand the derived behavior.\n- I updated the REPL : svelte.dev/repl/3c86bd48d5b5428daee514765c926e58?version=3.2‌​9.7 The core question was to pass the parameter in the store function. Is that possible ?\n- No this is not directly possible -- function calls are never reactive. What you can do is call your function in a reactive expression when the lang value changes. But IMO this function call is really trying to force some procedural style where a more functional approach would be far more natural for Svelte, and probably less bug prone in the end. For this, your function call would become changing the value of a `key` writable store, and the result would come from a derived store. Updated REPL to illustrate both approaches: svelte.dev/repl/7633dfdc70bb4eee80d0a87e4bd1a631?version=3.2‌​9.7\n- Thank you again for the second sample. I think I may try to use the store as a something it is not like you are saying. Maybe i'm missing the point of the store / reactive behaviour, got to work on this. Thanks","metadata":{"transformedAt":"2026-08-18T18:33:40.693Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":309,"estimatedTokens":1848}}459{"id":"stack-75967405","source":"stackoverflow","questionId":75967405,"title":"How to pass in parameters from client side to server side code in Sveltekit?","tags":["javascript","svelte","server-side-rendering","sveltekit","supabase"],"text":"Title: How to pass in parameters from client side to server side code in Sveltekit?\nTags: javascript, svelte, server-side-rendering, sveltekit, supabase\nSource: Stack Overflow\n\nQuestion:\nI've been trying to run a query to a Supabase database that needs a dog breed passed through and will return metrics about it, the breed is defined on the client side. I was able to get the server side query to run but the value is not going through.\n\n```\n+page.svelte\n\nexport let metrics;\n export let data;\n\n const getAllDogs = async () => {\n const { metrics: data } = load({ dog: dog_val });\n metrics = data;\n };\n \n onMount(async () => {\n getAllDogs();\n })\n\n+page.server.js\n\nimport supabase from \"../../lib/db\";\n\n//Method to get all dog breeds\nexport const load = async ({dog}) => {\n const getAllMetrics = async () => {\n try {\n let { data, error } = await supabase\n .from(\"dogs\")\n .select(\n \"avg_size, avg_obedience, avg_compassion, avg_health, avg_cleanliness, avg_energy\"\n )\n .eq(\"Breed\", dog);\n console.log(data)\n console.log(dog)\n return data;\n } catch (e) {\n console.error(e);\n }\n };\n return {\n metrics: getAllMetrics(dog)\n }\n};\n```\n\n========================================\n\nTop Answer:\nThe modern SvelteKit offers some shorthand methods for doing HTTP POST API requests. Depending on the use case use HTTP POST if you are mutating the state on the server, HTTP GET if the request is idempotent query.\n\nIn your `+page.svelte.js`:\n\n```\nlet error = \"\"; // Render error text in page template if something happens\n\n // Example function that calls a server-side API from SvelteKit UI code,\n // e.g. on:click handler\n async function myDoSomething(myData) {\n \n const body = {\n param1: myData.something,\n param2: myData.somethingElse,\n };\n\n try {\n // https://stackoverflow.com/a/46640744/315168\n console.log(\"Server-side POST for update\", body);\n const resp = await fetch(\n \"/api/update-something\", \n {\n method: \"POST\", \n body: JSON.stringify(body),\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }\n }\n );\n\n if(resp.status != 200) {\n error = await resp.text()\n console.log(\"Server error\", error);\n throw new Error(`Server problem: ${resp.status} ${resp.statusText}`);\n }\n replyData = await resp.json();\n console.log(\"Got data\", replyData); \n } catch(e) {\n error = e.toString();\n console.log(e);\n } \n }\n```\n\nThen in `src/routes/api/update-something/+server.js`:\n\n```\nimport { json } from '@sveltejs/kit';\n\nexport async function POST({ request, cookies }) {\n\n const params = await request.json();\n console.log(\"JSON post params are\", params);\n\n return json({foo: 1, bar: 2}); // Send reply to the client\n}\n```\n\n========================================\n\nCode:\n```text\n+page.svelte\n\nexport let metrics;\n export let data;\n\n const getAllDogs = async () => {\n const { metrics: data } = load({ dog: dog_val });\n metrics = data;\n };\n \n onMount(async () => {\n getAllDogs();\n })\n\n\n+page.server.js\n\nimport supabase from \"../../lib/db\";\n\n//Method to get all dog breeds\nexport const load = async ({dog}) => {\n const getAllMetrics = async () => {\n try {\n let { data, error } = await supabase\n .from(\"dogs\")\n .select(\n \"avg_size, avg_obedience, avg_compassion, avg_health, avg_cleanliness, avg_energy\"\n )\n .eq(\"Breed\", dog);\n console.log(data)\n console.log(dog)\n return data;\n } catch (e) {\n console.error(e);\n }\n };\n return {\n metrics: getAllMetrics(dog)\n }\n};\n```\n\n```text\n+page.svelte\n //set empty array for dogs if getting array\n let dogs = []\n //set param somehow for breedToSearch\n let breedToSearch = \"lab\"\n\n async function getAllDogs {\n\n const response = await fetch('/api/dogs?dog=${breedToSearch}', {\n method: 'GET',\n });\n let newData = await response.json();\n dogs = newData.message;\n\n \n onMount(async () => {\n getAllDogs();\n })\n\n\n}\n\n+server.js (in the src-api-dogs directory)\n/** @type {import('./$types').RequestHandler} */\nexport async function GET({ url }) {\n//get the dog param sent in the fetch call\nconst dog = url.searchParams.get('dog')\n\nconst dogsFromDB = -----call to database----\n\nreturn new Response(JSON.stringify({ message: dogsFromDB }), { status: 200 })\n}\n```\n\n```js\nlet error = \"\"; // Render error text in page template if something happens\n\n // Example function that calls a server-side API from SvelteKit UI code,\n // e.g. on:click handler\n async function myDoSomething(myData) {\n \n const body = {\n param1: myData.something,\n param2: myData.somethingElse,\n };\n\n try {\n // https://stackoverflow.com/a/46640744/315168\n console.log(\"Server-side POST for update\", body);\n const resp = await fetch(\n \"/api/update-something\", \n {\n method: \"POST\", \n body: JSON.stringify(body),\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }\n }\n );\n\n if(resp.status != 200) {\n error = await resp.text()\n console.log(\"Server error\", error);\n throw new Error(`Server problem: ${resp.status} ${resp.statusText}`);\n }\n replyData = await resp.json();\n console.log(\"Got data\", replyData); \n } catch(e) {\n error = e.toString();\n console.log(e);\n } \n }\n```\n\n```js\nimport { json } from '@sveltejs/kit';\n\nexport async function POST({ request, cookies }) {\n\n const params = await request.json();\n console.log(\"JSON post params are\", params);\n\n return json({foo: 1, bar: 2}); // Send reply to the client\n}\n```\n\n```text\n+page.svelte.js\n```\n\n```text\nsrc/routes/api/update-something/+server.js\n```\n\n========================================\n\nComments:\n- That is not how any of this works, you can't just make up `load` parameters, nor is that function called explicitly. Please read the docs on loading data,\n- On the client-side it's better to use an ordinary `` to send the HTTP request to the server, instead of calling `fetch()`. This way, not only will you end up with more readable code with better semantics, but the code will also work for users that have client-side JS disabled in their web browser.\n- Ah yes Peppe you are correct. This is for cases you need to trigger POST that is not originated from a form.","metadata":{"transformedAt":"2026-08-18T18:33:40.693Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":259,"estimatedTokens":1577}}460{"id":"stack-62567071","source":"stackoverflow","questionId":62567071,"title":"Bind to `onbeforeunload`","tags":["svelte","svelte-3"],"text":"Title: Bind to `onbeforeunload`\nTags: svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI was hoping to bind to `` but have no luck.\n\n```\n\n true} />\n\n true} />\n\n true} />\n```\n\nin all instances, `window.onbeforeunload` is `null`\n\nI ended up just going with `window.onbeforeunload = () => true` but was wondering why setting on the element didn't work.\n\n========================================\n\nCode:\n```html\n<!-- doesn't work -->\n<svelte:window on:beforeunload={() => true} />\n\n<!-- doesn't work -->\n<svelte:window on:onbeforeunload={() => true} />\n\n<!-- doesn't work -->\n<svelte:window on:beforeUnload={() => true} />\n```\n\n```text\n<svelte:window>\n```\n\n```text\nwindow.onbeforeunload\n```\n\n```text\nnull\n```\n\n```text\nwindow.onbeforeunload = () => true\n```\n\n```text\n<script>\n\n function beforeUnload() {\n // Cancel the event as stated by the standard.\n event.preventDefault();\n // Chrome requires returnValue to be set.\n event.returnValue = '';\n // more compatibility\n return '...';\n }\n\n</script>\n\n<svelte:window on:beforeunload={beforeUnload}/>\n```\n\n```text\nreturnValue\n```\n\n```text\nsvelte:window\n```\n\n```text\non:event={handler}\n```\n\n```text\nnode.addEventListener(event, handler, options)\n```\n\n```text\nbeforeunload\n```\n\n```text\naddEventListener\n```\n\n```text\nreturnValue\n```\n\n```text\nwindow.onbeforeunload\n```\n\n========================================\n\nComments:\n- In my case I just needed a `on:beforeunload|preventDefault`.","metadata":{"transformedAt":"2026-08-18T18:33:40.693Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":103,"estimatedTokens":361}}461{"id":"stack-71789793","source":"stackoverflow","questionId":71789793,"title":"how to handle reset layout?","tags":["svelte","sveltekit"],"text":"Title: how to handle reset layout?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm now getting this error:\n\n__layout.reset has been removed in favour of named layouts: https://kit.svelte.dev/docs/layouts#named-layouts\n\nI have a sub-directory for which I do not want to inherit the base layout.\n\n```\n$ find . -name '*layout*' \n./setup-profile/__layout.reset.svelte\n./auth/__layout.reset.svelte\n./__layout.svelte\n```\n\npackage.json has\n\n```\n\"@sveltejs/kit\": \"next\",\n```\n\n========================================\n\nTop Answer:\nThe doc page you linked is pretty self-explanatory.\n\n**Edit:**\n\nOverall the simpler way is to create a named reset layout at the root of your source tree containing a simple ``, and reference that layout whenever you want to start from a reset layout:\n\n```\nsrc/routes/\n├ auth/\n│ ├ __layout@reset.svelte (will inherit from the reset layout)\n│ ├ pageA.svelte\n│ └ pageB.svelte\n├ setup-profile/\n│ ├ __layout@reset.svelte (will inherit from the reset layout)\n│ ├ pageA.svelte\n│ └ pageB.svelte\n├ no-reset/\n│ ├ __layout.svelte (will inherit from the base layout)\n│ ├ pageA.svelte\n│ └ pageB.svelte\n├ __layout.svelte\n└ __layout-reset.svelte\n```\n\n========================================\n\nCode:\n```text\n$ find . -name '*layout*' \n./setup-profile/__layout.reset.svelte\n./auth/__layout.reset.svelte\n./__layout.svelte\n```\n\n```text\n\"@sveltejs/kit\": \"next\",\n```\n\n```bash\nsrc/routes\n├── (app)\n│ ├── +layout.svelte ----> contains Header, Main, Footer etc.\n│ ├── page1\n│ │ └── +page.svelte\n│ ├── page2\n│ │ └── +page.svelte\n│ ├── page3\n│ │ └── +page.svelte\n├── (popup)\n| ├── +layout.svelte ----> contains only popup HTML & styles\n│ ├── popup\n│ └── popup1\n│ │ └── +page.svelte\n│ └── popup2\n│ └── +page.svelte\n├── (test)\n│ ├── +layout.svelte\n│ └── test\n│ ├── +layout.svelte\n│ └── page.svelte\n├── +error.svelte\n├── +layout.svelte ----> contains nothing or only global things\n├── +page.svelte\n└── api\n ├── user\n │ └── [uid]\n │ └── get.json\n └── ...\n...\n```\n\n```text\n+page.svelte\n```\n\n```text\nz-index\n```\n\n```text\n<slot />\n```\n\n```text\n(app)\n```\n\n```text\n(popup)\n```\n\n```text\nsrc/routes/\n├ auth/\n│ ├ __layout@reset.svelte (will inherit from the reset layout)\n│ ├ pageA.svelte\n│ └ pageB.svelte\n├ setup-profile/\n│ ├ __layout@reset.svelte (will inherit from the reset layout)\n│ ├ pageA.svelte\n│ └ pageB.svelte\n├ no-reset/\n│ ├ __layout.svelte (will inherit from the base layout)\n│ ├ pageA.svelte\n│ └ pageB.svelte\n├ __layout.svelte\n└ __layout-reset.svelte\n```\n\n```text\n<slot />\n```\n\n```text\nl2_named/\n __layout-foo.svelte\n level_2_named@foo.svelte\n```\n\n```text\n-foo\n```\n\n```text\n@foo\n```\n\n========================================\n\nComments:\n- `> Files and directories prefixed with __ are reserved (saw src/routes/__layout-reset.svelte)`\n- had to remove `package-lock.json` and `node_modules`\n- This explanation helps exactly the behaviour I am seeing, so thanks. The confusion is that the docs say: \"Ordinarily, this would inherit the root layout, the (app) layout, the item layout and the [id] layout. We can reset to one of those layouts by appending @ followed by the segment name\" which to me reads the opposite behaviour kit.svelte.dev/docs/…\n- @aroundtheworld glad I could help a bit, but keep in mind my answer above is obsolete if you are using more recent versions of SvelteKit where routing conventions have been updated! However if you have a specific question or need regarding the use of layouts I'd be able to assist if I can.\n- thanks @ThomasHennes, i am using svelte 3.5.4 - using groups, noticing that routes/(app)>layout.svelte is taken by every child +page. As the docs read, it sounded like using the +page@[id].svelte meant the root or (app) layout was not taken (ie, 'reset') but actually as it is described in your post still holds, as far as I can see\n- This was useful and helped a lot.","metadata":{"transformedAt":"2026-08-18T18:33:40.693Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":163,"estimatedTokens":987}}462{"id":"stack-71622971","source":"stackoverflow","questionId":71622971,"title":"svelte: how can I declare two cyclically reactive variables?","tags":["javascript","svelte","svelte-3","sveltekit"],"text":"Title: svelte: how can I declare two cyclically reactive variables?\nTags: javascript, svelte, svelte-3, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have two variables `a` and `b` which add up to 100. How do I set up a reactive declaration such that when `a` changes `b` changes to be `100 - a` and vice versa? When I try something like\n\n```\nlet total = 100;\n$: a = total - b;\n$: b = total - a;\n```\n\nI get a 'Cyclical dependency detected' error. Is there any way to get this done?\n\n========================================\n\nTop Answer:\nThat does not work; Svelte does not allow this and this cycle cannot be resolved either. If you want a variable to be editable, you cannot declare it as reactive (`$: x = ...`). You can either reactively set regular variables with reactive statements/blocks or use events instead (see other answers).\n\n*The following is an explanation why this could not be resolved logically either.*\n\nTreating this like two equations with two unknowns you get this useless simplification:\n\n```\na = total - b\nb = total - a\nb = total - (total - b)\nb = total - total + b\nb = b\n```\n\nYou have to fix at least one of the values, otherwise all possible values are valid here.\n\nYou can also first normalize the equations:\n\n```\na = total - b => a + b = total => a + b = total\nb = total - a => b + a = total => a + b = total\n```\n\nAs you can see, they are the same, so you actually have two unknowns and only one equation, so this is underspecified.\n\n*(Note that even if this would yield a valid solution, Svelte cannot solve systems of linear equations for you.)*\n\n========================================\n\nCode:\n```text\nlet total = 100;\n$: a = total - b;\n$: b = total - a;\n```\n\n```text\na\n```\n\n```text\nb\n```\n\n```text\na\n```\n\n```text\nb\n```\n\n```text\n100 - a\n```\n\n```html\n<script>\n let total = 100;\n let a = 0\n let b = 0\n \n const setA = () => {\n // the assignment to a (or b in the other function) are still\n // reactive, of course, but Svelte won't propagate changes to\n // variable that are assigned their current value, so this\n // will break the loop\n a = total - b\n }\n \n const setB = () => {\n b = total - a\n }\n \n $: setA(total - b);\n $: setB(total - a);\n</script>\n\n<pre>\n a: {a}\n b: {b}\n</pre>\n\n<label>\n a <input type=\"number\" bind:value={a} />\n</label>\n\n<label>\n b <input type=\"number\" bind:value={b} />\n</label>\n```\n\n```js\n// this function is just normal\nconst setA = (value) => {\n a = value\n}\n\n// this reactive expression makes it obvious and straightforward that \n// its dependencies are total and b, and only those\n$: setA(total - b)\n```\n\n```js\nconst recomputeEverythingOrWhatever = () => {\n ...\n}\n\n// in Svelte lingo, this is broadly understood as \"whenever a, or b, or\n// total changes, then recompute everything (or whatever)\"\n$: a, b, total, recomputeEverythingOrWhatever()\n```\n\n```text\na\n```\n\n```text\nb\n```\n\n```text\na = total - b\nb = total - a\nb = total - (total - b)\nb = total - total + b\nb = b\n```\n\n```text\na = total - b => a + b = total => a + b = total\nb = total - a => b + a = total => a + b = total\n```\n\n```text\n$: x = ...\n```\n\n```html\n<script>\n const total = 100;\n let a = total;\n let b = 0;\n</script>\n\na: {a} <br>\nb: {b}\n\n<label>\n a <input type=\"number\" bind:value={a}\n on:input={() => b = total - a} />\n</label>\n\n<label>\n b <input type=\"number\" bind:value={b}\n on:input={() => a = total - b} />\n</label>\n```\n\n========================================\n\nComments:\n- I don't know, this feels kinda like an abuse of the reactive system. It took me a while to understand how this works, since `setA` and `setB` don't take any parameters, and yet you're supplying arguments when you call them in the reactive `$` blocks. You have them there since you want the reactive blocks to trigger, but actually the equation inside the reactive block is arbitrary. This would still work correctly even if you changed the first `$:` to: `$: setA(total + b);`. Or any expression that contains both total and b, really. Basically, you're using `setA` and `setB` as side effects.\n- You're right. I'm not sure I'd call it an abuse but the code in example is poorly written. I was focused on demonstrating what was reactive where. I have edited the answer to add a disclaimer about real world usage.\n- That's pretty cool, thanks for the quick edit!","metadata":{"transformedAt":"2026-08-18T18:33:40.693Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":183,"estimatedTokens":1094}}463{"id":"stack-59111833","source":"stackoverflow","questionId":59111833,"title":"How can I host a Svelte app in a subdirectory?","tags":["hosting","svelte"],"text":"Title: How can I host a Svelte app in a subdirectory?\nTags: hosting, svelte\nSource: Stack Overflow\n\nQuestion:\nHow can I host an exported Svelte project in a subdirectory on my domain? Imagine that example.com is my domain, how can I have *src\\routes\\index.svelte* correspond to *https://example.com/subdir/*?\n\nWhen I upload the Svelte export to this subdirectory of the web server, it reads from the console that it cannot find *https://example.com/service-worker.js* among other files, which is true, because it's in the */subdir* folder. But where can I set the base URL?\n\n========================================\n\nCode:\n```js\n// app/server.js\n\nexpress() // or Polka, or a similar framework\n .use(\n '/subdir', // <-- add this line\n compression({ threshold: 0 }),\n serve('static'),\n sapper.middleware()\n )\n .listen(process.env.PORT);\n```\n\n```text\nsrc/server.js\n```\n\n```text\n--basepath\n```\n\n```text\nsapper export\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.693Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":36,"estimatedTokens":239}}464{"id":"stack-68404931","source":"stackoverflow","questionId":68404931,"title":"Check TypeScript types in Svelte files from command line","tags":["typescript","svelte"],"text":"Title: Check TypeScript types in Svelte files from command line\nTags: typescript, svelte\nSource: Stack Overflow\n\nQuestion:\nI run `tsc --noemit` to ensure the are no type errors in the codebase. Unfortunately, it does not seem to check .svelte files.\n\nIs there a way to make it work? I can see the type errors in .svelte files open in VS Code, so I think it has to be possible somehow with existing tooling.\n\nAlso I'm using the official @rollup/plugin-typescript I'm aware there is also rollup-plugin-typescript2 which checks types on build and may be an alternative solution, but I prefer to not enforce types on build and check types separately as I currently do.\n\n========================================\n\nCode:\n```text\ntsc --noemit\n```\n\n```text\nsvelte-check\n```\n\n```text\ntsc --noemit\n```\n\n```text\nsvelte-check\n```\n\n```text\nsvelte-check --tsconfig ./path/to/your/tsconfig.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\nsvelte-check --tsconfig ./tsconfig.json\n```\n\n```text\nsvelte-check\n```\n\n```text\nscript\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/…\n- Also you may want to add `--threshold=error` or `--threshold=warning` to ignore linting-level hints and only get the type errors.\n- @dummdidumm, `svelte-check --tsconfig ./tsconfig.json` doesn't respect tsconfig.json excludes array.","metadata":{"transformedAt":"2026-08-18T18:33:40.693Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":60,"estimatedTokens":349}}465{"id":"stack-56065845","source":"stackoverflow","questionId":56065845,"title":"How to do graphql and graphql subscriptions with svelte","tags":["graphql","svelte"],"text":"Title: How to do graphql and graphql subscriptions with svelte\nTags: graphql, svelte\nSource: Stack Overflow\n\nQuestion:\nTo do graphql queries and mutations ive had success with both fetch and svelte-apollo (see https://github.com/timhall/svelte-apollo)\n\nI like the fech approach for its simplicity. \n\nSvelte-apollo features subscriptions and I will try to get it to work.\n\nBut are there alternatives?\n\nHow do you consume graphql subscriptions with svelte?\n\n========================================\n\nTop Answer:\nI'm using urql's svelte bindings. The documentation also shows how to use the bindings with subscriptions.\n\n========================================\n\nCode:\n```text\nimport { ApolloClient } from 'apollo-client';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport { HttpLink } from 'apollo-link-http';\nimport { WebSocketLink } from 'apollo-link-ws';\nimport { split } from 'apollo-link';\nimport { getMainDefinition } from 'apollo-utilities';\n\nconst httpLink = new HttpLink({\n uri: 'http://localhost:3000/graphql'\n});\nconst wsLink = new WebSocketLink({\n uri: `ws://localhost:3000/subscriptions`,\n options: {\n reconnect: true\n }\n});\n\n\nconst link = split(\n // split based on operation type\n ({ query }) => {\n const definition = getMainDefinition(query);\n return (\n definition.kind === 'OperationDefinition' &&\n definition.operation === 'subscription'\n );\n },\n wsLink,\n httpLink,\n);\n\nconst client = new ApolloClient({\n link,\n cache: new InMemoryCache()\n});\n```\n\n```text\nimport gql from 'graphql-tag';\n\nclient.subscribe({\n query: gql`subscription { whatever }`\n}).subscribe(result => console.log(result.data);\n```\n\n========================================\n\nComments:\n- I'm also looking for the same suggestion. Any news?\n- Nice you can do this even without sapper. It's been almost a year since you posted this solution. Would would you write the same solution today?\n- the example on the website doesn't work. do you have a working example?","metadata":{"transformedAt":"2026-08-18T18:33:40.693Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":75,"estimatedTokens":497}}466{"id":"stack-50102627","source":"stackoverflow","questionId":50102627,"title":"How to import and render components dynamically in Svelte/Sapper?","tags":["svelte"],"text":"Title: How to import and render components dynamically in Svelte/Sapper?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI have a component (`IconInline.html`), within which I would like to import and render components dynamically based on a prop (`IconID`) passed to it.\n\nCurrently I do it manually like this:\n\n\r\n\r\n\n```\n{{#if IconID === \"A\"}}\r\n \r\n{{elseif IconID === \"B\"}}\r\n \r\n{{elseif IconID === \"C\"}}\r\n \r\n{{elseif IconID === \"D\"}}\r\n \r\n{{/if}}\r\n\r\n\r\n import A from \"./icons/A.html\";\r\n import B from \"./icons/B.html\";\r\n import C from \"./icons/C.html\";\r\n import D from \"./icons/D.html\";\r\n\r\n export default {\r\n components: { A, B, C, D }\r\n };\r\n\n```\n\n\r\n\r\n\r\n\nIs there a way to\n\n- Import all components in a given directory dynamically?\n\n- Render a specific component that matches a given prop?\n\n========================================\n\nCode:\n```html\n{{#if IconID === \"A\"}}\n <A />\n{{elseif IconID === \"B\"}}\n <B />\n{{elseif IconID === \"C\"}}\n <C />\n{{elseif IconID === \"D\"}}\n <D />\n{{/if}}\n\n<script>\n import A from \"./icons/A.html\";\n import B from \"./icons/B.html\";\n import C from \"./icons/C.html\";\n import D from \"./icons/D.html\";\n\n export default {\n components: { A, B, C, D }\n };\n</script>\n```\n\n```text\nIconInline.html\n```\n\n```text\nIconID\n```\n\n```html\n<svelte:component this={cmp} foo=\"bar\" baz=\"bop\">\n <!-- contents go here -->\n</svelte:component>\n\n<script>\n import A from \"./icons/A.html\";\n import B from \"./icons/B.html\";\n import C from \"./icons/C.html\";\n import D from \"./icons/D.html\";\n\n const components = { A, B, C, D };\n\n export default {\n computed: {\n cmp: ({ IconID }) => components[IconID]\n }\n };\n</script>\n```\n\n```html\n<A foo=\"bar\" baz=\"bop\">\n <!-- contents go here -->\n</A>\n```\n\n```text\n<svelte:component>\n```\n\n```text\nIconID\n```\n\n```text\n\"A\"\n```\n\n========================================\n\nComments:\n- Thank you! Much appreciated.\n- However, when replicating your example I get an error: `Module build failed: Error: ValidationError: Computed properties cannot use destructuring in function parameters`. Pointing to the curly brackets in the `cmp` function.\n- I now realize that I'm on version 1. Could this be the problem?\n- Changing it to `` syntax made it work. Thanks again.\n- Ah yep, it changed in v2. I definitely recommend upgrading as soon as you can :) You just need to do `npx svelte-upgrade v2 routes` — full migration guide here, upgrade tool here\n- @rich-harris - How do you do this with version 3?\n- `$: cmp = components[IconID];`","metadata":{"transformedAt":"2026-08-18T18:33:40.693Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":128,"estimatedTokens":628}}467{"id":"stack-78774621","source":"stackoverflow","questionId":78774621,"title":"Why does the following event handler work in a Svelte component?","tags":["svelte","svelte-component"],"text":"Title: Why does the following event handler work in a Svelte component?\nTags: svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI have the following component `Form.svelte`:\n\n```\n\n export let onDelete;\n\n Update\n Delete\n\n```\n\nand this is the page which is using the component:\n\n```\n\n import Form from './Form.svelte';\n\n function onDelete() {\n console.log('deleted');\n }\n\n```\n\nAccording to the Svelte docs and tutorials, we should define the event handler as\n\n```\n onDelete()}>Delete\n```\n\nor\n\n```\nDelete\n```\n\nSo why does the above code in the `Form.svelte` component works?\n\nHere is a REPL.\n\n========================================\n\nCode:\n```html\n<script>\n export let onDelete;\n</script>\n<form>\n <button type=\"submit\">Update</button>\n <button on:click={onDelete()}>Delete</button>\n</form>\n```\n\n```html\n<script>\n import Form from './Form.svelte';\n\n function onDelete() {\n console.log('deleted');\n }\n</script>\n<Form {onDelete} />\n```\n\n```html\n<button on:click={() => onDelete()}>Delete</button>\n```\n\n```html\n<button on:click={onDelete}>Delete</button>\n```\n\n```text\nForm.svelte\n```\n\n```text\nForm.svelte\n```\n\n```js\ndispose = listen(button1, \"click\", onDelete());\n```\n\n```js\ndispose = listen(button1, \"click\", function () {\n if (is_function(/*onDelete*/ ctx[0]()))\n /*onDelete*/ ctx[0]().apply(this, arguments);\n});\n```\n\n```text\nif\n```\n\n```text\nonDelete\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.693Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":102,"estimatedTokens":345}}468{"id":"stack-70450981","source":"stackoverflow","questionId":70450981,"title":"How to inherit slots with svelte components?","tags":["javascript","inheritance","svelte"],"text":"Title: How to inherit slots with svelte components?\nTags: javascript, inheritance, svelte\nSource: Stack Overflow\n\nQuestion:\nThere is a component `` that inherits from a component ``.\n\nThe `` component defines a slot named `content` with a fallback content. The `` component also defines a slot named `content` with a different fallback content.\n\n```\n\n foo fallback\n \n\nimport Foo from './Foo.svelte'\n\n \n bar fallback\n \n\n```\n\nThe `` component displays the fallback when called with `` but it does not display the custom content when called with `bar custom`.\n\nCan you tell me what I am doing wrong?\n\n```\n\n foo custom\n\n bar custom\n\n```\n\nNote that this code is oversimplified, and my real-world usecase is a bit more complex than this, and I need to use slots there.\n\nThe fiddle: https://svelte.dev/repl/5c525651eb8b4f60a6a696c1bd19f723\n\n========================================\n\nTop Answer:\nI think most of the answers were pretty close. I believe you can fix it by creating a slot with both content and name being the same value. Building off of your example (Repl with full 3rd level inheritance),\n\n```\n\n foo fallback\n\n```\n\n```\n\nimport Foo from './Foo.svelte'\n\n \n bar fallback\n \n\n```\n\nBy doing it this way, we are both passing the slot through and including our new fallback.\n\nIf you were looking to make sure the span is there, that can be done by either putting it inside or outside of the `slot` depending on your use case.\n\n```\n\nimport Foo from './Foo.svelte'\n\n \n \n bar fallback\n \n \n\n \n \n bar fallback\n \n \n\n```\n\n========================================\n\nCode:\n```text\n<!-- Foo.svelte -->\n<slot name=\"content\">\n foo fallback\n</slot> \n\n<!-- Bar.svelte -->\n<script>import Foo from './Foo.svelte'</script>\n<Foo>\n <span slot=\"content\">\n bar fallback\n </span>\n</Foo>\n```\n\n```text\n<Foo/>\n<!-- prints 'foo fallback': OK -->\n\n<Foo>\n <span slot=\"content\">foo custom</span>\n</Foo>\n<!-- prints 'foo custom': OK -->\n\n<Bar/>\n<!-- prints 'bar fallback': OK -->\n\n<Bar>\n <span slot=\"content\">bar custom</span>\n</Bar>\n<!-- prints 'bar fallback': KO - I would have expected 'bar custom' -->\n```\n\n```text\n<Bar>\n```\n\n```text\n<Foo>\n```\n\n```text\n<Foo>\n```\n\n```text\ncontent\n```\n\n```text\n<Bar>\n```\n\n```text\ncontent\n```\n\n```text\n<Bar>\n```\n\n```text\n<Foo/>\n```\n\n```text\n<Bar><span slot=\"content\">bar custom</span></Bar>\n```\n\n```text\n// App.svelte\n\n<script>\n import Foo from './Foo.svelte'\n import Bar from './Bar.svelte'\n</script>\n\nExpected: <em>bar custom</em><br>\n<Bar>\n <span slot=\"content\">bar custom</span>\n</Bar>\n```\n\n```text\n// ./Bar.svelte\n\n<script>\n import Foo from './Foo.svelte';\n</script>\n\n<Foo>\n <span slot=\"content\">\n <slot name=\"content\">bar fallback</slot>\n </span>\n</Foo>\n```\n\n```text\n// ./Foo.svelte\n\n<slot name=\"content\">\n foo fallback\n</slot>\n```\n\n```text\nBar\n```\n\n```text\nFoo\n```\n\n```text\nBar\n```\n\n```text\nFoo\n```\n\n```text\ncontent\n```\n\n```text\nBar\n```\n\n```text\nFoo\n```\n\n```html\n<!-- Foo.svelte -->\n<slot name=\"content\">\n foo fallback\n</slot>\n```\n\n```html\n<!-- Bar.svelte -->\n<script>import Foo from './Foo.svelte'</script>\n<Foo>\n <slot name=\"content\" slot=\"content\">\n bar fallback\n </slot>\n</Foo>\n```\n\n```html\n<!-- Bar.svelte -->\n<script>import Foo from './Foo.svelte'</script>\n<!-- option 1-->\n<Foo>\n <span>\n <slot name=\"content\" slot=\"content\">\n bar fallback\n </slot>\n </span>\n</Foo>\n<!-- option 2-->\n<Foo>\n <slot name=\"content\" slot=\"content\">\n <span>\n bar fallback\n </span>\n </slot>\n</Foo>\n```\n\n```text\nslot\n```\n\n========================================\n\nComments:\n- You aren't defining a slot for `Bar` so all that is ever rendered is `Foo`'s slot. A clearer way to do this is to define a property for `Bar` repl\n- Thanks. This is an oversimplified sample of code to expose my issue, in my real-world usecase a property is just not powerful enough and I do need to use slots.\n- Fair enough, though it's a little unclear how you expect the nested slots to work. Regardless, you are passing slot content to `Bar` but Bar doesn't define a slot, here's one option which still renders slot content passed to `Bar` inside `Foo`: REPL (looks like REPL site is broken)\n- Thank you. This seems OK, but that would break with a third level of inheritance. For instance, with a `` component inheriting from `` and without a fallback slot, I cannot achieve to use a custom content. svelte.dev/repl/58c4dadc8d884abd8c46e4f8edfa6ea3 Although, that might be another issue.\n- Well you've just replicated the problem you had in the `Foo` `Bar` inheritance by not specifying a slot in `Baz`. Without more context for how your real compenents interact I can't really offer more.","metadata":{"transformedAt":"2026-08-18T18:33:40.693Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":267,"estimatedTokens":1157}}469{"id":"stack-66917187","source":"stackoverflow","questionId":66917187,"title":"How to mount HTMLElement directly in Svelte?","tags":["svelte","svelte-3"],"text":"Title: How to mount HTMLElement directly in Svelte?\nTags: svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI'm using some external code that returns an HTML element, and it'd be nice to embed it without having to manage the loading and everything via JavaScript (i.e. `appendChild`/`removeChild`). Right now I'm using `{@html element.outerHTML}`, but this seems inelegant to make the round trip to an HTML string:\n\n```\n\n function sleep(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n async function someCall() {\n await sleep(1000);\n const p = document.createElement(\"p\");\n p.innerText = \"hello!\";\n console.log(p);\n return p;\n }\n\n let data = someCall();\n\n {#await data}\n Loading data...\n\n {:then result}\n {@html result.outerHTML}\n {/await}\n\n```\n\nWhat I'm looking for might be something like\n\n```\n\n {#await data}\n Loading data...\n\n {:then result}\n {result}\n {/await}\n\n```\n\nbut this doesn't work (since it string-ifies the element).\n\n========================================\n\nTop Answer:\nI think you can do it like this.\n\n```\n\n function sleep(ms) {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n async function someCall() {\n await sleep(1000);\n return `hello\n\n`;\n }\n\n let data = someCall();\n\n \n {#await data}\n Loading data...\n\n {:then result}\n {@html result}\n {/await}\n\n```\n\nhttps://codesandbox.io/s/blissful-sea-mfcx5?file=/App.svelte:0-336\n\n========================================\n\nCode:\n```html\n<script>\n function sleep(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n async function someCall() {\n await sleep(1000);\n const p = document.createElement(\"p\");\n p.innerText = \"hello!\";\n console.log(p);\n return p;\n }\n\n let data = someCall();\n</script>\n\n<div>\n {#await data}\n <p>Loading data...</p>\n {:then result}\n {@html result.outerHTML}\n {/await}\n</div>\n```\n\n```html\n<div>\n {#await data}\n <p>Loading data...</p>\n {:then result}\n {result}\n {/await}\n</div>\n```\n\n```text\nappendChild\n```\n\n```text\nremoveChild\n```\n\n```text\n{@html element.outerHTML}\n```\n\n```text\n<script>\n import { onMount } from 'svelte';\n\n function sleep(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n let elem;\n \n onMount(async () => {\n await sleep(1000);\n const p = document.createElement(\"p\");\n p.innerText = \"hello!\";\n elem.appendChild(p) \n });\n</script>\n\n<div bind:this={elem}> \n</div>\n```\n\n```text\n<script>\n function sleep(ms) {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n async function someCall() {\n await sleep(1000);\n return `<p>hello</p>`;\n }\n\n let data = someCall();\n</script>\n\n<main>\n <div>\n {#await data}\n <p>Loading data...</p>\n {:then result}\n {@html result}\n {/await}\n</div>\n</main>\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.693Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":176,"estimatedTokens":695}}470{"id":"stack-70403075","source":"stackoverflow","questionId":70403075,"title":"Sveltekit newly created cookie is not showing in the hook's handle function","tags":["cookies","svelte","sveltekit"],"text":"Title: Sveltekit newly created cookie is not showing in the hook's handle function\nTags: cookies, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\n### Summary\n\nOnce *set-cookie* header is sent in a response it takes another request before the cookie is visible in `handle()` function in the `hooks.ts` file.\n\n### Example\n\n- User POSTs username & password to the login endpoint;\n\n- Enpoint responds with set *access_token* cookie header;\n\n- User should be redirected to a protected page. (**FAILS**)\n\nIt fails because auth guard checks if the cookie exists, but it can't be seen from a code side at this point, only in the browser end.\n\n*Refresh the page*\n\nUser is now able to be redirected to a protected page.\n\n### Minimal reproduction\n\nIt has dummy login/logout functionality & protected user profile. There are also server side console logs which shows that cookie *lags* to be recognised in a hook.\n\n========================================\n\nCode:\n```text\nhandle()\n```\n\n```text\nhooks.ts\n```\n\n```text\nimport * as cookie from 'cookie';\n\nexport const post = (request) => {\n return {\n status: 302,\n headers: {\n location: '/',\n 'set-cookie': `${cookie.serialize('token', 'VALUE_OF_THE_COOKIE')}; path=/; HttpOnly`\n }\n }\n};\n\nexport const del = (request) => {\n return {\n status: 302,\n headers: {\n location: '/',\n 'set-cookie': `${cookie.serialize('token', '')}; path=/; HttpOnly; maxAge: 0`\n }\n }\n};\n```\n\n========================================\n\nComments:\n- I have a very similar example running flawlessly. The only difference i could find on first sight is that i am returning a `status: 302` instead of 200 when authenticating inside your login.ts file. Could you please try that as well? If it doesn`t work, please let me know and ill run your code on my side to troubleshoot\n- Hi, Did you found any solution for this? I've used `status: 302` but I am still facing this issue.\n- Hi, Blaze, status 302 did it for me.\n- Yup, 302 worked for me as well. Blaze, I'd try to double check if `contentType: \"application/json\"` header is set on the request.\n- Do we know why setting the HTTP response status to 302 would affect whether or not the cookie is readable in `hooks.ts`? Those seem unrelated to each other","metadata":{"transformedAt":"2026-08-18T18:33:40.693Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":70,"estimatedTokens":578}}471{"id":"stack-66878080","source":"stackoverflow","questionId":66878080,"title":"How to create pages from markdown in SvelteKit","tags":["svelte","sveltekit"],"text":"Title: How to create pages from markdown in SvelteKit\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm in the process of migrating my blog from Sapper to SvelteKit. I've written blog posts using markdown, and I was using markedjs to import the markdown files and export them to my component. It looks like this approach doesn't work with SvelteKit, however.\n\nHow would I do this using SvelteKit? Do I need a Vite plugin?\n\n========================================\n\nCode:\n```text\nnpx svelte-add mdsvex\n```\n\n========================================\n\nComments:\n- This is magic: mdsvex.com","metadata":{"transformedAt":"2026-08-18T18:33:40.693Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":20,"estimatedTokens":150}}472{"id":"stack-71326906","source":"stackoverflow","questionId":71326906,"title":"Global Descendant-Only Styles in Svelte","tags":["javascript","css","svelte","svelte-3","svelte-component"],"text":"Title: Global Descendant-Only Styles in Svelte\nTags: javascript, css, svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nIs there a way in Svelte to add styles that only affect the current component and any descendant components?\n\nSvelte supports a native `:global()` selector wrapper which will declare styles for that selector in the global scope, but I am looking for something similar which only matches selectors in the current or any descendant components.\n\nFor example (REPL):\n\n**App.svelte**\n\n```\n\n import C1 from './C1.svelte';\n let name = 'world';\n\nHello {name}!\n```\n\n**C1.svelte**\n\n```\n\n import C2 from './C2.svelte';\n let name = 'world';\n\n :global(div) {\n padding: 10px;\n background-color: blue;\n }\n div {\n background-color: red;\n }\n\n```\n\n**C2.svelte**\n\n```\n\n```\n\nIn the above example, all three components receive the global styling from the middle child component, **C1.svelte**. I am looking for a way to do a sort of hybrid styling (not passing down styles to child components) to add \"global-down\" styles that only affect components downward in the component tree.\n\nWhen the `:global()` selector wrapper is not used, matched nodes are assigned a unique class which the selector then targets, added to the selector during compilation. What I am asking/suggesting would be something like this:\n\n```\n:find(div) {\n background-color: blue;\n}\n```\n\n…where `:find()` similarly assigns a unique class to any HTML elements matched in the same or descending components. Is this possible?\n\n========================================\n\nCode:\n```html\n<script>\n import C1 from './C1.svelte';\n let name = 'world';\n</script>\n\n<div><C1>Hello {name}!</C1></div>\n```\n\n```html\n<script>\n import C2 from './C2.svelte';\n let name = 'world';\n</script>\n\n<style>\n :global(div) {\n padding: 10px;\n background-color: blue;\n }\n div {\n background-color: red;\n }\n</style>\n\n<div><C2><slot /></C2></div>\n```\n\n```html\n<div><slot /></div>\n```\n\n```css\n:find(div) {\n background-color: blue;\n}\n```\n\n```text\n:global()\n```\n\n```text\n:global()\n```\n\n```text\n:find()\n```\n\n```html\n<style>\n div :global(div) {\n padding: 10px;\n background-color: blue;\n }\n</style>\n```\n\n```css\ndiv.svelte-hash div { /* etc */ }\n```\n\n```html\n<style>\n div, div :global(div) {\n padding: 10px;\n background-color: blue;\n }\n</style>\n```\n\n```text\n:global()\n```\n\n========================================\n\nComments:\n- This makes perfect sense! I played around with the idea of using `div, * :global(div)` but Rich Harris pointed out on GitHub that my solution wouldn't account for elements that were descendants of an unscoped component within a top-level component where the styles are applied, so a scoped selector truly is necessary.","metadata":{"transformedAt":"2026-08-18T18:33:40.694Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":139,"estimatedTokens":695}}473{"id":"stack-78325491","source":"stackoverflow","questionId":78325491,"title":"Running standalone scripts and long-running applications with SvelteKit codebase","tags":["vite","svelte","sveltekit"],"text":"Title: Running standalone scripts and long-running applications with SvelteKit codebase\nTags: vite, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a SvelteKit project and'd like to run some maintenance scripts from the command line. I know how to run scripts with node. The maintenance scripts would refer modules in SvelteKit's `$lib` folder which then import other modules and `$env`.\n\nHow can I run a script in a way that the SvelteKit framework specific functionality imports like $lib and $env are available inside the script code?\n\nE.g.\n\n```\nnode src/scripts/myscript.js # How can import $lib here\n```\n\n- How SvelteKit sets up its framework specific modules and imports?\n\n- What of these can be used in command line applications? Naturally some like navigator cannot be made available.\n\n========================================\n\nTop Answer:\nI would proceed like that:\n\n1\nPlace your script in a directory like src/scripts. For example, src/scripts/myscript.js.\n\n2\n\n```\nnpm install --save-dev esbuild vite\n```\n\n3\n\n```\nimport { defineConfig } from 'vite';\nimport { sveltekit } from '@sveltejs/kit/vite';\n\nexport default defineConfig({\n plugins: [sveltekit()],\n build: {\n outDir: './out',\n rollupOptions: {\n input: './src/scripts/myscript.js'\n }\n }\n});\n```\n\n4\nThis configuration ensures that Vite uses the SvelteKit plugin to resolve module paths and other configurations as it would in your SvelteKit application.\n\nc. Modify your script to use async imports if necessary:\nDepending on what you are importing from $lib or other SvelteKit managed directories, you might need to adjust how imports are handled:\n\n5\n\n```\n// Example using dynamic import\n(async () => {\n const { myFunction } = await import('$lib/myLibModule');\n myFunction();\n})();\n```\n\n6 Add a script to package.json:\nAdd a command in your package.json to run your script through Vite:\n\n```\n\"scripts\": {\n \"run-script\": \"vite build --config vite.config.script.js && node ./out/myscript.js\"\n}\n```\n\n7\n\n```\nnpm run run-script\n```\n\nThis setup ensures that your Node.js script can use all SvelteKit-specific aliases and functionalities, except those that are strictly browser-specific (like navigator or DOM APIs).\n\nLimitations and Considerations:\nEnvironment Variables: Ensure that environment variables used by $env are available in the Node.js runtime environment when the script is executed.\nBrowser-Specific APIs: Clearly, APIs that depend on a browser context won't work in this setup and should either be mocked or avoided.\n\n========================================\n\nCode:\n```bash\nnode src/scripts/myscript.js # How can import $lib here\n```\n\n```text\n$lib\n```\n\n```text\n$env\n```\n\n```bash\nnpx vite-node src/scripts/my-sveltekit-script.js\n```\n\n```text\nprocess.env\n```\n\n```text\nnpm install --save-dev esbuild vite\n```\n\n```text\nimport { defineConfig } from 'vite';\nimport { sveltekit } from '@sveltejs/kit/vite';\n\nexport default defineConfig({\n plugins: [sveltekit()],\n build: {\n outDir: './out',\n rollupOptions: {\n input: './src/scripts/myscript.js'\n }\n }\n});\n```\n\n```text\n// Example using dynamic import\n(async () => {\n const { myFunction } = await import('$lib/myLibModule');\n myFunction();\n})();\n```\n\n```text\n\"scripts\": {\n \"run-script\": \"vite build --config vite.config.script.js && node ./out/myscript.js\"\n}\n```\n\n```text\nnpm run run-script\n```\n\n```text\nesrun\n```\n\n```text\ndotenv\n```\n\n```text\n$env\n```\n\n```text\ndotenv\n```\n\n```text\n$env\n```\n\n========================================\n\nComments:\n- `$lib` is just an alias. Not sure how exactly `$env` is implemented.\n- I wanted to access private environment variables in my server-side scripts using the regular `$env` accessor, and found the option `vite-node --options.transformMode.ssr='/.*/' src/scripts/my-script.js` thanks to this github discussion: github.com/sveltejs/kit/discussions/…","metadata":{"transformedAt":"2026-08-18T18:33:40.694Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":172,"estimatedTokens":965}}474{"id":"stack-59363370","source":"stackoverflow","questionId":59363370,"title":"Why do we need to access the custom Event data through 'detail' Object in Svelte?","tags":["javascript","svelte","svelte-3","svelte-component"],"text":"Title: Why do we need to access the custom Event data through 'detail' Object in Svelte?\nTags: javascript, svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nWhy do we need to access the custom event property through 'detail' object?\n\n```\nfunction handleMessage(event) {\n\n alert(event.detail.text); // why do we need to access 'text' property from 'detail' object?\n\n}\n\n// In the Child component, we are using this function to dispatch the custom event with some data.\n\n function sayHello() {\n dispatch('message', {\n text: 'Hello!' // we are not wrapping the data into the 'detail' object\n });\n }\n```\n\nSample code is here\n\n========================================\n\nCode:\n```text\nfunction handleMessage(event) {\n\n alert(event.detail.text); // why do we need to access 'text' property from 'detail' object?\n\n}\n\n\n\n// In the Child component, we are using this function to dispatch the custom event with some data.\n\n function sayHello() {\n dispatch('message', {\n text: 'Hello!' // we are not wrapping the data into the 'detail' object\n });\n }\n```\n\n```text\nexport function createEventDispatcher() {\n const component = get_current_component();\n\n return (type: string, detail?: any) => {\n const callbacks = component.$$.callbacks[type];\n\n if (callbacks) {\n // TODO are there situations where events could be dispatched\n // in a server (non-DOM) environment?\n const event = custom_event(type, detail);\n callbacks.slice().forEach(fn => {\n fn.call(component, event);\n });\n }\n };\n}\n```\n\n```text\nexport function custom_event<T=any>(type: string, detail?: T) {\n const e: CustomEvent<T> = document.createEvent('CustomEvent');\n e.initCustomEvent(type, false, false, detail);\n return e;\n}\n```\n\n========================================\n\nComments:\n- This is not specific to svelte. The `CustomEvent` model supports the `detail` property for passing data. See Creating Events\n- Agree. In native custom events we will be using 'detail' object explicitly. But here we are sending the data without wrapping it into 'detail' object.","metadata":{"transformedAt":"2026-08-18T18:33:40.694Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":78,"estimatedTokens":543}}475{"id":"stack-70534899","source":"stackoverflow","questionId":70534899,"title":"SvelteKit: \"Error: request.query has been replaced by request.url.searchParams\"","tags":["npm","svelte","sveltekit"],"text":"Title: SvelteKit: \"Error: request.query has been replaced by request.url.searchParams\"\nTags: npm, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI wanted to try out SvelteKit on MacOs 11.5.2. Using node v16.13.1, npm 8.1.2.\n\nI have installed the SvelteKit as per original guidance:\n\n```\nnpm init svelte@next my-app\ncd my-app\nnpm install\nnpm run dev -- --open\n```\n\nThen, when localhost:3000 opens, I get this error:\n\n```\n**Error: request.query has been replaced by request.url.searchParams**\n at Object.get (file:///Web/Svelte_30-12-21/my-app/node_modules/@sveltejs/kit/dist/ssr.js:1753:12)\n at Object.handle (/Web/Svelte_30-12-21/my-app/src/hooks.ts:10:30)\n at respond (file:///Web/Svelte_30-12-21/my-app/node_modules/@sveltejs/kit/dist/ssr.js:1764:30)\n at svelteKitMiddleware (file:///Web/Svelte_30-12-21/my-app/node_modules/@sveltejs/kit/dist/chunks/index.js:4577:28)\n```\n\nWhat could be the problem?\n\n========================================\n\nTop Answer:\nI ran into the same problem. In `src/hooks.js` replace\n\n`const method = request.query.get('_method');`\n\nwith\n\n`const method = request.method;`\n\nIf you are using `npm init svelte@next my-app` and using the demo app, you are also going to run into a problem in `Header.svelte`.\n\nreplace\n\n```\n\n- Home\n\n- About\n\n- Todos\n```\n\nwith\n\n```\n\n \n- Home\n \n About\n \n \n Todos\n \n\n```\n\n========================================\n\nCode:\n```text\nnpm init svelte@next my-app\ncd my-app\nnpm install\nnpm run dev -- --open\n```\n\n```text\n**Error: request.query has been replaced by request.url.searchParams**\n at Object.get (file:///Web/Svelte_30-12-21/my-app/node_modules/@sveltejs/kit/dist/ssr.js:1753:12)\n at Object.handle (/Web/Svelte_30-12-21/my-app/src/hooks.ts:10:30)\n at respond (file:///Web/Svelte_30-12-21/my-app/node_modules/@sveltejs/kit/dist/ssr.js:1764:30)\n at svelteKitMiddleware (file:///Web/Svelte_30-12-21/my-app/node_modules/@sveltejs/kit/dist/chunks/index.js:4577:28)\n```\n\n```text\nnpm update\n```\n\n```text\nnode_modules\n```\n\n```js\n<li class:active={$page.path === '/'}><a sveltekit:prefetch href=\"/\">Home</a></li>\n<li class:active={$page.path === '/about'}><a sveltekit:prefetch href=\"/about\">About</a></li>\n<li class:active={$page.path === '/todos'}><a sveltekit:prefetch href=\"/todos\">Todos</a></li>\n```\n\n```js\n<ul>\n <li class:active={$page.url.pathname === '/'}><a sveltekit:prefetch href=\"/\">Home</a></li>\n <li class:active={$page.url.pathname === '/about'}>\n <a sveltekit:prefetch href=\"/about\">About</a>\n </li>\n <li class:active={$page.url.pathname === '/todos'}>\n <a sveltekit:prefetch href=\"/todos\">Todos</a>\n </li>\n</ul>\n```\n\n```text\nsrc/hooks.js\n```\n\n```text\nconst method = request.query.get('_method');\n```\n\n```text\nconst method = request.method;\n```\n\n```text\nnpm init svelte@next my-app\n```\n\n```text\nHeader.svelte\n```\n\n```text\nsrc/hooks.js\n```\n\n```text\nconsole.log(request.method)\n```\n\n```text\nGET\n```\n\n```text\n// TODO https://github.com/sveltejs/kit/issues/1046\nconst searchParams = new URL(event.request.url).searchParams;\nif (searchParams.has('_method')) {\n event.request = new Request({ ...event.request, method: searchParams.get('_method').toUpperCase()||''}) ;\n}\n```\n\n========================================\n\nComments:\n- This one also fixed it. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:40.694Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":155,"estimatedTokens":812}}476{"id":"stack-74161479","source":"stackoverflow","questionId":74161479,"title":"Does SvelteKit support background jobs","tags":["svelte","sveltekit"],"text":"Title: Does SvelteKit support background jobs\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nWhere should I put codes that are supposed to always run like croner? I can't find it here.\n\nEdit:\n\nIt seems like it's not possible at the moment. Should I use a separate backend?\n\n========================================\n\nTop Answer:\nSvelte does not support come with support for background jobs, but if you are running it as a node app then you can add a library for background jobs. I'd suggest you checkout Quirrel from https://docs.quirrel.dev/api/sveltekit/ .\n\nAlso, you can create API routes with Sveltekit which can do whatever you want, they don't have to render HTML and can respond to any HTTP verbs: https://docs.quirrel.dev/api/sveltekit/\n\n========================================\n\nCode:\n```js\n/**\n * Cron jobs for SvelteKit site\n * \n * - Runs as a standalone process (launched with vite-node)\n */\n\nimport { doMyDailyJob } from \"$lib/my-tasks/daily\";\nimport schedule from \"node-schedule\";\n\nconst jobs = []\n\n// Run 00:10 every day\njobs.push(schedule.scheduleJob('10 00 * * *', async function () {\n await doMyDailyJob();\n}));\n\nconsole.log(\"node-schedule running with jobs\", jobs.map((j) => j.name));\n```\n\n```json\n\"scripts\": {\n \"cron\": \"vite-node src/scripts/cron.js\"\n },\n```\n\n```bash\nnpm run cron\n```\n\n```text\nnode-schedule running with jobs [ '<Anonymous Job 1 2024-09-12T01:47:00.125Z>']\n```\n\n```yaml\nservices:\n frontend:\n container_name: frontend\n image: ghcr.io/miohtama/exampleapp:main\n ports:\n - '3000'\n env_file:\n - prod.env\n deploy:\n restart_policy:\n condition: on-failure\n delay: 5s\n max_attempts: 3\n window: 30s\n\n caddy:\n image: caddy:2.4.3-alpine\n container_name: caddy\n restart: unless-stopped\n command: caddy run --config /etc/caddy/Caddyfile\n ports:\n - 80:80\n - 443:443\n volumes:\n - ./caddy/prod/Caddyfile:/etc/caddy/Caddyfile\n - ./caddy/data:/data\n - ./caddy/logs:/var/log/caddy\n depends_on:\n - frontend\n\n cron:\n container_name: cron\n image: ghcr.io/miohtama/exampleapp:main\n entrypoint: npx \n env_file:\n - prod.env\n command: vite-node src/scripts/cron.js\n```\n\n```text\nnode\n```\n\n```text\n$env\n```\n\n```text\n$lib\n```\n\n```text\nsrc/scripts/cron.js\n```\n\n```text\npackage.json\n```\n\n```text\n$lib/scripts/run-my-daily-job.js\n```\n\n```text\nrun-my-daily-job.js\n```\n\n```text\ndoMyDailyJob()\n```\n\n========================================\n\nComments:\n- This is incorrect, Sveltekit supports API routes that let you define whatever function you want to run server-side. Also if you run it as a Node app, you can use libraries to support background jobs.\n- Quirrel has not been updated since 2023, since the maintainer joined Netlify.","metadata":{"transformedAt":"2026-08-18T18:33:40.694Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":132,"estimatedTokens":698}}477{"id":"stack-58058715","source":"stackoverflow","questionId":58058715,"title":"How could I sort a svelte array-store?","tags":["store","svelte"],"text":"Title: How could I sort a svelte array-store?\nTags: store, svelte\nSource: Stack Overflow\n\nQuestion:\nI am doing a Todo app with store.\nAll is good now , but i want to sort the items in the store , or maybe to show them ordered.\nThe store is an array , and all item in the store is an object with the keys : text,id,editing,line,checkboxed.\nSo \"checkboxed\" is a boolean value , and i want that all the \"checkboxed:true\" objects would be first in the array.\nhow could i do it ?\nOr maybe : \nhow could i sort items in svelte-store-array in general ?\nthanks !!!!\n\nlink to the app\n\n========================================\n\nTop Answer:\nanother solution : \nto add that to the TodoLIst component :\n\n```\n$:sortedTodos=$customTodos\n .sort((a,b)=>b.checkboxed-a.checkboxed)\n .sort((a,b)=>a.line-b.line)\n```\n\nand work with sortedTodos variable in the \"each\" loop.\n\n========================================\n\nCode:\n```text\nconst sorted = derived(todos_, todos => sortBy(todos, 'checkboxed'))\n```\n\n```text\nderived\n```\n\n```text\n$:sortedTodos=$customTodos\n .sort((a,b)=>b.checkboxed-a.checkboxed)\n .sort((a,b)=>a.line-b.line)\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.694Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":46,"estimatedTokens":280}}478{"id":"stack-61200516","source":"stackoverflow","questionId":61200516,"title":"How to use fetch in a Sapper project outside of routes?","tags":["svelte","sapper"],"text":"Title: How to use fetch in a Sapper project outside of routes?\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nIn Sapper it's possible to use `this.fetch` in the `preload()` function inside ``. Sapper then figures out whether to use the client or server version of `fetch`.\n\n```\n\n export async function preload() {\n const res = await this.fetch(`something.json`);\n }\n\n```\n\nWriting all your requests in your routes doesn't scale well so it becomes a necessity to create an `api` service to do something like:\n\n```\n\n import {getJson} from 'api';\n\n export async function preload() {\n const res = await getJson();\n }\n\n```\n\nThis creates a problem since outside of the `preload()` function there is no `this` context provided by Sapper and hence no `this.fetch` available when running in the Node context (when loading the first page of the application and doing SSR). Afterwards all requests are made from the browser so regular `fetch` is available.\n\nA solution could be to use an HTTP client for Node like `node-fetch` in the api service and then determine at runtime with `process.browser` if we need to use `fetch` or `node-fetch`.\n\nIs there a better way to overcome this Sapper limitation?\n\n========================================\n\nTop Answer:\n`this.fetch` is meant to be used only in routes (think `asyncData` in Nuxt).\nUsing Axios is a common solution too, as it allows to write code that execute the same in both environments without patching `fetch` (like you would with `node-fetch`).\n\n========================================\n\nCode:\n```text\n<script context=\"module\">\n export async function preload() {\n const res = await this.fetch(`something.json`);\n }\n</script>\n```\n\n```text\n<script context=\"module\">\n import {getJson} from 'api';\n\n export async function preload() {\n const res = await getJson();\n }\n</script>\n```\n\n```text\nthis.fetch\n```\n\n```text\npreload()\n```\n\n```text\n<script context=\"module\">\n```\n\n```text\nfetch\n```\n\n```text\napi\n```\n\n```text\npreload()\n```\n\n```text\nthis\n```\n\n```text\nthis.fetch\n```\n\n```text\nfetch\n```\n\n```text\nnode-fetch\n```\n\n```text\nprocess.browser\n```\n\n```text\nfetch\n```\n\n```text\nnode-fetch\n```\n\n```text\n<script context=\"module\">\n import {getJson} from 'api';\n\n export async function preload() {\n const res = await getJson(this.fetch);\n }\n</script>\n```\n\n```text\nthis.fetch\n```\n\n```text\nthis.fetch\n```\n\n```text\nasyncData\n```\n\n```text\nfetch\n```\n\n```text\nnode-fetch\n```\n\n========================================\n\nComments:\n- You might want to look at npmjs.com/package/@beyonk/sapper-httpclient which I wrote for this exact purpose. It does what Stephane suggests below.\n- Thanks @AntonyJones ! I moved from Sapper to an SPA with code splitting because it became too complicated dealing with cookies.","metadata":{"transformedAt":"2026-08-18T18:33:40.694Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":147,"estimatedTokens":695}}479{"id":"stack-66236169","source":"stackoverflow","questionId":66236169,"title":"rollup.js svelte bundle not activating in index.html","tags":["javascript","server","svelte","rollup"],"text":"Title: rollup.js svelte bundle not activating in index.html\nTags: javascript, server, svelte, rollup\nSource: Stack Overflow\n\nQuestion:\nI am trying to deploy my svelte project, but I am having trouble having the bundle javascript activate outside of livereload plugin. When I run rollup -c -w, the code displays fine, but serving the application with other server does not activate the javacsript. It should at least console.log something and hopefully add the html, but it only display a blank page.\n\nrollup.config.js\n\n```\nimport svelte from \"rollup-plugin-svelte\";\nimport resolve from \"@rollup/plugin-node-resolve\";\nimport commonjs from \"@rollup/plugin-commonjs\";\nimport livereload from \"rollup-plugin-livereload\";\nimport replace from \"@rollup/plugin-replace\";\nimport { terser } from \"rollup-plugin-terser\";\nimport postcss from \"rollup-plugin-postcss\";\nimport babel from \"rollup-plugin-babel\";\n\nexport default {\n input: \"src/main.js\",\n output: {\n sourcemap: true,\n format: \"iife\",\n name: \"app\",\n file: \"public/build/bundle.js\"\n },\n plugins: [\n babel({\n exclude: \"node_modules/**\"\n }),\n \n svelte({\n // enable run-time checks when not in production\n dev: !production,\n // we'll extract any component CSS out into\n // a separate file - better for performance\n css: css => {\n css.write(\"bundle.css\");\n }\n }),\n\n postcss(),\n\n // If you have external dependencies installed from\n // npm, you'll most likely need these plugins. In\n // some cases you'll need additional configuration -\n // consult the documentation for details:\n // https://github.com/rollup/plugins/tree/master/packages/commonjs\n resolve({\n browser: true,\n dedupe: [\"svelte\"]\n }),\n commonjs(),\n\n // In dev mode, call `npm run start` once\n // the bundle has been generated\n !production && serve(),\n\n // Watch the `public` directory and refresh the\n // browser on changes when not in production\n !production && livereload(\"public\"),\n\n // If we're building for production (npm run build\n // instead of npm run dev), minify\n production && terser(),\n\n // for absolut imports\n // i.e., instead of\n // import Component from \"../../../../components/Component.svelte\";\n // we will be able to say\n // import Component from \"components/Component.svelte\";\n aliases\n ],\n watch: {\n clearScreen: false\n }\n};\n```\n\nrollup -c will output the bundle.js. My index.html is below\n\n```\n\n \n \n \n\n \n \n \n \n \n Teach Me Sensei\n\n \n if (process === undefined) {\n var process = { env: {} };\n }\n \n \n\n \n \n We're sorry but notus-svelte doesn't work properly without JavaScript\n enabled. Please enable it to continue.\n \n \n \n \n\n```\n\nHere is a picture of what the chrome console looks like when running livereload. rollup -c -w\n\nhttps://i.sstatic.net/rZw5i.png\n\nHere is a picture of what the chrome console looks like in production or other servers. rollup -c and just serve the static content. I am not sure if livereload does something special for the javascript, but in my other servers, I made sure to serve the public folder. I can view the bundle.js in the console.\n\nhttps://i.sstatic.net/JMBab.png\n\n========================================\n\nCode:\n```text\nimport svelte from \"rollup-plugin-svelte\";\nimport resolve from \"@rollup/plugin-node-resolve\";\nimport commonjs from \"@rollup/plugin-commonjs\";\nimport livereload from \"rollup-plugin-livereload\";\nimport replace from \"@rollup/plugin-replace\";\nimport { terser } from \"rollup-plugin-terser\";\nimport postcss from \"rollup-plugin-postcss\";\nimport babel from \"rollup-plugin-babel\";\n\nexport default {\n input: \"src/main.js\",\n output: {\n sourcemap: true,\n format: \"iife\",\n name: \"app\",\n file: \"public/build/bundle.js\"\n },\n plugins: [\n babel({\n exclude: \"node_modules/**\"\n }),\n \n svelte({\n // enable run-time checks when not in production\n dev: !production,\n // we'll extract any component CSS out into\n // a separate file - better for performance\n css: css => {\n css.write(\"bundle.css\");\n }\n }),\n\n postcss(),\n\n // If you have external dependencies installed from\n // npm, you'll most likely need these plugins. In\n // some cases you'll need additional configuration -\n // consult the documentation for details:\n // https://github.com/rollup/plugins/tree/master/packages/commonjs\n resolve({\n browser: true,\n dedupe: [\"svelte\"]\n }),\n commonjs(),\n\n // In dev mode, call `npm run start` once\n // the bundle has been generated\n !production && serve(),\n\n // Watch the `public` directory and refresh the\n // browser on changes when not in production\n !production && livereload(\"public\"),\n\n // If we're building for production (npm run build\n // instead of npm run dev), minify\n production && terser(),\n\n // for absolut imports\n // i.e., instead of\n // import Component from \"../../../../components/Component.svelte\";\n // we will be able to say\n // import Component from \"components/Component.svelte\";\n aliases\n ],\n watch: {\n clearScreen: false\n }\n};\n```\n\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />\n\n <link rel=\"shortcut icon\" href=\"/favicon.ico\" />\n <link rel=\"apple-touch-icon\" sizes=\"76x76\" href=\"/apple-icon.png\" />\n <link rel=\"stylesheet\" href=\"/build/bundle.css\" />\n <link\n rel=\"stylesheet\"\n href=\"/assets/vendor/@fortawesome/fontawesome-free/css/all.min.css\"\n />\n <link rel=\"stylesheet\" href=\"/assets/styles/tailwind.css\" />\n <title>Teach Me Sensei</title>\n\n <script>\n if (process === undefined) {\n var process = { env: {} };\n }\n </script>\n </head>\n\n <body class=\"text-gray-800 antialiased\">\n <noscript>\n <strong\n >We're sorry but notus-svelte doesn't work properly without JavaScript\n enabled. Please enable it to continue.</strong\n >\n </noscript>\n <div id=\"app\"></div>\n <script src=\"/build/bundle.js\"></script>\n </body>\n</html>\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.694Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":231,"estimatedTokens":1492}}480{"id":"stack-47903917","source":"stackoverflow","questionId":47903917,"title":"How to manipulate DOM using Svelte framework","tags":["dom","svelte"],"text":"Title: How to manipulate DOM using Svelte framework\nTags: dom, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm pretty much new to Svelte framework. Recently I'm playing around with Svelte but confused how I would manipulate the DOM like in jQuery using Svelte.\n\nI'm trying to show/hide an `` on button click.\n\n========================================\n\nCode:\n```text\n<li>\n```\n\n```text\n<button on:click='set({ visible: !visible })'>toggle visibility</button>\n\n{{#if visible}}\n <p>hello!</p>\n{{/if}}\n```\n\n```text\n<button on:click='set({ visible: !visible })'>toggle visibility</button>\n\n<p hidden='{{!visible}}'>hello!</p>\n```\n\n```text\nvisible\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.694Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":33,"estimatedTokens":161}}481{"id":"stack-68155746","source":"stackoverflow","questionId":68155746,"title":"Can svelte use composable functions?","tags":["javascript","svelte","sveltekit"],"text":"Title: Can svelte use composable functions?\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am coming from vue and used to composable functions. I am trying to figure out the way to do this in svelte\n\nSo I make a js file and import store and then was trying to make a function that I could call on multiple components and act individually\n\nswipe.js file\n\n```\nimport { writable, derived, get } from 'svelte/store';\n\nfunction createSwipe() {\n\n const dyFromStart = writable(0)\n\n function moveEvent(eventType, val){\n console.log('moveEvent', eventType, val, get(dyFromStart))\n dyFromStart.update(n => n + 1);\n }\n\n const dxScore = derived(dyFromStart, $dyFromStart => $dyFromStart + 3)\n const dyScore = derived(dyFromStart, $dyFromStart => Math.round($dyFromStart + 100));\n return {\n moveEvent,\n dxScore,\n dyScore, \n };\n}\n\nexport const swipe = createSwipe();\n```\n\nthen in .svelte component import function in script and decompose into subparts\n\n```\n\nimport { swipe } from \"$lib/swipe\";\nlet { moveEvent, dxScore, dyScore } = swipe\n\n{$dxScore}{$dyScore}\n\n moveEvent\">button\n```\n\nWell eventually I want to turn into a swipe component hence name but trying to get fundamentals down. So I want to be able to have unique store for each component and for this if I use multiple of this .svelte component the state is shared amongst all.\n\nAnd not just like three idk modal.svelte components I want to use swipe for a bunch of diff components maybe a photoViewer.svelte right just generic swipe function and use same code for all.\n\nor would I just have to keep the state like `const dyFromStart = writable(0)` be just `let dyFromStart = 0` in each .svelte component and pass it into a pure js function that returns results and update local .svelte variables\n\nAdding this as the non store more pure js things I was trying but couldn't get to be reactive so accepting the answer below on store method that worked and sounds like is the correct approach\n\n```\nexport function createSwipe() {\n let dyFromStart = 0\n\n function moveEvent(eventType, val){\n console.log('moveEvent', eventType, val, dyFromStart, dxScore(), dyScore())\n dyFromStart++\n }\n\n function dxScore(){ return dyFromStart + 3 }\n // const dzScore = derived(dyFromStart, $dyFromStart => $dyFromStart + 3)\n const dyScore = () => Math.round(dyFromStart + 100)\n \n return {\n moveEvent,\n dxScore,\n dyScore,\n dyFromStart\n };\n```\n\n```\nexport function createSwipe() {\nlet dyFromStart = 0\n let dxScore = dyFromStart + 3\n let dyScore = Math.round(dyFromStart + 100)\n\n function moveEvent(eventType, val){\n console.log('moveEvent', eventType, val, dyFromStart, dxScore, dyScore)\n dyFromStart++\n dxScore = dyFromStart + 3\n dyScore = Math.round(dyFromStart + 100)\n }\n\n return {\n moveEvent,\n dxScore,\n dyScore,\n dyFromStart\n };\n```\n\nI suppose that works fine just not reactive with $ and need to call to update a diff local var if doing that\n\nthis would seem most sveltey to me or something like it as far as composable function type style not store type\n\n```\nexport function createSwipe() {\n let dyFromStart = 0\n\n function moveEvent(eventType, val){\n console.log('moveEvent', eventType, val)\n dyFromStart++\n }\n\n $: dxScore = dyFromStart + 3\n $: dyScore = Math.round($dyFromStart + 100)\n return {\n moveEvent,\n dxScore,\n dyScore, \n };\n}\n```\n\n========================================\n\nCode:\n```text\nimport { writable, derived, get } from 'svelte/store';\n\nfunction createSwipe() {\n\n const dyFromStart = writable(0)\n\n function moveEvent(eventType, val){\n console.log('moveEvent', eventType, val, get(dyFromStart))\n dyFromStart.update(n => n + 1);\n }\n\n const dxScore = derived(dyFromStart, $dyFromStart => $dyFromStart + 3)\n const dyScore = derived(dyFromStart, $dyFromStart => Math.round($dyFromStart + 100));\n return {\n moveEvent,\n dxScore,\n dyScore, \n };\n}\n\nexport const swipe = createSwipe();\n```\n\n```svelte\n<script>\nimport { swipe } from \"$lib/swipe\";\nlet { moveEvent, dxScore, dyScore } = swipe\n</script>\n<p>{$dxScore}{$dyScore}</p>\n<button on:click=\"() => moveEvent\">button</button>\n```\n\n```text\nexport function createSwipe() {\n let dyFromStart = 0\n\n function moveEvent(eventType, val){\n console.log('moveEvent', eventType, val, dyFromStart, dxScore(), dyScore())\n dyFromStart++\n }\n\n function dxScore(){ return dyFromStart + 3 }\n // const dzScore = derived(dyFromStart, $dyFromStart => $dyFromStart + 3)\n const dyScore = () => Math.round(dyFromStart + 100)\n \n return {\n moveEvent,\n dxScore,\n dyScore,\n dyFromStart\n };\n```\n\n```text\nexport function createSwipe() {\nlet dyFromStart = 0\n let dxScore = dyFromStart + 3\n let dyScore = Math.round(dyFromStart + 100)\n\n function moveEvent(eventType, val){\n console.log('moveEvent', eventType, val, dyFromStart, dxScore, dyScore)\n dyFromStart++\n dxScore = dyFromStart + 3\n dyScore = Math.round(dyFromStart + 100)\n }\n\n return {\n moveEvent,\n dxScore,\n dyScore,\n dyFromStart\n };\n```\n\n```text\nexport function createSwipe() {\n let dyFromStart = 0\n\n function moveEvent(eventType, val){\n console.log('moveEvent', eventType, val)\n dyFromStart++\n }\n\n $: dxScore = dyFromStart + 3\n $: dyScore = Math.round($dyFromStart + 100)\n return {\n moveEvent,\n dxScore,\n dyScore, \n };\n}\n```\n\n```text\nconst dyFromStart = writable(0)\n```\n\n```text\nlet dyFromStart = 0\n```\n\n```svelte\n<script>\n import { createSwipe } from \"$lib/swipe\";\n let { moveEvent, dxScore, dyScore } = createSwipe()\n</script>\n<p>{$dxScore}{$dyScore}</p>\n<button on:click=\"() => moveEvent\">button</button>\n```\n\n```text\nexport const swipe = createSwipe()\n```\n\n========================================\n\nComments:\n- Excellent yes this is exactly what I wanted thanks! up question is does the code need to (or is it recommended) to be using store type vars or would it work with plain js. When I tried with plain js I didnt quite figure out how to have the vars be reactive and tried having like $: locDxScore = dxScore or as var dxScore() and wouldn't be reactive. If called button and console log it would call it and show correct val but I'd rather it just be automatic if possible. I'm not 100% sure on all the pros and cons of the store stuff since new to svelte so yeah is it better or worse here\n- Usage of the store is the correct choice in this case in order to get the reactivity, automatic updates etc that you want.\n- I added some of the non store things I was trying that weren't reactive (or I wasn't doing fully right) but ok great sounds like store is way to go anyway thanks. Is this generally true also as best approach? Like a let variable in .svelte is reactive but can't move that exact code (no store) external and bring in and work same way reactive and all\n- Because if I have really long js code I mean not ideal to have super long js code in one file but also not ideal to have to convert everything to store to move to external file right? Seems like should work same way from external file I just have to do it right but maybe I'm wrong","metadata":{"transformedAt":"2026-08-18T18:33:40.694Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":245,"estimatedTokens":1751}}482{"id":"stack-73987081","source":"stackoverflow","questionId":73987081,"title":"Scroll to bottom of element in sveltekit","tags":["javascript","svelte","sveltekit"],"text":"Title: Scroll to bottom of element in sveltekit\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nHow do I make an element scroll to the bottom when the page is loaded?\n\nI've tried doing it in `onMount`, but the element is undefined.\n\nI'm accessing the element using `bind:this`.\n\nWhen I try to make the element scroll later (when clicking a button, for example) it works.\n\nHere's the code I'm using to make the element scroll to the bottom (taken from svelte repl):\n\n```\nnode.scroll({ top: node.scrollHeight, behavior: 'smooth' });\n```\n\n========================================\n\nCode:\n```text\nnode.scroll({ top: node.scrollHeight, behavior: 'smooth' });\n```\n\n```text\nonMount\n```\n\n```text\nbind:this\n```\n\n```js\nonMount(() => scrollToBottom(element))\n```\n\n```js\nconst scrollToBottom = node => {\n const scroll = () => node.scroll({\n top: node.scrollHeight,\n behavior: 'smooth',\n });\n scroll();\n\n return { update: scroll }\n};\n```\n\n```html\n<div use:scrollToBottom={list} ...>\n```\n\n```text\n#if\n```\n\n```text\nonMount\n```\n\n```text\nscrollToBottom\n```\n\n```text\nlist\n```\n\n```text\nupdate\n```\n\n========================================\n\nComments:\n- Marking this as the correct answer. My element was in fact shown conditionally. So, I fixed it using a reactive block, and it worked. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:40.694Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":78,"estimatedTokens":331}}483{"id":"stack-62423561","source":"stackoverflow","questionId":62423561,"title":"Why can't I access a \"$:\" aka reactive variable inside the script tags in svelte3?","tags":["svelte","svelte-3","reactive-variable"],"text":"Title: Why can't I access a \"$:\" aka reactive variable inside the script tags in svelte3?\nTags: svelte, svelte-3, reactive-variable\nSource: Stack Overflow\n\nQuestion:\nI am pretty new to svelte started it a week ago......😁\n\nI am trying to know about it i really loved❤️❤️ it but I have a problem☹️☹️\n\nI am trying to access a $: variable in the script tags but i get an Error `Cannot access 'greeting' before initialization`.\n\n```\n\n let name = 'world';\n $: greeting = `Hello ${name}`\n console.log(greeting)\n\n### Hello {name}!\n\n```\n\nI also tried declaring the variable with **let** prior to using it\n\n```\nlet greeting\n```\n\nBut in this case `console.log` outputs `undefined`.\n\n========================================\n\nCode:\n```js\n<script>\n let name = 'world';\n $: greeting = `Hello ${name}`\n console.log(greeting)\n</script>\n\n<h1>Hello {name}!</h1>\n```\n\n```js\nlet greeting\n```\n\n```text\nCannot access 'greeting' before initialization\n```\n\n```text\nconsole.log\n```\n\n```text\nundefined\n```\n\n```js\n<script>\n let name = 'world';\n $: greeting = `Hello ${name}`\n $: console.log(greeting)\n</script>\n\n<h1>Hello {name}!</h1>\n```\n\n```text\nconsole.log(greeting)\n```\n\n```text\nconsole.log\n```\n\n```text\ngreeting\n```\n\n```text\nundefined\n```\n\n```text\nlet greeting\n```\n\n```text\nconsole.log\n```\n\n```text\ngreeting\n```\n\n```text\ngreeting\n```\n\n```text\ngreeting\n```\n\n========================================\n\nComments:\n- Please add text as *text*, not screenshots.\n- I will add text from the next time.\n- Thanks Thomas ... It is working!!! 👍👍😁😁","metadata":{"transformedAt":"2026-08-18T18:33:40.694Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":110,"estimatedTokens":384}}484{"id":"stack-70983393","source":"stackoverflow","questionId":70983393,"title":"Dynamically detection of screen height and screen width to change the height and width of an image in svelte","tags":["jquery","css","svelte"],"text":"Title: Dynamically detection of screen height and screen width to change the height and width of an image in svelte\nTags: jquery, css, svelte\nSource: Stack Overflow\n\nQuestion:\nI was able to `display` a `div` tag only in `portrait` using the code below as mentioned by corrl in this post response\n\n```\n\n import Viewport from 'svelte-viewport-info'\n\n only visible in Portrait Mode\n\n :global(.Landscape .only-portrait) {\n display: none;\n }\n :global(.Portrait .only-portrait) {\n display: block;\n background: black;\n color: white;\n padding: 2rem;\n }\n\n```\n\nWorked as intended\n\nBut one of image elements dimension(height and width) needs to reduce in `portrait` mode when the dimension of the viewport to be more specific is `height.viewport https://i.sstatic.net/IaFBJ.png\n\nI tried to get the `viewport` `height` and `width` using code from Inner and Outer window bindings\n\n```\n\n $: outerWidth = 0\n $: outerHeight = 0\n\n```\n\nTried using jquery to change the width and height of image based on condition `viewport.width*1.33 imported jquery as mentioned here\n\n```\n\n import jQuery from 'jquery';\n import { onMount } from 'svelte';\n onMount(() => {\n window.jQuery = jQuery;\n \n jQuery(window).resize(function(event){\n console.log(outerWidth*1.33,' ',outerHeight);\n if(outerWidth*1.33 \n\n```\n\nI am getting this error\n\nFile: /home/Documents/sve/svelteDemo/src/App.svelte 29 |\nimport { MetaTags } from 'svelte-meta-tags'; 30 | import\n'svelte-viewport-info'; 31 | import jQuery from 'jquery';\n| ^ 32 | import { onMount } from 'svelte'; 33 | import image1v from './assets/image1.png';\nat formatError (/home/Documents/sve/svelteDemo/node_modules/vite/dist/node/chunks/dep-f5552faa.js:36769:46)\nat TransformContext.error (/home/Documents/sve/svelteDemo/node_modules/vite/dist/node/chunks/dep-f5552faa.js:36765:19)\nat normalizeUrl (/home/Documents/sve/svelteDemo/node_modules/vite/dist/node/chunks/dep-f5552faa.js:73703:26)\nat processTicksAndRejections (node:internal/process/task_queues:96:5)\nat async TransformContext.transform (/home/Documents/sve/svelteDemo/node_modules/vite/dist/node/chunks/dep-f5552faa.js:73843:57)\nat async Object.transform (/home/Documents/sve/svelteDemo/node_modules/vite/dist/node/chunks/dep-f5552faa.js:36985:30)\nat async doTransform (/home/Documents/sve/svelteDemo/node_modules/vite/dist/node/chunks/dep-f5552faa.js:52060:29)\n\nDon't seem to understand what is going wrong here!\n\nHow to make this work? or is there a simple solution for this?\n\n========================================\n\nCode:\n```text\n<script context=\"module\">\n import Viewport from 'svelte-viewport-info'\n</script>\n\n<div class=\"only-portrait\">\n only visible in Portrait Mode\n</div>\n\n<style>\n :global(.Landscape .only-portrait) {\n display: none;\n }\n :global(.Portrait .only-portrait) {\n display: block;\n background: black;\n color: white;\n padding: 2rem;\n }\n</style>\n```\n\n```text\n<script>\n $: outerWidth = 0\n $: outerHeight = 0\n</script>\n\n<svelte:window bind:innerWidth bind:outerWidth bind:innerHeight bind:outerHeight />\n```\n\n```text\n<script lang=\"ts\">\n import jQuery from 'jquery';\n import { onMount } from 'svelte';\n onMount(() => {\n window.jQuery = jQuery;\n \n jQuery(window).resize(function(event){\n console.log(outerWidth*1.33,' ',outerHeight);\n if(outerWidth*1.33 <= outerHeight) {\n jQuery(\".imageclass\").each(function() {\n jQuery(this).attr(\"width\", \"78vw\"); jQuery(this).attr(\"height\", \"78vw/2.81vh\");\n });} \n\n });\n\n});\n</script>\n<svelte:window bind:outerWidth bind:outerHeight />\n```\n\n```text\ndisplay\n```\n\n```text\ndiv\n```\n\n```text\nportrait\n```\n\n```text\nportrait\n```\n\n```text\nheight.viewport <= 133% of width.viewport\n```\n\n```text\nviewport\n```\n\n```text\nheight\n```\n\n```text\nwidth\n```\n\n```text\nviewport.width*1.33 <= viewport.height\n```\n\n```text\n<script>\n let innerWidth = 0\n let innerHeight = 0\n \n $: condition = innerWidth*1.33 <= innerHeight\n</script>\n\n<svelte:window bind:innerWidth bind:innerHeight />\n\n<p> Inner Width: {innerWidth} </p>\n<p> Inner Height: {innerHeight} </p>\n<p> condition: {condition} </p>\n\n<img src=\"https://svelte.dev/svelte-logo-horizontal.svg\" alt=\"\"\n class=\"image-basic\"\n class:image-conditional={condition}\n />\n\n<style>\n .image-basic {\n width: 100vw;\n }\n .image-conditional {\n width: 50vw;\n }\n\n</style>\n```\n\n```text\n<svelte:window>\n```\n\n```text\nlet innerHeight = 0\n```\n\n```text\n$:\n```\n\n```text\n$:\n```\n\n```text\ntrue\n```\n\n```text\nfalse\n```\n\n```text\nclass:\n```\n\n```text\ntrue\n```\n\n```text\n<style>\n```\n\n========================================\n\nComments:\n- It's possible to bind the windows width and height by using the special `svelte:window` component. Here is an example: svelte.dev/tutorial/svelte-window-bindings\n- @johannchopin Tried using it, having the above issue\n- I had to reverse the condition to `condition = outerWidth*1.33 >= outerHeight` to get the desired result weird.\n- You should start a tutorial on YouTube for svelte, to make it easy for beginners. At least the basics part, if the official or unofficial examples were simple enough for a new person like me to understand, I wouldn't have posted it here.\n- @SanthoshDhaipuleChandrakanth I prefer helping out with concrete problems :) And while I agree, that some examples might be a bit more complex than they probably need to and so are maybe not completely beginner friendly, the official tutorial is still a very good place to learn Svelte. Just check back now and then and things will become clearer with time... (that's what I experienced)","metadata":{"transformedAt":"2026-08-18T18:33:40.694Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":236,"estimatedTokens":1390}}485{"id":"stack-65162885","source":"stackoverflow","questionId":65162885,"title":"Cannot find module './SLink.svelte' or its corresponding type declarations","tags":["typescript","jestjs","svelte"],"text":"Title: Cannot find module './SLink.svelte' or its corresponding type declarations\nTags: typescript, jestjs, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to configure Jest with Svelte and TypeScript in an existing project.\n\nI've setup everything as per this article (using Babel and ts-jest).\n\nWhen I run the test I get this:\n\n```\nFAIL src/tests/methods.test.ts\n ● Test suite failed to run\n\n src/router/components/index.ts:1:19 - error TS2307: Cannot find module './SLink.svelte' or its corresponding type declarations.\n\n 1 import SLink from './SLink.svelte';\n ~~~~~~~~~~~~~~~~\n\nTest Suites: 1 failed, 1 total\nTests: 0 total\nSnapshots: 0 total\nTime: 2.705 s\nRan all test suites.\nnpm ERR! Test failed. See above for more details.\n```\n\nI have other components being imported that don't throw this error, the only difference being that `SLink` is imported into a regular `.ts` file while my other components are imported into other components (with the exception of `App.svelte`).\n\nIf I change the export to an empty string, it goes through the test as it should (though, it still throws an error that this component can't be rendered).\n\nThis SO post suggests adding `@tsconfig/svelte`, which I've already done.\n\nIf I add `// @ts-ignore` above the import, it works exactly as it should, but, is there another way around this?\n\n### Relevant code:\n\n**src/tests/methods.test.ts:**\n\n```\nimport { render } from '@testing-library/svelte';\nimport App from '../App.svelte';\n\ntest('should render', () => {\n const results = render(App);\n\n expect(() => results.getByText('Hello world!')).not.toThrow();\n});\n```\n\n**src/router/components/index.ts:**\n\n```\nimport SLink from './SLink.svelte';\n\nexport { SLink };\n```\n\n`SLink` is an ordinary Svelte component that **doesn't** use TypeScript.\n\n**jest.config.js:**\n\n```\nmodule.exports = {\n preset: 'ts-jest',\n clearMocks: true,\n coverageDirectory: 'coverage',\n transform: {\n '^.+\\\\.svelte$': [\n 'svelte-jester',\n {\n preprocess: true,\n },\n ],\n '^.+\\\\.ts$': 'ts-jest',\n '^.+\\\\.js$': 'babel-jest',\n },\n moduleFileExtensions: ['js', 'ts', 'svelte'],\n};\n```\n\n**babel.config.js:**\n\n```\nmodule.exports = {\n presets: [\n ['@babel/preset-env', { targets: { node: 'current' } }],\n '@babel/preset-typescript',\n ],\n};\n```\n\n**svelte.config.js:**\n\n```\nimport sveltePreprocess from 'svelte-preprocess';\n\nmodule.exports = {\n preprocess: sveltePreprocess(),\n};\n```\n\n**File tree:**\n\n```\nsrc\n|_ tests\n |_ methods.test.ts\n|_ router\n |_ components\n |_ index.ts\n |_ SLink.svelte\n```\n\n========================================\n\nCode:\n```sh\nFAIL src/tests/methods.test.ts\n ● Test suite failed to run\n\n src/router/components/index.ts:1:19 - error TS2307: Cannot find module './SLink.svelte' or its corresponding type declarations.\n\n 1 import SLink from './SLink.svelte';\n ~~~~~~~~~~~~~~~~\n\nTest Suites: 1 failed, 1 total\nTests: 0 total\nSnapshots: 0 total\nTime: 2.705 s\nRan all test suites.\nnpm ERR! Test failed. See above for more details.\n```\n\n```text\nimport { render } from '@testing-library/svelte';\nimport App from '../App.svelte';\n\ntest('should render', () => {\n const results = render(App);\n\n expect(() => results.getByText('Hello world!')).not.toThrow();\n});\n```\n\n```text\nimport SLink from './SLink.svelte';\n\nexport { SLink };\n```\n\n```text\nmodule.exports = {\n preset: 'ts-jest',\n clearMocks: true,\n coverageDirectory: 'coverage',\n transform: {\n '^.+\\\\.svelte$': [\n 'svelte-jester',\n {\n preprocess: true,\n },\n ],\n '^.+\\\\.ts$': 'ts-jest',\n '^.+\\\\.js$': 'babel-jest',\n },\n moduleFileExtensions: ['js', 'ts', 'svelte'],\n};\n```\n\n```text\nmodule.exports = {\n presets: [\n ['@babel/preset-env', { targets: { node: 'current' } }],\n '@babel/preset-typescript',\n ],\n};\n```\n\n```text\nimport sveltePreprocess from 'svelte-preprocess';\n\nmodule.exports = {\n preprocess: sveltePreprocess(),\n};\n```\n\n```text\nsrc\n|_ tests\n |_ methods.test.ts\n|_ router\n |_ components\n |_ index.ts\n |_ SLink.svelte\n```\n\n```text\nSLink\n```\n\n```text\n.ts\n```\n\n```text\nApp.svelte\n```\n\n```text\n@tsconfig/svelte\n```\n\n```text\n// @ts-ignore\n```\n\n```text\nSLink\n```\n\n```json\n{\n \"extends\": \"@tsconfig/svelte/tsconfig.json\",\n // ...\n \"compilerOptions\": {\n \"types\": [\"node\", \"jest\"]\n }\n}\n```\n\n```text\n(!) Plugin typescript: @rollup/plugin-typescript TS2307: Cannot find module './App.svelte' or its corresponding type declarations.\n```\n\n```json\n{\n // ...\n \"compilerOptions\": {\n \"types\": [\"node\", \"svelte\", \"jest\"]\n }\n}\n```\n\n```text\ncompilerOptions\n```\n\n```text\n.ts\n```\n\n```text\n\"svelte\"\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.694Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":256,"estimatedTokens":1161}}486{"id":"stack-72168054","source":"stackoverflow","questionId":72168054,"title":"Svelte only supports es6+ syntax. Set your 'compilerOptions.target' to 'es6' or higher","tags":["javascript","typescript","svelte","rollup","transpiler"],"text":"Title: Svelte only supports es6+ syntax. Set your 'compilerOptions.target' to 'es6' or higher\nTags: javascript, typescript, svelte, rollup, transpiler\nSource: Stack Overflow\n\nQuestion:\nI have been using Svelte, TypeScript and Rollup (letting TypeScript handle the transpilation) to target ES7. Now I'm starting a new project and need to target ES5.\n\nThe first thing I have noticed is that everything gets transpiled but the components are still classes. I didn't have any scripts in the components at that point. Once I added a script tag to .svelte file, I immediately got the error:\n\nSvelte only supports es6+ syntax. Set your 'compilerOptions.target' to 'es6' or higher\n\nI understand that I will need to set TS target to ES6/ES7 and install Rollup Babel plugin to handle the transpilation to ES5. But why would plain TypeScript transpilation not work? Why does Svelte care about TypeScript target? You'd think that Svelte files get converted to TS before being transpiled to ES5, but it seems like it's the other way around?\n\n========================================\n\nCode:\n```text\nTS => JS 6+ =Svelte=> JS 6+ => JS 5\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.694Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":19,"estimatedTokens":281}}487{"id":"stack-60208157","source":"stackoverflow","questionId":60208157,"title":"I want to deploy back-end and front-end seperate apps on the same server with nginx","tags":["node.js","nginx","svelte","sapper"],"text":"Title: I want to deploy back-end and front-end seperate apps on the same server with nginx\nTags: node.js, nginx, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI've created a restful api with nodejs and I'm planning to use sapper/svelte for front-end. In the end, these will be seperate apps and I want to run them on the same server with same domain. Is this approach reasonable? If it is, what should my nginx configuration file look like? If not, what should be my approach? \n\nThis my conf for api: \n\n```\nserver {\n server_name domain.name;\n\n location / {\n proxy_pass http://localhost:5000;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection 'upgrade';\n proxy_set_header Host $host;\n proxy_cache_bypass $http_upgrade;\n }\n .\n .\n .\n}\n```\n\n========================================\n\nTop Answer:\nSince this is your first svelte / sapper project, I would keep things separate and see if you can get started with svelte to hit the API on nginx. Decouple things and ship svelte on gitlab pages or whatever other CI destination you prefer.\n\nIf it comes time to run with sapper, my advice remains the same - have it hit your API externally to keep your projects clear and distinct. You already launched the API before the front end - no worries, but I don’t see how your config needs to know where the front end will run or why entwining them would be beneficial.\n\n========================================\n\nCode:\n```text\nserver {\n server_name domain.name;\n\n location / {\n proxy_pass http://localhost:5000;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection 'upgrade';\n proxy_set_header Host $host;\n proxy_cache_bypass $http_upgrade;\n }\n .\n .\n .\n}\n```\n\n```text\nserver {\n server_name domain.name;\n\n location /api/ { # Backend\n proxy_pass http://localhost:5000;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection 'upgrade';\n proxy_set_header Host $host;\n proxy_cache_bypass $http_upgrade;\n\n ...\n }\n\n location / { # Frontend\n root /app-path/;\n index index.html;\n try_files $uri $uri/ /index.html;\n\n ...\n }\n}\n```\n\n========================================\n\nComments:\n- why two apps? Sapper is already doing backend and frontend. You may as well put your api in sapper server routes. Or you could export your sapper app as static to lose the server part.\n- I've already created the api. I was thinking about vue or react for a frontend but then I've come across sapper. It'll be my first project with svelte. I liked the idea of server side rendering for SEO purposes. So, no static export. Maybe I might try to merge it. But is it difficult to configure nginx for double app single domain?\n- No, you can do that with nginx. It just feels bloated. You could instead use a plain svelte site or use a different static router for the frontend. Maybe you join the discord chat for more details.\n- Why the location block for the frontend doesn't have any proxy related configurations?\n- @Ulvi this is just an example, you can always add proxy_pass to that block, if the frontend is deployed in another process/port.","metadata":{"transformedAt":"2026-08-18T18:33:40.695Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":88,"estimatedTokens":825}}488{"id":"stack-66371140","source":"stackoverflow","questionId":66371140,"title":"How to use MathJax in a svelte project?","tags":["svelte","mathjax"],"text":"Title: How to use MathJax in a svelte project?\nTags: svelte, mathjax\nSource: Stack Overflow\n\nQuestion:\nI am working on a svelte text editor project in svelte , the code is very simple (REPL) :\n\n```\n\n let rawText\n let formatText = (text)=>{\n // Text Formating\n return text\n }\n $: formatedText = formatText(rawText)\n\n{#if formatedText}\n {formatedText}\n{/if}\n```\n\nI need to be able to write math equations.\n\nTo do so I have found MathJax but I can't find a clean way to import it into my svelte app\n\nI have tried multiples approach like\n\n### the npm way :\n\nusing :\n\n```\nnpm i mathjax\n```\n\nand on the svelte component :\n\n```\nimport MathJax from 'mathjax'\n```\n\nBut when I do this the app turn white without any error\n\n### The svelte:head way :\n\nThe second solution I tried was to import MathJax from a cdn in a script tag like that :\n\n```\n\n \n \n\n```\n\nAnd it kinda works because I can access MathJax functions in the browser console but I don't know to use them in my svelte app\n\ncapture\n\n### The hacky way :\n\nThe last solution I have found in this example leads to the same problem.\n\nSo my question is how to import mathjax in my svelte project or can I use something else?\n\n========================================\n\nTop Answer:\nIn addition to @Luis' answer, if you see that Mathjax is flaky, add this to your page component.\n\n```\nafterNavigate(() => MathJax.Hub.Queue(['Typeset', MathJax.Hub]));\n```\n\nThis will rerender Mathjax on navigation to the page.\n\n========================================\n\nCode:\n```html\n<script>\n let rawText\n let formatText = (text)=>{\n // Text Formating\n return text\n }\n $: formatedText = formatText(rawText)\n</script>\n\n<textarea bind:value={rawText}></textarea>\n{#if formatedText}\n {formatedText}\n{/if}\n```\n\n```text\nnpm i mathjax\n```\n\n```js\nimport MathJax from 'mathjax'\n```\n\n```html\n<svelte:head>\n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script\n id=\"MathJax-script\"\n async\n src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js\"></script>\n</svelte:head>\n```\n\n```text\n// Thanks to https://github.com/dpvc\n<script>\nMathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n};\n</script>\n<script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n```\n\n```text\n# Svelte file\n<script lang=\"ts\">\n let equ = `$$x = \\\\frac{t}{3}$$`;\n</script>\n<main>\n {equ}\n</main>\n```\n\n```text\napp/public/index.html\n```\n\n```text\nindex.html\n```\n\n```text\nafterNavigate(() => MathJax.Hub.Queue(['Typeset', MathJax.Hub]));\n```\n\n========================================\n\nComments:\n- Have you tried adding `` to your `App.svelte` component?\n- No, where do I need to write this? I have found this example on the doc but can't figure out how it works","metadata":{"transformedAt":"2026-08-18T18:33:40.695Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":149,"estimatedTokens":699}}489{"id":"stack-76153910","source":"stackoverflow","questionId":76153910,"title":"How define an optional prop in svelte with typescript?","tags":["typescript","svelte"],"text":"Title: How define an optional prop in svelte with typescript?\nTags: typescript, svelte\nSource: Stack Overflow\n\nQuestion:\nI want to declare an optional prop in svelte with typescript, but I get the following error: \"Declaration or statement expected\". How can I declare the prop correctly?\n\nMy Type\n\n```\nexport enum MyVariants {\n one = 'one',\n two = 'two'\n}\n```\n\nSvelte component\n\n```\n\n export let variant?: MyVariants;\n\n```\n\nError:\n\n```\nts Declaration or statement expected\n```\n\n========================================\n\nTop Answer:\nIt is an optional property if you give it a default value.\n\n```\nexport let variant: MyVariants | undefined = undefined;\n```\n\n========================================\n\nCode:\n```text\nexport enum MyVariants {\n one = 'one',\n two = 'two'\n}\n```\n\n```text\n<script lang=\"ts\">\n export let variant?: MyVariants;\n</script>\n```\n\n```text\nts Declaration or statement expected\n```\n\n```html\n<script lang=\"ts\">\n export let variant: MyVariants | undefined = undefined;\n</script>\n```\n\n```typescript\ntype Optional<T> = T | undefined;\n```\n\n```html\n<script lang=\"ts\">\n export let variant: Optional<MyVariants> = undefined;\n</script>\n```\n\n```html\n<script lang=\"ts\">\n export let variant: Optional<MyVariants> = void 0;\n</script>\n```\n\n```typescript\nfunction optional<T>(): T | undefined {\n return undefined;\n}\n```\n\n```html\n<script>\nlet variant = optional<MyVariants>();\n</script>\n```\n\n```text\nundefined\n```\n\n```text\nundefined\n```\n\n```text\nundefined\n```\n\n```text\nvoid 0\n```\n\n```text\nundefined\n```\n\n```html\nexport let variant: MyVariants | undefined = undefined;\n```\n\n```text\n<script lang=\"ts\">\n export let item: MyVariant;\n</script>\n```\n\n========================================\n\nComments:\n- At least closely related: stackoverflow.com/questions/62405066/…\n- Ah cool it works, but not very efficient, that I always have to write \"undefined\"\n- @vuvu - Yeah. :-| There are things you can do to make it a bit shorter (give yourself a reusable `Optional` type and then `let variant: Optional = void 0;`), but...\n- @vuvu - I've added a couple of thoughts to the answer. Happy coding!\n- It doesn't seem right. Your IDE is probably misconfigured and not showing typescript errors properly. If you're using vite for development, then you should note that it doesn't perform any type checking (leaving this job to your IDE). More info here: vitejs.dev/guide/features#typescript","metadata":{"transformedAt":"2026-08-18T18:33:40.695Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":131,"estimatedTokens":598}}490{"id":"stack-62374265","source":"stackoverflow","questionId":62374265,"title":"Svelte with leaflet","tags":["leaflet","svelte"],"text":"Title: Svelte with leaflet\nTags: leaflet, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to find my way into Svelte combined with leaflet. Where I'm stuck is how to correctly split the leaflet components into files. For learning, I'm trying to build the official official leaflet quickstart with svelte. \n\nThis is how my app.svelte looks like:\n\n```\n\n import L from 'leaflet';\n import { onMount } from \"svelte\";\n import { Circle } from \"./components/Circle.svelte\";\n\n let map;\n\n onMount(async () => {\n map = L.map(\"map\");\n\n L.tileLayer(\"https://a.tile.openstreetmap.org/{z}/{x}/{y}.png \", {\n attribution:\n 'Map data © OpenStreetMap contributors, CC-BY-SA',\n maxZoom: 18,\n tileSize: 512,\n zoomOffset: -1\n }).addTo(map);\n\n map.setView([51.505, -0.09], 13);\n Circle.addTo(map);\n\n });\n\n html,body {\n padding: 0;\n margin: 0;\n }\n html, body, #map {\n height: 100%;\n width: 100vw;\n }\n\n \n\n```\n\nand my circle component:\n\n```\n\n import L from 'leaflet';\n export let map_obj;\n\n export let Circle = L.circle([51.508, -0.11], {\n color: \"red\",\n fillColor: '#f03',\n fillOpacity: 0.5,\n radius: 500\n });\n\n```\n\nWhile this is working I do not think it's effective to consider every component and add it to the map with `Circle.addTo(map);`. How could I pass in the map object to the circle component or is there some better pattern to build the map with several components?\n\nNote: I do know of svelte/leaflet but like to start from scratch for learning.\n\n========================================\n\nCode:\n```text\n<script>\n import L from 'leaflet';\n import { onMount } from \"svelte\";\n import { Circle } from \"./components/Circle.svelte\";\n\n let map;\n\n onMount(async () => {\n map = L.map(\"map\");\n\n L.tileLayer(\"https://a.tile.openstreetmap.org/{z}/{x}/{y}.png \", {\n attribution:\n 'Map data © <a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors, <a href=\"https://creativecommons.org/licenses/by-sa/2.0/\">CC-BY-SA</a>',\n maxZoom: 18,\n tileSize: 512,\n zoomOffset: -1\n }).addTo(map);\n\n map.setView([51.505, -0.09], 13);\n Circle.addTo(map);\n\n });\n</script>\n\n<style>\n html,body {\n padding: 0;\n margin: 0;\n }\n html, body, #map {\n height: 100%;\n width: 100vw;\n }\n</style>\n\n<svelte:head>\n <link\n rel=\"stylesheet\"\n href=\"https://unpkg.com/leaflet@1.6.0/dist/leaflet.css\"\n integrity=\"sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==\"\n crossorigin=\"\" />\n</svelte:head>\n\n<div id=\"map\" />\n```\n\n```text\n<script context=\"module\">\n import L from 'leaflet';\n export let map_obj;\n\n export let Circle = L.circle([51.508, -0.11], {\n color: \"red\",\n fillColor: '#f03',\n fillOpacity: 0.5,\n radius: 500\n });\n</script>\n```\n\n```text\nCircle.addTo(map);\n```\n\n```text\n<script>\n import L from 'leaflet';\n import { getContext } from \"svelte\";\n\n export let lat = 0;\n export let lng = 0;\n\n let map = getContext('leafletMapInstance');\n\n L.marker([lat, lng]).addTo(map);\n</script>\n```\n\n```text\n<script>\n import LeafletMap from './LeafletMap.svelte'\n import LeafletMarker from './LeafletMarker.svelte'\n</script>\n\n<LeafletMap>\n <LeafletMarker lat=40 lng=-3></LeafletMarker>\n <LeafletMarker lat=60 lng=10></LeafletMarker>\n</LeafletMap>\n```\n\n```text\nlet map = L.map(L.DomUtil.create('div')\n```\n\n```text\nimport { setContext } from \"svelte\";\nsetContext('leafletMapInstance', map);\n```\n\n```text\n<div class='map' bind:this={mapContainer}>\n```\n\n```text\nlet mapContainer;\nonMount(function() {\n mapContainer.appendChild(map.getContainer());\n map.getContainer().style.width = '100%';\n map.getContainer().style.height = '100%';\n map.invalidateSize();\n});\n```\n\n```text\n<script>\n import L from \"leaflet\";\n import { setContext, onMount } from \"svelte\";\n\n let mapContainer;\n let map = L.map(L.DomUtil.create(\"div\"), {\n center: [0, 0],\n zoom: 0,\n });\n setContext(\"leafletMapInstance\", map);\n console.log(\"map\", map);\n\n L.tileLayer(\"https://a.tile.openstreetmap.org/{z}/{x}/{y}.png \", {\n attribution:\n 'Map data © <a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors, <a href=\"https://creativecommons.org/licenses/by-sa/2.0/\">CC-BY-SA</a>',\n }).addTo(map);\n\n onMount(() => {\n mapContainer.appendChild(map.getContainer());\n map.getContainer().style.width = \"100%\";\n map.getContainer().style.height = \"100%\";\n map.invalidateSize();\n });\n</script>\n<svelte:head>\n <link\n rel=\"stylesheet\"\n href=\"https://unpkg.com/leaflet@1.6.0/dist/leaflet.css\"\n integrity=\"sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==\"\n crossorigin=\"\"\n />\n</svelte:head>\n<style>\n .map {\n height: 100vh;\n width: 100vw;\n }\n</style>\n<div class=\"map\" bind:this=\"{mapContainer}\">\n <slot></slot>\n</div>\n```\n\n```text\nsetContext\n```\n\n```text\ngetContext\n```\n\n```text\nL.Map\n```\n\n```text\nL.Marker\n```\n\n```text\nL.Map\n```\n\n```text\ngetContext\n```\n\n```text\nL.Marker\n```\n\n```text\nL.Map\n```\n\n```text\nL.Map\n```\n\n```text\nonRender\n```\n\n```text\nonRender\n```\n\n```text\nL.Map\n```\n\n```text\nL.Map\n```\n\n```text\nL.Map\n```\n\n```text\nL.Map\n```\n\n========================================\n\nComments:\n- really nice answer, thanks a lot @IvanSanchez ! just one question. The marker do not show up in your example?\n- That's a side effect of github.com/Leaflet/Leaflet/issues/4968 , a bug that tends to show up whenever the Leaflet code undergoes bundling.\n- ahhh correct, I do see the 404 . Wow bad , this would have cost me hours. thanks again!\n- Really nice @IvanSanchez ! Given the difficulties with Leaflet, what would be a recommended mapping framework to use together with Svelte ?","metadata":{"transformedAt":"2026-08-18T18:33:40.695Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":25,"totalLines":294,"estimatedTokens":1435}}491{"id":"stack-53501707","source":"stackoverflow","questionId":53501707,"title":"Best practice to expose and call methods from svelte component","tags":["svelte","svelte-component"],"text":"Title: Best practice to expose and call methods from svelte component\nTags: svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI built a simple Banner component which is imported in _layout.html. It exposes 5 methods (dismiss, info, warning, ...).\n\nCurrently I'm using the store to keep track of these methods as in _layout.html below.\n\n_layout.html\n\n```\n\n \n \n\n export default {\n components: {\n Banner: '../components/Banner.html',\n },\n\n oncreate() {\n this.store.set({\n Banner: {\n dismiss: this.refs.banner.dismiss,\n danger: this.refs.banner.danger,\n info: this.refs.banner.info,\n success: this.refs.banner.success,\n warning: this.refs.banner.warning\n }\n })\n }\n }\n```\n\nSo I can call them from any part of the app like so:\n\nblog.html\n\n```\n... \n this.store.get().Banner.success('Post saved!') \n} catch (err) {\n this.store.get().Banner.danger(err)\n}\n...\n```\n\nThis is working fine however I wonder if this is the best Svelte way to do it.\n\n========================================\n\nCode:\n```text\n<main>\n <Banner ref:banner/>\n <svelte:component this={child.component} {...child.props} />\n</main>\n\n<script>\n export default {\n components: {\n Banner: '../components/Banner.html',\n },\n\n oncreate() {\n this.store.set({\n Banner: {\n dismiss: this.refs.banner.dismiss,\n danger: this.refs.banner.danger,\n info: this.refs.banner.info,\n success: this.refs.banner.success,\n warning: this.refs.banner.warning\n }\n })\n }\n }\n```\n\n```text\n... \n this.store.get().Banner.success('Post saved!') \n} catch (err) {\n this.store.get().Banner.danger(err)\n}\n...\n```\n\n```text\noncreate() {\n Object.assign(this, this.refs.banner);\n //or assign the exposed methods to the root component in any way\n}\n\n...\nthis.root.success('Post saved!');\n...\n```\n\n========================================\n\nComments:\n- I think this question is outdated, ref:xxx seems to be no longer supported in svelte 3:The ref directive is no longer supported — use `bind:this={xxx}, perhaps a tag wih svelte 2 (or whatever this question applies to) should be added","metadata":{"transformedAt":"2026-08-18T18:33:40.695Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":103,"estimatedTokens":556}}492{"id":"stack-64102150","source":"stackoverflow","questionId":64102150,"title":"How is Svelte using the 'this' keyword in this scenario?","tags":["javascript","dom","events","this","svelte"],"text":"Title: How is Svelte using the 'this' keyword in this scenario?\nTags: javascript, dom, events, this, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm going through the tutorial for Svelte and came upon this example, and am confused as to how this is working. (I cut out some other code not relevant to question, full example here: https://svelte.dev/tutorial/tick)\n\n```\n\n async function handleKeydown(event) {\n const { selectionStart, selectionEnd, value } = this;\n\n await tick();\n this.selectionStart = selectionStart;\n this.selectionEnd = selectionEnd;\n }\n\n```\n\nCould someone please explain the logic of how 'this' is being used here? I don't understand how it knows to reference the value within the textarea. Does it have something to do with the function being called by the textarea and creating a context within the function referencing the textarea element?\n\nAnd also why something like the code below does not work? (console log's undefined)\n\n```\nfunction logger(event) {\n console.log(event.value)\n}\n```\n\n========================================\n\nCode:\n```text\n<script>\n async function handleKeydown(event) {\n const { selectionStart, selectionEnd, value } = this;\n\n await tick();\n this.selectionStart = selectionStart;\n this.selectionEnd = selectionEnd;\n }\n</script>\n\n<textarea value={text} on:keydown={handleKeydown}></textarea>\n```\n\n```text\nfunction logger(event) {\n console.log(event.value)\n}\n```\n\n```text\nthis\n```\n\n```text\nthis\n```\n\n```text\nthis\n```\n\n```text\non:keydown={handleKeydown}\n```\n\n========================================\n\nComments:\n- About your final paragraph? How do you call `logger`?\n- Could you provide feed-back?\n- Sorry about that, thank you this makes a lot of sense! Appreciate you taking the time to answer!\n- Also regarding the logger function, I was calling it the same way as handleKeydown above, with on:keydown. But i was getting 'undefined' as the console.","metadata":{"transformedAt":"2026-08-18T18:33:40.695Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":75,"estimatedTokens":478}}493{"id":"stack-70967483","source":"stackoverflow","questionId":70967483,"title":"SvelteKit: Cannot reference store value inside","tags":["svelte","sveltekit","svelte-store"],"text":"Title: SvelteKit: Cannot reference store value inside\nTags: svelte, sveltekit, svelte-store\nSource: Stack Overflow\n\nQuestion:\nSvelteKit / Svelte : Not able to get or set (Read or Write) values from the \"store\" in the context module.\n\n```\nimport {selectedStore} from \"src/storelocation\";\n\n export const load = async ({params})=> {\n \n $selectedStore.value // throwing error\n }\n```\n\n========================================\n\nCode:\n```text\nimport {selectedStore} from \"src/storelocation\";\n\n<script context=\"module\">\n export const load = async ({params})=> {\n \n $selectedStore.value // throwing error\n }\n```\n\n```text\nimport {selectedStore} from \"src/storelocation\";\nimport { get } from 'svelte/store';\n\n<script context=\"module\">\nexport const load = async ({params})=> {\n\n // use this\n get(selectedStore).value;\n}\n```\n\n========================================\n\nComments:\n- Thank you for you answer. Would you mind explaining why this is the case or pointing me somewhere to find out?\n- @BlaviButcher If I understand correctly, the reason is because Variables defined in module scripts are not reactive, therefore you can't access stores using reactive notation (`$mystore`) but manually calling store methods is ok (`mystore.set(…)` and `get(mystore).value`). Here's a github issue with an example.","metadata":{"transformedAt":"2026-08-18T18:33:40.695Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":46,"estimatedTokens":326}}494{"id":"stack-70059159","source":"stackoverflow","questionId":70059159,"title":"How to remove `href` attribute from link with Svelte? Should this be enough?","tags":["svelte","svelte-3"],"text":"Title: How to remove `href` attribute from link with Svelte? Should this be enough?\nTags: svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nAm I wrong or this should remove `href` attribute from the `a` tag?\n\n```\n\n```\n\nIt doesn't (\"svelte\": \"3.44.2\").\n\n========================================\n\nTop Answer:\nUse `null` and it will deactivate the hyperlink and won't go anywhere.\nOr you can add `on:click|preventDefault` to the anchor.\n\n```\nlink\n```\n\n========================================\n\nCode:\n```html\n<a href={false}></a>\n```\n\n```text\nhref\n```\n\n```text\na\n```\n\n```html\n<a href={null}>linkText</a>\n<a href={undefined} >linkText</a>\n```\n\n```text\nhref=\n```\n\n```text\nfalse\n```\n\n```text\nnull/undefined\n```\n\n```text\n<a href={null} on:click|preventDefault>link</a>\n```\n\n```text\nnull\n```\n\n```text\non:click|preventDefault\n```\n\n========================================\n\nComments:\n- You chose a later answer as the correct answer while its exactly the same.","metadata":{"transformedAt":"2026-08-18T18:33:40.695Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":71,"estimatedTokens":238}}495{"id":"stack-75975695","source":"stackoverflow","questionId":75975695,"title":"Svelte: how to pass `on:` event to a child component","tags":["javascript","svelte","sveltekit"],"text":"Title: Svelte: how to pass `on:` event to a child component\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI want to create a component that will handle `on:click`, but without exporting an `handleClick` function; this is how it works right now\n\n`button.svelte`:\n\n```\n\n export let handleClick: ((e: MouseEvent) => void ) | undefined = undefined\n\n \n\n```\n\n`app.svelte`:\n\n```\n\n import Button from '$lib/button/button.svelte'\n\n console.log('click!')}>\n Click me!\n\n```\n\nHow to change the Button element to use `on:click` directly in the app component?\n\n`app.svelte`:\n\n```\n\n \n\n```\n\n========================================\n\nCode:\n```html\n<script lang=\"ts\">\n export let handleClick: ((e: MouseEvent) => void ) | undefined = undefined\n</script>\n<button on:click={handleClick}>\n <slot></slot>\n</button>\n```\n\n```html\n<script lang=\"ts\">\n import Button from '$lib/button/button.svelte'\n</script>\n<Button handleClick={() => console.log('click!')}>\n Click me!\n</button>\n```\n\n```html\n<Button on:click={handleClick}>\n <slot></slot>\n</Button>\n```\n\n```text\non:click\n```\n\n```text\nhandleClick\n```\n\n```text\nbutton.svelte\n```\n\n```text\napp.svelte\n```\n\n```text\non:click\n```\n\n```text\napp.svelte\n```\n\n```html\n<button on:click>\n <slot></slot>\n</button>\n```\n\n```html\n<script>\nimport Button from './button.svelte';\n\nconst handleClick = (event) => {\n // …\n};\n</script>\n\n<Button on:click={handleClick}>\n Foo\n</Button>\n```\n\n```text\non:\n```\n\n```text\nbutton.svelte\n```\n\n```text\napp.svelte\n```\n\n========================================\n\nComments:\n- Thank you! Will be more patient during reading the docs next time\n- Any way to forward all event without specify all the required events?","metadata":{"transformedAt":"2026-08-18T18:33:40.695Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":126,"estimatedTokens":421}}496{"id":"stack-71705998","source":"stackoverflow","questionId":71705998,"title":"Is there a way to create a NeutralinoJS project based on Svelte and Typescript?","tags":["typescript","svelte","neutralinojs"],"text":"Title: Is there a way to create a NeutralinoJS project based on Svelte and Typescript?\nTags: typescript, svelte, neutralinojs\nSource: Stack Overflow\n\nQuestion:\nI need to create a neutralino+svelte+ts project, I've noted it was possible in old version (neutralino-cli@1.8.1) but nothing similar is described in newest version of neutralino. I've tried to run in latest neutralino version the same command described in version `1.8.1` (`neu create myapp --template svelte`) but I received the error:\n\n`neu: ERROR Unable to download resources from internet. Please check your internet connection and template URLs.`\n\nI've tried with different type of template (`ts` and `js`) and I had the same result.\n\nI've tried also by running the command `neu create myapp --template neutralinojs/neutralinojs-svelte` (same error).\n\nAny idea how to do it?\n\n========================================\n\nCode:\n```text\n1.8.1\n```\n\n```text\nneu create myapp --template svelte\n```\n\n```text\nneu: ERROR Unable to download resources from internet. Please check your internet connection and template URLs.\n```\n\n```text\nts\n```\n\n```text\njs\n```\n\n```text\nneu create myapp --template neutralinojs/neutralinojs-svelte\n```\n\n```text\n.gitignore\n```\n\n```text\n.gitignore-neu\n```\n\n```text\nreadme.md\n```\n\n```text\nreadme-neu.md\n```\n\n```text\npublic\n```\n\n```text\nresources\n```\n\n```text\nnpm install\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run build\n```\n\n```text\n.gitignore-neu\n```\n\n```text\n.gitignore\n```\n\n```text\n/neutralino.config.json\n```\n\n```text\n\"documentRoot\":\"/resources/\"\n```\n\n```text\n\"documentRoot\":\"/public/\"\n```\n\n```text\nnpm run dev\n```\n\n```text\nneu run\n```\n\n```text\n/src\n```\n\n```text\nnpm run build\n```\n\n```text\nneu build\n```\n\n```text\n/resources/js/neutralino.js\n```\n\n```text\n/public/\n```\n\n```text\n<script src=\"/neutralino.js\"></script>\n```\n\n```text\n<head>\n```\n\n```text\n/public/index.html\n```\n\n```text\n<script defer src='/build/bundle.js'></script>\n```\n\n```text\nNeutralino.init();\n```\n\n```text\n/src/main.js\n```\n\n========================================\n\nComments:\n- Thanks for your answer and welcome to stackoverflow, do you know if there is a way to use typescript in the project?\n- I have the same need as @Raffaele: Neu + Svelte + TS. I need the Neu API. I added `` to the `` block of `/public/index.html`, however, adding `Neutralino.init()` to `main.ts` fails, as TS cannot find `Neutralino`. Should I import it from somewhere? … You also mention to install *Neutralino Typescrip app at step 1*, but don’t mention from where. Could you add this info please? Thanks!\n- I solved it by installing `neutralinojs-types` NPM package and adding `import 'neutralinojs-types'` before `app` variable definition and `Neutralino.init()` after it and before `export default app`, all in `main.ts`.","metadata":{"transformedAt":"2026-08-18T18:33:40.695Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":33,"totalLines":156,"estimatedTokens":692}}497{"id":"stack-68220955","source":"stackoverflow","questionId":68220955,"title":"how does svelte unsubscribe actually work?","tags":["svelte","svelte-3","svelte-store"],"text":"Title: how does svelte unsubscribe actually work?\nTags: svelte, svelte-3, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI can subscribe to a store like this:\n\n```\ncount.subscribe(value => {\n count_value = value;\n});\n```\n\nbut when we want to unsubscribe we will put the previous subscribe code into a new variable (becomes a function expression) and run it only when the component is destroyed (`onDestroy`)\n\n```\nconst unsubscribe = count.subscribe(value => {\n count_value = value;\n});\n\nonDestroy(unsubscribe);\n```\n\nthe question is, how about just putting the previous function into a new variable called unsubscribe. can perform the unsubscribe function to the store. I mean we don't even change the subscribe code at all for the unsubscribe implementation, all we do is put it in a new variable so it becomes a function expression and only call it via `onDestroy`, then how can it magically unsubscribe? how does it actually work?\n\n========================================\n\nTop Answer:\nbut when we want to unsubscribe we will put the previous subscribe code into a new variable\n\nThat's not what is happening here. The function is not assigned to the `unsubscribe` variable; its return value is another function.\n\nImagine `subscribe` as something like this:\n\n\r\n\r\n\n```\nconst subscribe = (callback) => {\n callback('the stored value')\n\n const unsubscribe = () => {\n // do all the stuffs to unsubscribe here...\n console.log('Your are unsubscribed!')\n }\n\n return unsubscribe\n}\n\nlet count_value\n\n// unsubscribe is now the function returned in the subscribe function\nconst unsubscribe = subscribe(value => {\n count_value = value;\n})\n\nconsole.log(count_value)\n\n// calling this function will log 'You are unsubscribed!' in the console\nunsubscribe()\n```\n\n========================================\n\nCode:\n```js\ncount.subscribe(value => {\n count_value = value;\n});\n```\n\n```js\nconst unsubscribe = count.subscribe(value => {\n count_value = value;\n});\n\nonDestroy(unsubscribe);\n```\n\n```text\nonDestroy\n```\n\n```text\nonDestroy\n```\n\n```js\nstore = { subscribe: (subscription: (value: any) => void) => (() => void), set?: (value: any) => void }\n```\n\n```js\nType subscribe = (subscription: (value: any) => void) => (() => void)\n```\n\n```js\nclass Store {\n constructor(init) {\n this.subscribers = {};\n this.value = init;\n }\n subscribe(callback) {\n callback(this.value);\n const id = Symbol()\n this.subscribers[id] = callback;\n\n return () => delete this.subscribers[id]\n // ^^^ unsubscribe function here ^^^\n\n }\n set(value) {\n this.value = value;\n for (const id of Object.getOwnPropertySymbols(this.subscribers)) {\n this.subscribers[id](value)\n }\n }\n}\n```\n\n```text\nsubscribe\n```\n\n```text\nsvelte/store\n```\n\n```text\n.subscribe\n```\n\n```text\n.subscribe\n```\n\n```text\nsubscribe\n```\n\n```text\nstore.subscribe\n```\n\n```text\nsubscription\n```\n\n```text\n(value: any) => void\n```\n\n```text\n() => void\n```\n\n```js\nconst subscribe = (callback) => {\n callback('the stored value')\n\n const unsubscribe = () => {\n // do all the stuffs to unsubscribe here...\n console.log('Your are unsubscribed!')\n }\n\n return unsubscribe\n}\n\nlet count_value\n\n// unsubscribe is now the function returned in the subscribe function\nconst unsubscribe = subscribe(value => {\n count_value = value;\n})\n\nconsole.log(count_value)\n\n// calling this function will log 'You are unsubscribed!' in the console\nunsubscribe()\n```\n\n```text\nunsubscribe\n```\n\n```text\nsubscribe\n```\n\n========================================\n\nComments:\n- @Mir No problem please don't forget to validate this response so other users can find it more easily.\n- I'm impressed by the quality of this answer. Well done :)","metadata":{"transformedAt":"2026-08-18T18:33:40.695Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":193,"estimatedTokens":932}}498{"id":"stack-61197393","source":"stackoverflow","questionId":61197393,"title":"Use Storybook docs with Svelte","tags":["javascript","svelte","storybook"],"text":"Title: Use Storybook docs with Svelte\nTags: javascript, svelte, storybook\nSource: Stack Overflow\n\nQuestion:\nIt seems like the only proper way to write custom docs content for the Storybook Docs addon is through MDX, implying that it was meant primarily for React. The addon page explicitly lists Svelte as a compatible framework, but no deployment instructions seem to be around.\n\nSuppose I have a simple component:\n`button.svelte`:\n\n```\n\n export let text;\n\n{text}\n```\n\nAnd the respective story, `button.stories.js`:\n\n```\nimport Button from './button.svelte';\n\nexport default {\n title: 'Button',\n};\n\nexport const button = () => ({\n Component: Button,\n props: {\n text: 'press me!',\n },\n});\n```\n\nHow would I go about adding arbitrary markdown documentation with Storybook Docs?\n\n========================================\n\nTop Answer:\nTo Add to @illright answer i got it working with just using an mdx file. After following the setup update the regex in storybook config to match on mdx files as well as js/ts files if using `/\\.stories\\.([jt]s|mdx)$`\n\nThen you can define the stories using jsx style syntax within the mdx file like this.\n\n```\nimport { Story, Preview } from '@storybook/addon-docs/blocks';\nimport {text, withKnobs} from \"@storybook/addon-knobs\";\nimport Avatar from \"@common/avatar/Avatar.svelte\";\n\n# Button\n\nOne can write __proper Markdown__ here, as well as embed stories:\n\n \n {{\n Component: Avatar,\n props: {\n imageUrl: text('Image Url', '/default-profile-image.png'),\n size: text('Size', '2.35rem'),\n },\n }}\n \n\n```\n\nUsing svelte style syntax is something that could be coming in the future, hopefully you could define it something like\n\n```\n\n \n \n \n\n```\n\n========================================\n\nCode:\n```html\n<script>\n export let text;\n</script>\n\n<button on:click>{text}</button>\n```\n\n```js\nimport Button from './button.svelte';\n\nexport default {\n title: 'Button',\n};\n\nexport const button = () => ({\n Component: Button,\n props: {\n text: 'press me!',\n },\n});\n```\n\n```text\nbutton.svelte\n```\n\n```text\nbutton.stories.js\n```\n\n```sh\nyarn add -D react react-is babel-loader\n```\n\n```text\nimport { Story, Preview } from '@storybook/addon-docs/blocks';\n\n# Button\n\nOne can write __proper Markdown__ here, as well as embed stories:\n\n<!-- the IDs can be retrieved from the URL when opening a story -->\n<Preview>\n <Story id=\"button--button\" />\n <Story id=\"button--other\" />\n</Preview>\n\n<!-- or an individual story -->\n<Story id=\"button--flat\" />\n```\n\n```js\nimport Button from './button.svelte';\nimport docs from './docs.mdx'; // add this import\n\nexport default {\n title: 'Button',\n parameters: { // and this parameters section\n docs: {\n page: docs,\n },\n },\n};\n\nexport const button = () => ({\n Component: Button,\n props: {\n text: 'press me!',\n },\n});\n\n// Another story just for demonstration\nexport const other = () => ({\n Component: Button,\n props: {\n text: 'me too!',\n },\n});\n```\n\n```text\n.mdx\n```\n\n```text\n./docs.mdx\n```\n\n```text\nbutton.stories.js\n```\n\n```text\nbutton.stories.js\n```\n\n```text\nimport { Story, Preview } from '@storybook/addon-docs/blocks';\nimport {text, withKnobs} from \"@storybook/addon-knobs\";\nimport Avatar from \"@common/avatar/Avatar.svelte\";\n\n# Button\n\nOne can write __proper Markdown__ here, as well as embed stories:\n\n<Meta title=\"Components/Avatar\" decorators={[withKnobs]} />\n\n<Preview>\n <Story name=\"Normal\">\n {{\n Component: Avatar,\n props: {\n imageUrl: text('Image Url', '/default-profile-image.png'),\n size: text('Size', '2.35rem'),\n },\n }}\n </Story> \n</Preview>\n```\n\n```text\n<Preview>\n <Story name=\"Normal\">\n <Avatar imageUrl=\"/default-profile-image.png\" size=\"2.35rem\"/>\n </Story> \n</Preview>\n```\n\n```text\n/\\.stories\\.([jt]s|mdx)$\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.695Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":209,"estimatedTokens":954}}499{"id":"stack-77020450","source":"stackoverflow","questionId":77020450,"title":"Is it any way to calling SvelteKit form actions from within children components?","tags":["svelte","sveltekit","svelte-component"],"text":"Title: Is it any way to calling SvelteKit form actions from within children components?\nTags: svelte, sveltekit, svelte-component\nSource: Stack Overflow\n\nQuestion:\nFor example I have a route tree like this\n\n```\nfoobar_route\n|\n|-+page.server.js\n|-+page.svelte\n|-child_component.svelte\n|\n```\n\nIn +page.server.js I have\n\n```\nexport const actions = {\n\n create_content: async ({ cookies, request }) => {\n ...\n }\n};\n```\n\nIn child_component.svelte I have a form like the same one on svelte example page\n\n```\n\n \n Post\n\n```\n\nAnd the child_component is called inside +page.svelte\n\n```\n\n...\n\n...\n\n...\n```\n\nBut seems like it was not the right way to implemented it since the action was not called from the form within child component.\n\nIs there any other way to use it than use store?\n\n========================================\n\nCode:\n```text\nfoobar_route\n|\n|-+page.server.js\n|-+page.svelte\n|-child_component.svelte\n|\n```\n\n```js\nexport const actions = {\n\n create_content: async ({ cookies, request }) => {\n ...\n }\n};\n```\n\n```text\n<form method=\"POST\" action=\"?/create_content\">\n <input/>\n <button type=\"submit\">Post</button>\n</form>\n```\n\n```text\n<script>\n...\n</script>\n...\n<Child_component/>\n...\n```\n\n========================================\n\nComments:\n- Deleting and recreating the component seems to fix this for me.\n- The returned values from the form are not accessible to me, neither in the child nor the parent component. Could you find a way?\n- @aldo.roman.nurena: As I stated in the answer, this should just work. Tested it *again* just now, and it also worked. `form` data is only accessible in the `+page.svelte`, for child components it has to be passed or accessed via the `page` store (i.e. `$page.form`).\n- It just works. I was missing `export` in `export let form: ActionData`. Now I am facing a problem when having multiple forms in the same page, and one of them is handled by the `+page.server.ts` of another page. The form does not return to parent.\n- @aldo.roman.nurena: Please ask a separate question, giving all the necessary details/code.","metadata":{"transformedAt":"2026-08-18T18:33:40.695Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":96,"estimatedTokens":516}}500{"id":"stack-60610241","source":"stackoverflow","questionId":60610241,"title":"Add event directive to svelte html expression?","tags":["javascript","html","svelte"],"text":"Title: Add event directive to svelte html expression?\nTags: javascript, html, svelte\nSource: Stack Overflow\n\nQuestion:\nI want to add a custom button through an html expression in svelte. \nThrough the docs here, I can do that using the *@html* tag.\n\n```\n{@html \n`\n \n click me\n \n`\n}\n```\n\nI would like to now add a directive event handler to the html string, namely a locally defined function that will be called when button is clicked. What I have tried so far: \n\n```\n{@html \n`\n doSomething()}\">\n click me\n \n`\n}\n```\n\nHowever, as I expected it didn't work. I was thinking there could be another way to this, but couldn't come up with one so far\n\n========================================\n\nCode:\n```text\n{@html \n`\n <button>\n click me\n </button>\n`\n}\n```\n\n```text\n{@html \n`\n <button\n on:click=\"${()=>doSomething()}\">\n click me\n </button>\n`\n}\n```\n\n```html\n<button on:click={doSomething}>Click me</button>\n```\n\n```html\n{@html '<button onclick=\"doSomething()\">Click click!</button>'}\n```\n\n```html\n<script context=\"module\">\n // note: using context=module to avoid adding this function to window\n // multiple times\n window.doSomething = () => { ... }\n</script>\n{@html '<button onclick=\"doSomething()\">Click click!</button>'}\n```\n\n```html\n<script>\n import { onMount } from 'svelte'\n\n const doSomething = () => { ... }\n\n onMount(() => {\n const btn = document.querySelector('#grab-me')\n btn.addEventListener('click', doSomething)\n })\n</script>\n\n{@html '<button id=\"grab-me\">Click click!</button>'}\n```\n\n```text\n@html\n```\n\n```text\nel.innerHTML = myHtmlString\n```\n\n```text\non:click\n```\n\n```text\nonclick\n```\n\n```text\nonclick\n```\n\n```text\non:click\n```\n\n```text\nonclick\n```\n\n```text\neval\n```\n\n```text\non:click\n```\n\n```text\nonclick\n```\n\n```text\ndoSomething()\n```\n\n```text\ndoSomething\n```\n\n```text\nwindow\n```\n\n```text\nbind:this={el}\n```\n\n```text\n@html\n```\n\n```text\n@html\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.695Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":151,"estimatedTokens":473}}501{"id":"stack-61589334","source":"stackoverflow","questionId":61589334,"title":"How to include static asset/image with svelte component and webpack?","tags":["webpack","svelte","webpack-file-loader","svelte-component"],"text":"Title: How to include static asset/image with svelte component and webpack?\nTags: webpack, svelte, webpack-file-loader, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI want to create a svelte component (based on webpack) which uses/imports a static image. \nHow do I make sure that the image gets properly exported, i.e. that a svelte app using my component also sees the image?\n\nIn my component, I tried importing the image and using the file-loader for webpack:\n\n```\nimport image from \"./image.jpg\";\n```\n\nand\n\n```\n{\n test: /\\.(png|svg|jpg|gif)$/,\n use: [\n 'file-loader',\n ],\n}\n```\n\nThis works, the image is included in the dist folder, but in this case I also need to add a file-loader to the main svelte app, which is an additional requirement I want to avoid. The main app should only need to import my component.\n\nIs this possible or is the above already the recommended approach?\n\n========================================\n\nCode:\n```text\nimport image from \"./image.jpg\";\n```\n\n```text\n{\n test: /\\.(png|svg|jpg|gif)$/,\n use: [\n 'file-loader',\n ],\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.695Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":44,"estimatedTokens":269}}502{"id":"stack-61911455","source":"stackoverflow","questionId":61911455,"title":"In Svelte how to make bind:group work, when checkbox is in component?","tags":["bind","svelte","svelte-component"],"text":"Title: In Svelte how to make bind:group work, when checkbox is in component?\nTags: bind, svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI worked with bind:group for checkbox when it is not in component.\nNow when I try to make checkbox with label a component it is not working.\n\nCheckboxWithLabel.svelte (component)\n\n```\n\n export let label=\"\";\n export let bindGroup=\"\";\n export let value=\"\";\n\n{label}\n \n \n\n```\n\nSettingsSession.svelte (page)\n\n```\nimport CheckboxWithLabel from '@/components/ui/CheckboxWithLabel';\n\nlet sessionLengths = [5, 15];\n$: console.log('duration', sessionLengths);\n\n \n\n### Select live session durations\n\n \n \n \n \n \n \n \n\n...\n```\n\nA brief example of working bind:group when it is done without component.\n\n```\n\nlet goodDogs = []\nlet dogs = ['Roger', 'Syd']\n\n Who's a good dog?\n\n {#each dogs as dog}\n \n- {dog} \n {/each}\n\n Good dogs according to me:\n\n {#each goodDogs as dog}\n \n- {dog}\n {/each}\n\n```\n\nSource: https://www.freecodecamp.org/news/the-svelte-handbook/#svelte-lifecycle-events\n\n========================================\n\nTop Answer:\nTo my knowledge this still does not work.\n\nHere's a simple workaround :\n\nhttps://svelte.dev/repl/02d60142a1cc470bb43e0cfddaba4af1?version=3.38.3\n\n```\n\n import Checkbox from './Checkbox.svelte';\n \n let options = [\"1\"];\n\n{options}\n```\n\n```\n\n export let label = \"\";\n export let bindGroup = [];\n export let value = \"\";\n \n function onChange({ target }) {\n const { value, checked } = target;\n if (checked) {\n bindGroup = [...bindGroup, value]\n } else {\n bindGroup = bindGroup.filter((item) => item !== value);\n }\n }\n\n{label}\n \n\n```\n\n========================================\n\nCode:\n```svelte\n<script>\n export let label=\"\";\n export let bindGroup=\"\";\n export let value=\"\";\n</script>\n<label class=\"container\">{label}\n <input type=\"checkbox\" bind:group={bindGroup} value={value} />\n <span class=\"checkmark\"></span>\n</label>\n```\n\n```svelte\nimport CheckboxWithLabel from '@/components/ui/CheckboxWithLabel';\n\n<script>\nlet sessionLengths = [5, 15];\n$: console.log('duration', sessionLengths);\n</script>\n\n<div class=\"form-group\">\n <h5>Select live session durations</h5>\n <CheckboxWithLabel label='5 minutes' bindGroup={sessionLengths} value=\"5\"/>\n <CheckboxWithLabel label='15 minutes' bindGroup={sessionLengths} value=\"15\"/>\n <CheckboxWithLabel label='30 minutes' bindGroup={sessionLengths} value=\"30\"/>\n <CheckboxWithLabel label='45 minutes' bindGroup={sessionLengths} value=\"45\"/>\n <CheckboxWithLabel label='60 minutes' bindGroup={sessionLengths} value=\"60\"/>\n <CheckboxWithLabel label='90 minutes' bindGroup={sessionLengths} value=\"90\"/>\n <CheckboxWithLabel label='120 minutes' bindGroup={sessionLengths} value=\"120\"/>\n</div>\n...\n```\n\n```svelte\n<script>\nlet goodDogs = []\nlet dogs = ['Roger', 'Syd']\n</script>\n\n<h2>\n Who's a good dog?\n</h2>\n\n<ul>\n {#each dogs as dog}\n <li>{dog} <input type=checkbox bind:group={goodDogs} value={dog}></li>\n {/each}\n</ul>\n\n<h2>\n Good dogs according to me:\n</h2>\n\n<ul>\n {#each goodDogs as dog}\n <li>{dog}</li>\n {/each}\n</ul>\n```\n\n```text\n<script>\n export let label=\"Herbert\";\n export let bindGroup=[]\n export let value=\"Herbert\";\n export let value2=\"Robert\"\n export let label2=\"Robert\"\n</script>\n```\n\n```text\n<Checkbox label=\"Herbert\" bind:bindGroup={selectedNames} value=\"Herbert\"/>\n<Checkbox label=\"Robert\" bind:bindGroup={selectedNames} value=\"Robert\"/>\n<Checkbox label=\"Mike\" bind:bindGroup={selectedNames} value=\"Mike\"/>\n```\n\n```text\nCheckboxWithLabel.svelte (component)\n```\n\n```js\n<script>\n import Checkbox from './Checkbox.svelte';\n \n let options = [\"1\"];\n</script>\n\n<Checkbox label=\"1\" value=\"1\" bind:bindGroup={options} />\n<Checkbox label=\"2\" value=\"2\" bind:bindGroup={options} />\n<Checkbox label=\"3\" value=\"3\" bind:bindGroup={options} />\n\n{options}\n```\n\n```js\n<script>\n export let label = \"\";\n export let bindGroup = [];\n export let value = \"\";\n \n function onChange({ target }) {\n const { value, checked } = target;\n if (checked) {\n bindGroup = [...bindGroup, value]\n } else {\n bindGroup = bindGroup.filter((item) => item !== value);\n }\n }\n</script>\n\n<label>{label}\n <input type=\"checkbox\"\n {value}\n checked={bindGroup.includes(value)}\n on:change={onChange} />\n</label>\n```\n\n========================================\n\nComments:\n- What exactly is not working? Which behaviour do you expect? So I guess SettingsSession.svelte works and CheckboxWithLabel.svelte does not?\n- Without placing this checkboxes in component bind:group on checkboxes make them to add or remove in array, whatever is set in \"value\". There is nice example about this. Please search this page for \"bind:group\" freecodecamp.org/news/the-svelte-handbook/…\n- This is working, but it is not in a component. Bug or just a problem is when it is placed in component to make bind:group work. Thank you for your effort. I created another REPL where I reproduced the problem. And the problem is that the list in which bind:group should add or remove values depending on checked/unchecked state is not working when it is in component.\n- The reason why it doesn't work is that `bindGroup` from one component is actually a different variable from `bindGroup` in other siblings (i.e. as many groups as there are components, quite useless). `` could have been a way around, but it's not reactive, so that won't work either, and neither will a store because reading an array from a store returns a value and not a reference. There are other ways to replicate group behavior in components though: `on:change` handler passed from the parent, event dispatcher, store, or a combination of these.","metadata":{"transformedAt":"2026-08-18T18:33:40.695Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":236,"estimatedTokens":1428}}503{"id":"stack-60677238","source":"stackoverflow","questionId":60677238,"title":"Apply svelte-ignore warning comment to all files","tags":["css-selectors","svelte","sapper","svelte-3"],"text":"Title: Apply svelte-ignore warning comment to all files\nTags: css-selectors, svelte, sapper, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI have been getting a bunch of warnings in my console saying \"Unused CSS selector\" for css from other files or css that was deleted already. It may be related to https://github.com/sveltejs/sapper/issues/842, but for now I am just looking for a way to prevent the unused css selector warnings from appearing in the console. \n\nI have tried writing comments at the top of the _layout.svelte and template.html files like this: `` as is done here: https://svelte.dev/docs#Comments, but it does not work. I could go through and add this to each file, but I was wondering if there is a way to make it apply to all files. Thanks.\n\n========================================\n\nTop Answer:\nHere is webpack svelte-loader configuration that worked for me - warnings stays in VS Code, but not appears in the browser\n\n```\n// *** \n test: /\\.svelte$/,\n use: {\n loader: 'svelte-loader-hot',\n options: {\n hotReload: true, // optional\n preprocess: sveltePreprocess(),\n onwarn: (warning, handler) => {\n console.log(warning);\n if (warning.code.includes('css-unused-selector')) {\n return;\n }\n handler(warning);\n }\n }\n \n }\n// ***\n```\n\n========================================\n\nCode:\n```text\n<!-- svelte-ignore css-unused-selector -->\n```\n\n```text\nexport default {\n client: {\n ...\n svelte({\n dev,\n hydratable: true,\n emitCss: true,\n preprocess,\n // Warnings are normally passed straight to Rollup. You can\n // optionally handle them here, for example to squelch\n // warnings with a particular code\n onwarn: (warning, handler) => {\n // e.g. don't warn on <marquee> elements, cos they're cool\n if (warning.code === 'PLUGIN_WARNING') return;\n\n // let Rollup handle all other warnings normally\n handler(warning);\n }\n }),\n ...\n },\n ...\n}\n```\n\n```text\nrollup.config.js\n```\n\n```text\nonwarn\n```\n\n```text\n// *** \n test: /\\.svelte$/,\n use: {\n loader: 'svelte-loader-hot',\n options: {\n hotReload: true, // optional\n preprocess: sveltePreprocess(),\n onwarn: (warning, handler) => {\n console.log(warning);\n if (warning.code.includes('css-unused-selector')) {\n return;\n }\n handler(warning);\n }\n }\n \n }\n// ***\n```\n\n========================================\n\nComments:\n- placing this at the top of the css style tag ...... worked for me in my version of svelte (^3.48.0) transpiled with webpack and svelte-loader (^3.1.2) using webpack (copy-webpack-plugin@11.0.0)\n- Thanks SyntaxRules. The warning code was actually `'PLUGIN_WARNING'`, so I submitted an edit for that.\n- @Ross Sounds great. I had a hard time finding where these warning codes are documented. Glad it did the trick.\n- how can I solve it in sveltekit ?","metadata":{"transformedAt":"2026-08-18T18:33:40.695Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":104,"estimatedTokens":835}}504{"id":"stack-72984426","source":"stackoverflow","questionId":72984426,"title":"Sveltekit root route not causing page load","tags":["navigation","svelte","sveltekit"],"text":"Title: Sveltekit root route not causing page load\nTags: navigation, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a navigation bar with sveltekit. So far, I have all the links (hash routes) working to be styled when clicked. However, after clicking the \"Home\" route several times, it stops causing the page to load, which causes my `$page` subscription to not update and thus style the link correctly.\n\nMy subscription that logs the current hash route:\n`$: console.log($page.url.hash);`\n\nMy test for styling the link:\n`class:active={$page.url.hash === x.path.slice(1)`\n\nEven after the Home link stops being styled, all the other links will still be styled when clicked. I do get an empty string in the console on the first page load, and again after clicking away from Home and back on it. The second time clicking the Home link does not produce anything in the console.\n\nThe route changes in the address bar each time I click any link.\n\n```\n\n import { page } from '$app/stores';\n\n const navItems = [\n {\n label: 'home',\n path: '/'\n },\n {\n label: 'how it works',\n path: '/#how-it-works'\n },\n {\n label: 'pricing',\n path: '/#pricing'\n },\n {\n label: 'partners',\n path: '/#partners'\n },\n {\n label: 'contact',\n path: '/#contact-us'\n }\n ];\n\n $: console.log($page.url);\n\n {#each navItems as x}\n \n {x.label}\n \n {/each}\n\n .active {\n font-weight: bold;\n position: relative;\n }\n\n .active::after {\n content: '';\n width: 100%;\n height: 3px;\n position: absolute;\n left: 0;\n bottom: -8px;\n background-color: #17a398;\n border-radius: 999px;\n }\n\n```\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n import { page } from '$app/stores';\n\n const navItems = [\n {\n label: 'home',\n path: '/'\n },\n {\n label: 'how it works',\n path: '/#how-it-works'\n },\n {\n label: 'pricing',\n path: '/#pricing'\n },\n {\n label: 'partners',\n path: '/#partners'\n },\n {\n label: 'contact',\n path: '/#contact-us'\n }\n ];\n\n $: console.log($page.url);\n</script>\n\n<nav>\n {#each navItems as x}\n <a\n href={x.path}\n class=\"capitalize\"\n class:active={$page.url.hash === x.path.slice(1)}\n >\n {x.label}\n </a>\n {/each}\n</nav>\n\n<style>\n .active {\n font-weight: bold;\n position: relative;\n }\n\n .active::after {\n content: '';\n width: 100%;\n height: 3px;\n position: absolute;\n left: 0;\n bottom: -8px;\n background-color: #17a398;\n border-radius: 999px;\n }\n</style>\n```\n\n```text\n$page\n```\n\n```text\n$: console.log($page.url.hash);\n```\n\n```text\nclass:active={$page.url.hash === x.path.slice(1)\n```\n\n```text\nimport { goto } from '$app/navigation';\n```\n\n```html\n<nav>\n {#each navItems as x}\n <a\n on:click|preventDefault={() => goto(x.path)}\n href={x.path}\n class=\"capitalize\"\n class:active={$page.url.hash === x.path.slice(1)}\n >\n {x.label}\n </a>\n {/each}\n</nav>\n```\n\n```text\ngoto\n```\n\n```text\ngoto\n```\n\n========================================\n\nComments:\n- Could you create a REPL (svelte.dev/repl) to illustrate the problem?\n- @Coo Could not get access to `$app.stores` from the REPL (expected), so I added a code snippet to the question. I ended up just putting `/#` onto the home route to force a re-render. It works; and with an appropriate test, applies the styles correctly.\n- Another workaround is might be to mark links external `` until any underlying bug is fixed.","metadata":{"transformedAt":"2026-08-18T18:33:40.695Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":179,"estimatedTokens":923}}505{"id":"stack-69452447","source":"stackoverflow","questionId":69452447,"title":"How to use await blocks and update state in Svelte","tags":["svelte"],"text":"Title: How to use await blocks and update state in Svelte\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nExpanding on the example from https://svelte.dev/tutorial/await-blocks, what is the conventional way to update `numbers` and use await blocks, or should await blocks be avoided altogether?\n\n```\n\n let numbers = [1, 2, 3]\n async function getRandomNumber() {\n const res = await fetch(`tutorial/random-number`);\n const text = await res.text();\n\n if (res.ok) {\n return text;\n } else {\n throw new Error(text);\n }\n }\n \n let promise = getRandomNumber();\n\n function handleClick() {\n promise = getRandomNumber();\n }\n\n generate random number\n\n{#each numbers as number}\n\n {number}\n\n{/each}\n{#await promise}\n ...waiting\n\n{:catch error}\n {error.message}\n\n{/await}\n```\n\n========================================\n\nTop Answer:\nNot sure if this is the conventional way, but updating `handleClick` as follows seems to do the trick:\n\n```\nasync function handleClick() {\n promise = getRandomNumber();\n const newNumber = await promise\n numbers = [...numbers, newNumber]\n}\n```\n\nSee full result at Svelte REPL.\n\n========================================\n\nCode:\n```html\n<script>\n let numbers = [1, 2, 3]\n async function getRandomNumber() {\n const res = await fetch(`tutorial/random-number`);\n const text = await res.text();\n\n if (res.ok) {\n return text;\n } else {\n throw new Error(text);\n }\n }\n \n let promise = getRandomNumber();\n\n function handleClick() {\n promise = getRandomNumber();\n }\n</script>\n\n<button on:click={handleClick}>\n generate random number\n</button>\n\n{#each numbers as number}\n<p>\n {number}\n</p>\n{/each}\n{#await promise}\n <p>...waiting</p>\n{:catch error}\n <p style=\"color: red\">{error.message}</p>\n{/await}\n```\n\n```text\nnumbers\n```\n\n```js\n// option 1\nconst newNumber = await promise;\nnumbers.push(newNumber);\nnumbers = numbers;\n```\n\n```js\n// option 2\nconst newNumber = await promise;\nnumbers = [...numbers, newNumber]\n```\n\n```text\n{#await promise}\n <p>...waiting</p>\n{:then data}\n <!-- html markup here is the convention -->\n <p> {numbers = [...numbers, data]} </p>\n{:catch error}\n <p style=\"color: red\">{error.message}</p>\n{/await}\n```\n\n```text\n{#await}\n```\n\n```text\nnumbers\n```\n\n```js\nasync function handleClick() {\n promise = getRandomNumber();\n const newNumber = await promise\n numbers = [...numbers, newNumber]\n}\n```\n\n```text\nhandleClick\n```\n\n========================================\n\nComments:\n- Thanks for the reply. My question may have been unclear. I was was wondering how to combine it with await blocks if at all. I updated the question \"what is the conventional way to update `numbers` *and use await blocks, or should await blocks be avoided altogether*?\"\n- @David Updated my answer to reflect your question","metadata":{"transformedAt":"2026-08-18T18:33:40.696Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":151,"estimatedTokens":708}}506{"id":"stack-56690468","source":"stackoverflow","questionId":56690468,"title":"Cannot get D3.js to work inside Svelte component (with Rollup)","tags":["javascript","d3.js","rollupjs","svelte"],"text":"Title: Cannot get D3.js to work inside Svelte component (with Rollup)\nTags: javascript, d3.js, rollupjs, svelte\nSource: Stack Overflow\n\nQuestion:\nI've been trying to put the most basic D3 example into a Svelte app and can't get it to work. At first I tried installing D3 as a node module: `npm install d3` but this produces the same result (a lack of result) as importing D3 as an external script from CDN inside of `index.html`: ``. Using either method I get a bunch of circular dependency warnings on app start:\n\n```\n(!) Circular dependency: node_modules\\d3-selection\\src\\selection\\index.js -> node_modules\\d3-selection\\src\\selection\\select.js -> node_modules\\d3-selection\\src\\selection\\index.js\n```\n\nBut the app starts with no errors, and no D3 dynamic formatting occurs, nor any errors pop up in the DevTools console inside Chrome.\n\nThe Svelte component looks like this:\n\n```\n\n import * as d3 from 'd3';\n var data = [30, 86, 168, 281, 303, 365];\n\n d3.select(\".chart\")\n .selectAll(\"div\")\n .data(data)\n .enter()\n .append(\"div\")\n .style(\"width\", function(d) {\n return d + \"px\";\n })\n .text(function(d) {\n return d;\n });\n\n .chart div {\n font: 10px sans-serif;\n background-color: steelblue;\n text-align: right;\n padding: 3px;\n margin: 1px;\n color: white;\n }\n\n```\n\nPutting the code above into a static HTML file produces a bar chart, as expected. But when run as a Svelte component nothing is displayed.\n\nMy rollup.config.js is:\n\n```\nimport svelte from 'rollup-plugin-svelte';\nimport resolve from 'rollup-plugin-node-resolve';\nimport commonjs from 'rollup-plugin-commonjs';\nimport livereload from 'rollup-plugin-livereload';\nimport { terser } from 'rollup-plugin-terser';\n\nconst production = !process.env.ROLLUP_WATCH;\n\nexport default {\n input: 'src/main.js',\n output: {\n sourcemap: true,\n format: 'iife',\n name: 'app',\n file: 'public/bundle.js',\n globals: { 'd3': 'd3' },\n external: [ 'd3' ]\n },\n plugins: [\n svelte({\n dev: !production,\n css: css => { css.write('public/bundle.css'); }\n }),\n resolve({ browser: true }),\n commonjs(),\n !production && livereload('public'),\n production && terser()\n ],\n watch: {\n clearScreen: false\n }\n};\n```\n\n...and index.html is:\n\n```\n\n \n \n\n Svelte app\n\n \n \n \n\n \n \n\n```\n\nI would suspect Rollup not bundling D3 module correctly, but as an external script in `` it should in theory work, but it doesn't. Please point me in the right direction, I've spent way too much time trying to get it to work, and as a JS noob am out of options. Thanks!\n\n========================================\n\nCode:\n```text\n(!) Circular dependency: node_modules\\d3-selection\\src\\selection\\index.js -> node_modules\\d3-selection\\src\\selection\\select.js -> node_modules\\d3-selection\\src\\selection\\index.js\n```\n\n```text\n<script>\n import * as d3 from 'd3';\n var data = [30, 86, 168, 281, 303, 365];\n\n d3.select(\".chart\")\n .selectAll(\"div\")\n .data(data)\n .enter()\n .append(\"div\")\n .style(\"width\", function(d) {\n return d + \"px\";\n })\n .text(function(d) {\n return d;\n });\n</script>\n\n<style>\n .chart div {\n font: 10px sans-serif;\n background-color: steelblue;\n text-align: right;\n padding: 3px;\n margin: 1px;\n color: white;\n }\n</style>\n\n<div class=\"chart\"></div>\n```\n\n```text\nimport svelte from 'rollup-plugin-svelte';\nimport resolve from 'rollup-plugin-node-resolve';\nimport commonjs from 'rollup-plugin-commonjs';\nimport livereload from 'rollup-plugin-livereload';\nimport { terser } from 'rollup-plugin-terser';\n\nconst production = !process.env.ROLLUP_WATCH;\n\nexport default {\n input: 'src/main.js',\n output: {\n sourcemap: true,\n format: 'iife',\n name: 'app',\n file: 'public/bundle.js',\n globals: { 'd3': 'd3' },\n external: [ 'd3' ]\n },\n plugins: [\n svelte({\n dev: !production,\n css: css => { css.write('public/bundle.css'); }\n }),\n resolve({ browser: true }),\n commonjs(),\n !production && livereload('public'),\n production && terser()\n ],\n watch: {\n clearScreen: false\n }\n};\n```\n\n```html\n<!doctype html>\n<html>\n<head>\n <meta charset='utf8'>\n <meta name='viewport' content='width=device-width'>\n\n <title>Svelte app</title>\n\n <link rel='icon' type='image/png' href='favicon.png'>\n <link rel='stylesheet' href='global.css'>\n <link rel='stylesheet' href='bundle.css'>\n</head>\n\n<body>\n <script src=\"https://d3js.org/d3.v5.min.js\"></script>\n <script src='bundle.js'></script>\n</body>\n</html>\n```\n\n```text\nnpm install d3\n```\n\n```text\nindex.html\n```\n\n```text\n<script src=\"https://d3js.org/d3.v5.min.js\"></script>\n```\n\n```text\n<body>\n```\n\n```html\n<script>\n import { onMount } from 'svelte';\n\n // other code...\n\n onMount(() => {\n d3.select('.chart')\n // ...\n });\n</script>\n```\n\n```html\n<script>\n import { onMount } from 'svelte';\n\n // other code...\n\n let el;\n\n onMount(() => {\n d3.select(el) // no danger of selecting the wrong element\n // ...\n });\n</script>\n\n<div class=\"chart\" bind:this={el}></div>\n```\n\n```html\n<style>\n .chart :global(div) {\n /* styles */\n }\n</style>\n```\n\n```html\n<script>\n var data = [30, 86, 168, 281, 303, 365];\n</script>\n\n<style>\n .chart div {\n font: 10px sans-serif;\n background-color: steelblue;\n text-align: right;\n padding: 3px;\n margin: 1px;\n color: white;\n }\n</style>\n\n<div class=\"chart\">\n {#each data as d}\n <div style=\"width: {d}px\">\n {d}\n </div>\n {/each}\n</div>\n```\n\n```text\n<div class=\"chart\"></div>\n```\n\n```text\n<script>\n```\n\n```text\n.chart\n```\n\n```text\n.chart div {...}\n```\n\n========================================\n\nComments:\n- There is a Svelte+D3 example: link but I still can't see what I'm doing wrong in my code.\n- Thank you very much! Great explanation! This D3 example was just to test if D3 is working before I start using it in more complex ways. Now that I see it working properly I will code zoomable charts ;) Thanks again!\n- is it necessary to include the `d3.v5.min.js` in index.html if you import it from your component? shouldn't it go to bundle.js???\n- Any thoughts on getting rid of the circular dependency warning? Thanks!\n- @mikemaccana looks like the answer for removing the d3-selection warnings is a no github.com/d3/d3-selection/issues/229\n- The global modifier still seems to work only if there's a pre-existing element of the same kind. I cannot seem to select elements that are generated with D3. Options: - do the styling in D3 (complicates templating, which is a good advantage of using svelte) - use loops on svelte, which works for most charts, probably. I'm a bit new to svelte, so I'm not sure if the data reactivity I get from D3 will transfer well. - Maybe there is a way to make the styles work? Thanks in advance to anyone who answers! -","metadata":{"transformedAt":"2026-08-18T18:33:40.696Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":301,"estimatedTokens":1706}}507{"id":"stack-68717649","source":"stackoverflow","questionId":68717649,"title":"Conditional styling on class in Svelte","tags":["javascript","html","css","svelte","svelte-component"],"text":"Title: Conditional styling on class in Svelte\nTags: javascript, html, css, svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use Svelte to do some conditional styling and highlighting to equations. While I've been successful at applying a global static style to a class, I cannot figure out how to do this when an event occurs (like one instance of the class is hovered over).\n\nDo I need to create a stored value (i.e. some boolean that gets set to true when a class is hovered over) to use conditional styling? Or can I write a function as in the example below that will target all instances of the class? I'm a bit unclear why targeting a class in styling requires the `:global(classname)` format.\n\n`App.svelte`\n\n```\n\n // import Component\n import Katex from \"./Katex.svelte\"\n \n \n \n // math equations\n const math1 = \"a\\\\htmlClass{test}{x}^2+bx+c=0\";\n const math2 = \"x=-\\\\frac{-b\\\\pm\\\\sqrt{b^2-4ac}}{2a}\";\n const math3 = \"V=\\\\frac{1}{3}\\\\pi r^2 h\";\n \n // set up array and index for reactivity and initialize\n const mathArray = [math1, math2, math3];\n let index = 0;\n $: math = mathArray[index];\n \n // changeMath function for button click\n function changeMath() {\n // increase index\n index = (index+1)%3;\n }\n \n function hoverByClass(classname,colorover,colorout=\"transparent\")\n {\n var elms=document.getElementsByClassName(classname);\n console.log(elms);\n for(var i=0;i\n\n### KaTeX svelte component demo\n\n### Inline math\n\nOur math equation: and it is inline.\n\n### Displayed math\n\nOur math equation: and it is displayed.\n\n### Reactivity\n\n Displaying equation {index}\n\n### Static math expression within HTML\n\n :global(.test) {\n color: red\n }\n\n```\n\n`Katex.svelte`\n\n```\n\n import katex from \"katex\";\n export let math;\n export let displayMode = false;\n \n const options = {\n displayMode: displayMode,\n throwOnError: false,\n trust: true\n }\n \n $: katexString = katex.renderToString(math, options);\n\n \n\n{@html katexString}\n```\n\n========================================\n\nCode:\n```text\n<script>\n // import Component\n import Katex from \"./Katex.svelte\"\n \n \n \n // math equations\n const math1 = \"a\\\\htmlClass{test}{x}^2+bx+c=0\";\n const math2 = \"x=-\\\\frac{-b\\\\pm\\\\sqrt{b^2-4ac}}{2a}\";\n const math3 = \"V=\\\\frac{1}{3}\\\\pi r^2 h\";\n \n // set up array and index for reactivity and initialize\n const mathArray = [math1, math2, math3];\n let index = 0;\n $: math = mathArray[index];\n \n // changeMath function for button click\n function changeMath() {\n // increase index\n index = (index+1)%3;\n }\n \n function hoverByClass(classname,colorover,colorout=\"transparent\")\n {\n var elms=document.getElementsByClassName(classname);\n console.log(elms);\n for(var i=0;i<elms.length;i++)\n {\n elms[i].onmouseover = function()\n {\n for(var k=0;k<elms.length;k++)\n {\n elms[k].style.backgroundColor=colorover;\n }\n };\n elms[i].onmouseout = function()\n {\n for(var k=0;k<elms.length;k++)\n {\n elms[k].style.backgroundColor=colorout;\n }\n };\n } \n } \nhoverByClass(\"test\",\"pink\");\n</script>\n\n<h1>KaTeX svelte component demo</h1>\n\n<h2>Inline math</h2>\nOur math equation: <Katex {math}/> and it is inline.\n\n<h2>Displayed math</h2>\nOur math equation: <Katex {math} displayMode/> and it is displayed.\n\n<h2>Reactivity</h2>\n<button on:click={changeMath}>\n Displaying equation {index}\n</button>\n\n<h2>Static math expression within HTML</h2>\n<Katex math={\"V=\\\\pi\\\\textrm{ m}^3\"}/>\n<style>\n :global(.test) {\n color: red\n }\n</style>\n```\n\n```text\n<script>\n import katex from \"katex\";\n export let math;\n export let displayMode = false;\n \n const options = {\n displayMode: displayMode,\n throwOnError: false,\n trust: true\n }\n \n $: katexString = katex.renderToString(math, options);\n</script>\n\n<svelte:head>\n <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css\" integrity=\"sha384-AfEj0r4/OFrOo5t7NnNe46zW/tFgW6x/bCJG8FqQCEo3+Aro6EYUG4+cU+KJWu/X\" crossorigin=\"anonymous\">\n</svelte:head>\n\n{@html katexString}\n```\n\n```text\n:global(classname)\n```\n\n```text\nApp.svelte\n```\n\n```text\nKatex.svelte\n```\n\n```html\n<div>\n <p>This is some text <span class=\"a\">highlight</span></p>\n <span class=\"a\">Another highlight</span>\n <ul>\n <li>Some listitem</li>\n <li class=\"a\">Some listitem</li>\n <li class=\"b\">Some listitem</li>\n <li class=\"b\">Some listitem</li>\n </ul>\n</div>\n```\n\n```html\n<script>\n import { onMount } from 'svelte'\n\n let hash = {}\n let wrapper\n \n onMount(() => {\n [...wrapper.querySelectorAll('[class]')].forEach(el => {\n if (hash[el.className]) return\n else hash[el.className] = [...wrapper.querySelectorAll(`[class=\"${el.className}\"]`)]\n })\n \n Object.values(hash).forEach(nodes => {\n nodes.forEach(node => {\n node.addEventListener('mouseover', () => nodes.forEach(n => n.classList.add('hovered')))\n node.addEventListener('mouseout', () => nodes.forEach(n => n.classList.remove('hovered')))\n })\n })\n })\n</script>\n\n<div bind:this={wrapper}>\n <p>\n Blablabla <span class=\"a\">AAA</span>\n </p>\n <span class=\"a\">BBBB</span>\n <ul>\n <li>BBB</li>\n <li class=\"a b\">BBB</li>\n <li class=\"b\">BBB</li>\n <li class=\"b\">BBB</li>\n </ul>\n</div>\n\n<style>\n div :global(.hovered) {\n background-color: red;\n }\n</style>\n```\n\n```js\nhash['selector-1'] = wrapper.querySelectorAll('.selector-1');\nhash['selector-2'] = wrapper.querySelectorAll('.selector-2')];\nhash['selector-3'] = wrapper.querySelectorAll('.selector-3');\n```\n\n```css\ndiv > :global(.hovered) { background-color: red; }\n```\n\n```text\ndiv.svelte-12345 .hovered { background-color: red; }\n```\n\n```text\nclass=\"a\"\n```\n\n```text\nbind:this\n```\n\n```text\n{@html katexString}\n```\n\n```text\nquerySelector\n```\n\n```text\nonMount\n```\n\n```text\n@html\n```\n\n```text\nonMount\n```\n\n```text\nhovered\n```\n\n```text\n:global()\n```\n\n========================================\n\nComments:\n- The global is required because the class is not added conditionally with Svelte and does not exist in your markup. However, is there some reason you don't just use CSS? \"When one instance of the class is hovered\" looks like this in CSS: `.className:hover {styling}` and will work all the time when that class is hovered, no JS needed.\n- Thanks for the response. I'm trying to highlight multiple instances of the same class (i.e., if a user hovers over one \"x\", all instances of \"x\" should have conditional styling applied to them, rather than just the one that is hovered over).\n- You can also target siblings. `.className:hover ~ .className, .className:hover {styling}`\n- This is a neat way of doing it; thanks for the detailed response! For this particular use case, the content won't be changing so the solution works as is. I'm curious though if you could do something similar to apply conditional styling based on dependent nodes.","metadata":{"transformedAt":"2026-08-18T18:33:40.696Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":302,"estimatedTokens":1799}}508{"id":"stack-61640429","source":"stackoverflow","questionId":61640429,"title":"How to replace the contents of a target in Svelte instead of appending to children?","tags":["svelte","svelte-3","svelte-component"],"text":"Title: How to replace the contents of a target in Svelte instead of appending to children?\nTags: svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nCalling new Component({ target }) appends component to target, I want to replace all the old content of the target with the new component. How can I do that?\n\n========================================\n\nTop Answer:\n```\nfunction replaceTarget (target) {\n const component = new MySvelteComponent({\n target: target.parentElement,\n anchor: target,\n });\n target.remove();\n}\n```\n\nThis prepends the new component just before the target element (in the target's parent), and then removes the target.\n\nRelevant documentation on `anchor`:\n\nhttps://svelte.dev/docs/client-side-component-api#creating-a-component\n\nProbably not a good idea to use with `target === `.\n\n========================================\n\nCode:\n```js\ntarget.innerHTML = '';\nnew Component({ target });\n```\n\n```text\nhydrate: true\n```\n\n```text\ntarget\n```\n\n```text\n$destroy()\n```\n\n```text\ntarget\n```\n\n```js\nimport App from './App.svelte';\n\nlet target = document.querySelector('html').parentNode;\n\nnew App({\n target: target,\n hydrate: true\n});\n```\n\n```js\nimport App from './App.svelte';\n\nnew App({\n target: document,\n hydrate: true\n});\n```\n\n```text\n<html>\n```\n\n```text\n<html>\n```\n\n```js\nfunction replaceTarget (target) {\n const component = new MySvelteComponent({\n target: target.parentElement,\n anchor: target,\n });\n target.remove();\n}\n```\n\n```text\nanchor\n```\n\n```text\ntarget === <body>\n```\n\n```js\nexport function replaceTargetByComponent(target, Component, options) {\n const frag = document.createDocumentFragment()\n var props = {\n id: target.id,\n name: target.name,\n value: target.value,\n checked: target.checked,\n readonly: target.readOnly,\n ...target.dataset,\n ...options,\n }\n const component = new Component({\n target: frag,\n props: props,\n })\n target.replaceWith(frag)\n return component\n}\n```\n\n```js\nexport function replaceTargetByComponent(target, Component, options) {\n const frag = document.createDocumentFragment();\n const tagData = {\n //attributes\n attrs: get_attrs(target),\n //all other opts \n ...options,\n };\n const component = new Component({\n target: frag,\n props: { tagData },\n });\n target.replaceWith(frag);\n return component;\n}\n\n// get all attributes of a given element\nfunction get_attrs(el) {\n return el.getAttributeNames().reduce((acc, name) => {\n return { ...acc, [name]: el.getAttribute(name) };\n }, {});\n}\n```\n\n========================================\n\nComments:\n- Are your talking about routing ? if yes, try this : github.com/ItalyPaleAle/svelte-spa-router\n- Can't edit but the link is outdated, I think the new relevant link is : svelte.dev/docs/client-side-component-api#creating-a-compone‌​nt\n- How to keep attributes of the previous target? (For instance `name`, `id`, `class` etc.)\n- @cassepipe yes. I added an answer below.\n- @Lindsay-Needs-Sleep Can't edit but I think the new correct link is : svelte.dev/docs/client-side-component-api#creating-a-compone‌​nt\n- Thanks for crafting an asnwer ! May I ask why the `Object.assign()` is needed rather than just passing an object literal ?\n- I think this was just a piece of code I forgot to refactor. I edited the snippet.\n- Documentation about `createDocumentFragment` : developer.mozilla.org/en-US/docs/Web/API/Document/…\n- Do you have any idea if it's to to cast frag as an Element to satisfy Typescript ? The component's constructor expects an Element | Document | ShadowRoot","metadata":{"transformedAt":"2026-08-18T18:33:40.696Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":156,"estimatedTokens":923}}509{"id":"stack-58892432","source":"stackoverflow","questionId":58892432,"title":"In sapper/svelt is there a shortcut to components","tags":["svelte","sapper"],"text":"Title: In sapper/svelt is there a shortcut to components\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nIn nuxts/vue there is an alias @ and ~ to mean the root of the app. is there something similar in sapper/svelte to that in a deep route like /very/deep/page/1/2/3/4 I don't have to do something like:\n\n```\nimport Head from '../../../../../../../../components/Thingy.svelte'\n```\n\n========================================\n\nTop Answer:\nYou can put them in a directory like `src/node_modules/components`, and then you'll be able to import them like `import Foo from 'components/Foo.svelte'`. Just make sure that directory isn't gitignored!\n\n========================================\n\nCode:\n```text\nimport Head from '../../../../../../../../components/Thingy.svelte'\n```\n\n```js\n// ...\nimport alias from '@rollup/plugin-alias';\nimport path from 'path';\n// ...\n\nexport default {\n input: 'src/main.js',\n // ...\n plugins: [\n // ...\n alias({\n resolve: ['.jsx', '.js', '.svelte'], // optional, by default this will just look for .js files or folders\n entries: [\n { find: '@', replacement: path.resolve(__dirname, 'src') },\n ]\n }),\n // ...\n ],\n // ...\n};\n```\n\n```js\n// ...\nimport path from 'path';\n// ...\n\nmodule.exports = {\n // ...\n\n resolve: {\n alias: {\n '@': path.resolve(__dirname, 'src')\n }\n }\n\n // ...\n};\n```\n\n```text\nrollup.config.js\n```\n\n```text\n@\n```\n\n```text\nsrc\n```\n\n```text\nwebpack.config.js\n```\n\n```text\nsrc/node_modules/components\n```\n\n```text\nimport Foo from 'components/Foo.svelte'\n```\n\n========================================\n\nComments:\n- This works very well, but can I just add that for sapper, you need to add the alias config to both the client and server bits of the rollup config.\n- I think this should work, but I would be disinclined to add local stuff to node_modules as it may well be ignored by .gitignore files.\n- that's why I said \"Just make sure that directory isn't gitignored\" :) All you need to do is add `!src/node_modules`\n- Hahaha this is such a ridiculous solution, I cannot believe the author of the framework just suggested putting application data inside node_modules\n- This could maybe work, but sounds like a very bad idea. The solution by @Marco Pantaleoni works, just remember to add the alias to both the server and client of rollup config","metadata":{"transformedAt":"2026-08-18T18:33:40.696Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":96,"estimatedTokens":586}}510{"id":"stack-67941692","source":"stackoverflow","questionId":67941692,"title":"Call component from one SvelteKit App to another SvelteKit App","tags":["svelte","sapper","sveltekit"],"text":"Title: Call component from one SvelteKit App to another SvelteKit App\nTags: svelte, sapper, sveltekit\nSource: Stack Overflow\n\nQuestion:\nNote: I have migrated my Sapper app to SvelteKit(Update 3 below), so looking for solution for SvelteKit now.\nI have multiple MFEs(Micro-Frontends) built using Sapper and they are under different servers. There is a svelte component(that renders HTML content) in one MFE that I want to call/render in another MFE. How can I do that? I have tried running/serving both MFEs in my local at the same time and did a fetch(route-that-loads-component), but it returns a POJO in the response and I have no idea what to do with it:\n\n```\nResponse {\n size: 0,\n timeout: 0,\n [Symbol(Body internals)]: {\n body: Gunzip {\n _writeState: [Uint32Array],\n _readableState: [ReadableState],\n _events: [Object: null prototype],\n _eventsCount: 5,\n _maxListeners: undefined,\n _writableState: [WritableState],\n allowHalfOpen: true,\n bytesWritten: 0,\n _handle: [Zlib],\n _outBuffer: ,\n _outOffset: 0,\n _chunkSize: 16384,\n _defaultFlushFlag: 2,\n _finishFlushFlag: 2,\n _defaultFullFlushFlag: 3,\n _info: undefined,\n _maxOutputLength: 4294967295,\n _level: -1,\n _strategy: 0,\n [Symbol(kCapture)]: false,\n [Symbol(kTransformState)]: [Object],\n [Symbol(kError)]: null\n },\n disturbed: false,\n error: null\n },\n [Symbol(Response internals)]: {\n url: 'http://localhost:3000/mfe/content-mfe/content/testrouteasset1',\n status: 200,\n statusText: 'OK',\n headers: Headers { [Symbol(map)]: [Object: null prototype] },\n counter: 0\n }\n}\n```\n\n**UPDATE 1:**\n\nI was able to get the response from MFE by doing `response.text()`, and this is what it looks like:\n\n```\n\n \n \n \n\n \n\n \n \n \n\n tag containing `src/client.js`\n and anything else it needs to hydrate the app and\n initialise the router -->\n __SAPPER__={baseUrl:\"/mfe/content-mfe\",preloaded:[void 0,null,{}]};if('serviceWorker' in navigator)navigator.serviceWorker.register('/mfe/content-mfe/service-worker.js');var s=document.createElement(\"script\");try{new Function(\"if(0)import('')\")();s.src=\"/mfe/content-mfe/client/client.1dc273d9.js\";s.type=\"module\";s.crossOrigin=\"use-credentials\";}catch(e){s.src=\"/mfe/content-mfe/client/shimport@2.0.4.js\";s.setAttribute(\"data-main\",\"/mfe/content-mfe/client/client.1dc273d9.js\")}document.head.appendChild(s) \n\n tag containing critical CSS\n for the current page. CSS for the rest of the app is\n lazily loaded when it precaches secondary pages -->\n \n\n component, if\n the current page has one -->\n\n \n \n\n```\n\nHowever, Sapper is replacing baseURL of the MFE that is sending response to the calling MFE's baseURL, making it not-hydratable since client.js and client.css not reachable(404s)\nhttps://i.sstatic.net/oiwhw.png\n\nEven if I do end up resolving those base path URLs issue, will it still work for 2 Sapper apps to be initiated on one page?\n\n**UPDATE 2:**\n\nI somehow managed to add static baseURL for the MFE from where the content is to be requested, now I get hydration issue because Sapper can't hydrate 2 Sapper Apps in one page.\n\n**UPDATE 3:**\nI have migrated my Sapper apps to SvelteKit. So looking for suggestions on how to achieve this using SvelteKit now!\n\nAny other solution to call/import a component from one MFE to another MFE or would be really appreciated!\n\n========================================\n\nCode:\n```text\nResponse {\n size: 0,\n timeout: 0,\n [Symbol(Body internals)]: {\n body: Gunzip {\n _writeState: [Uint32Array],\n _readableState: [ReadableState],\n _events: [Object: null prototype],\n _eventsCount: 5,\n _maxListeners: undefined,\n _writableState: [WritableState],\n allowHalfOpen: true,\n bytesWritten: 0,\n _handle: [Zlib],\n _outBuffer: <Buffer 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 f7 7f 00 00 41 ff e2 55 48 89 e5 56 57 48 81 ec 10 01 00 00 48 89 75 e8 49 3b 65 e0 0f 86 fb 11 00 00 ... 16334 more bytes>,\n _outOffset: 0,\n _chunkSize: 16384,\n _defaultFlushFlag: 2,\n _finishFlushFlag: 2,\n _defaultFullFlushFlag: 3,\n _info: undefined,\n _maxOutputLength: 4294967295,\n _level: -1,\n _strategy: 0,\n [Symbol(kCapture)]: false,\n [Symbol(kTransformState)]: [Object],\n [Symbol(kError)]: null\n },\n disturbed: false,\n error: null\n },\n [Symbol(Response internals)]: {\n url: 'http://localhost:3000/mfe/content-mfe/content/testrouteasset1',\n status: 200,\n statusText: 'OK',\n headers: Headers { [Symbol(map)]: [Object: null prototype] },\n counter: 0\n }\n}\n```\n\n```text\n<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\">\n <meta name=\"theme-color\" content=\"#333333\">\n\n <base href=\"/mfe/content-mfe/\">\n\n <link rel=\"stylesheet\" href=\"global.css\">\n <link rel=\"manifest\" href=\"manifest.json\" crossorigin=\"use-credentials\">\n <link rel=\"icon\" type=\"image/png\" href=\"favicon.png\">\n\n <!-- Sapper creates a <script> tag containing `src/client.js`\n and anything else it needs to hydrate the app and\n initialise the router -->\n <script>__SAPPER__={baseUrl:\"/mfe/content-mfe\",preloaded:[void 0,null,{}]};if('serviceWorker' in navigator)navigator.serviceWorker.register('/mfe/content-mfe/service-worker.js');var s=document.createElement(\"script\");try{new Function(\"if(0)import('')\")();s.src=\"/mfe/content-mfe/client/client.1dc273d9.js\";s.type=\"module\";s.crossOrigin=\"use-credentials\";}catch(e){s.src=\"/mfe/content-mfe/client/shimport@2.0.4.js\";s.setAttribute(\"data-main\",\"/mfe/content-mfe/client/client.1dc273d9.js\")}document.head.appendChild(s)</script> \n\n <!-- Sapper generates a <style> tag containing critical CSS\n for the current page. CSS for the rest of the app is\n lazily loaded when it precaches secondary pages -->\n <link rel=\"stylesheet\" href=\"client/client-a7fe6d9e.css\"><link rel=\"stylesheet\" href=\"client/FieldErrorMessage-bce587e1.css\">\n\n <!-- This contains the contents of the <svelte:head> component, if\n the current page has one -->\n\n</head>\n<body>\n <!-- The application will be rendered inside this element,\n because `src/client.js` references it -->\n <div id=\"mfe-content\">\n\n\n<main><slot></slot></main></div>\n</body>\n</html>\n```\n\n```text\nresponse.text()\n```\n\n```js\nexport async function get({ query, page }) {\n const ASSET = (await import(\"../../assets/myasset.svelte\")).default;\n\n if (ASSET) {\n let renderedAsset = Asset.render();\n return {\n body: { asset: renderedAsset }\n };\n } else {\n return {\n status: data.status,\n error: new Error(`Could not load ${response}`)\n }\n }\n}\n```\n\n```text\n{\n \"asset\": {\n \"html\": \"<h1 class=\\\"s-ZmOKpGJa32Cj\\\">Hello! \\n</h1>\",\n \"css\": {\n \"code\": \"h1.s-ZmOKpGJa32Cj{color:blue}.s-ZmOKpGJa32Cj{}\",\n \"map\": null\n },\n \"head\": \"\"\n }\n}\n```\n\n```js\n<script context=\"module\">\n export async function load({ fetch }) {\n let status, Final;\n const Asset = await fetch('path-to-the-endpoint');\n if (Asset && Asset.status === 404) {\n return (status = 'Asset not found');\n }\n if (Asset && Asset.ok) {\n Final = await Asset.json();\n return {\n props: {\n Final: Final,\n status: 'Asset is OK',\n },\n };\n } else {\n return {\n props: {\n status: 'Okay, no prop.',\n },\n };\n }\n }\n</script>\n\n<script>\n export let Final, status;\n</script>\n```\n\n```html\n{status}\n\n{@html `<${''}style>${Final.asset.css.code }</${''}style>` }\n\n{@html Final.asset.html}\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.696Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":255,"estimatedTokens":1959}}511{"id":"stack-64727026","source":"stackoverflow","questionId":64727026,"title":"Getting scroll of element in svelte","tags":["svelte"],"text":"Title: Getting scroll of element in svelte\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI have a div with style `overflow: scroll` and it is overflowing on the X-axis.\nI would like to get the value of how far left/right the user has scrolled within this element, but I can't really figure it out.\n\nI saw that you can quite easily bind the window scroll, but as it is just an element that is scrolling and not the window this won't work.\nhttps://svelte.dev/tutorial/svelte-window-bindings\n\nso I tried binding the element, but couldn't really get any meaningful data out of it.\n\n```\n\n let content;\n\n \n ...\n \n\n{#if content}\n{content.scrollLeft}\n{/if}\n```\n\nis it at all possible and am I just missing something?\n\n========================================\n\nTop Answer:\nIn case anyone wants to bind the **vertical** AND the **horizontal** scrolling pixels of an element:\n\n- `element.scrollLeft`: horizontal pixels from left\n\n- `element.scrollTop`: vertical pixels from top\n\nHere's a REPL with a working example\n\n- Here is a list of all the properties and methods available to html elements\n\n- Here's the Svelte API documentation for binding elemental properties\n\n```\n\n let box\n let xScroll = 0\n let yScroll = 0\n\n function parseScroll() {\n xScroll=box.scrollLeft\n yScroll=box.scrollTop\n }\n\n ...\n (scrollable content)\n ...\n\n horizontal: {xScroll}\n vertical: {yScroll}\n\n```\n\n========================================\n\nCode:\n```text\n<script>\n let content;\n</script>\n\n<div class=\"carousel\">\n <div class=\"content\" bind:this={content}>\n ...\n </div>\n</div>\n{#if content}\n{content.scrollLeft}\n{/if}\n```\n\n```text\noverflow: scroll\n```\n\n```text\n<script>\n let carousel, sleft;\n</script>\n\n<div class=\"carousel\" bind:this={carousel} \non:scroll={()=>sleft=carousel.scrollLeft}>\n <div class=\"content\" >\n ...\n </div>\n</div>\n\n{#if carousel}\n{sleft}\n{/if}\n```\n\n```text\n<script>\n let box\n let xScroll = 0\n let yScroll = 0\n\n function parseScroll() {\n xScroll=box.scrollLeft\n yScroll=box.scrollTop\n }\n</script>\n\n<div class=\"box\" bind:this={box} on:scroll={parseScroll}>\n ...\n (scrollable content)\n ...\n</div>\n\n<div class='report'>\n <div>horizontal: {xScroll}</div>\n <div>vertical: {yScroll}</div>\n</div>\n```\n\n```text\nelement.scrollLeft\n```\n\n```text\nelement.scrollTop\n```\n\n========================================\n\nComments:\n- Or use the event's target: `sleft=e.target.scrollLeft}>...` if you rather not bind the element.\n- I would suggest updating this to @razvan-tanase 's answer","metadata":{"transformedAt":"2026-08-18T18:33:40.696Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":139,"estimatedTokens":620}}512{"id":"stack-58902385","source":"stackoverflow","questionId":58902385,"title":"SvelteJS vs ReactJS rendering difference (repaint / reflow)","tags":["javascript","reactjs","svelte","virtual-dom","svelte-3"],"text":"Title: SvelteJS vs ReactJS rendering difference (repaint / reflow)\nTags: javascript, reactjs, svelte, virtual-dom, svelte-3\nSource: Stack Overflow\n\nQuestion:\nHere's my naive understanding of how the DOM and browser works\n\nWhenever something in the DOM ( the real dom ) changes the browser repaints or reflows that the DOM. So in simpler terms every time the DOM changes browser needs to recalculate the CSS, do a layout and repaint the web page. This is what takes time in real dom. \n\nSo React comes with this virtual DOM and what it actually does is it batches the changes and call applies them on real-dom in one go. Thus, minimizing the re-flow and re-paint. \n\nThen what about Svelte. If it is manipulating the DOM directly how does it controls the repaint/reflow of the browser.\n\n========================================\n\nTop Answer:\nBoth libraries minimize how many changes need to be made to the dom. The difference is the way that they figure out what that minimal set of changes is. \n\nReact's approach is to have a representation of the dom in memory (the virtual dom). When you set state, it runs the render process again to create another virtual dom. It compares the before and after, finds what changed, and then any changes get pushed to the real dom.\n\nSvelte's approach is that when you set a variable, it sets a flag marking that variable as having changed. It knows which variables are dependent on other variables, so it then steps through any dependent variables and recalculates them, building up a list of what needs to change. Then these changes get pushed to the dom.\n\n========================================\n\nCode:\n```text\n<script>\n let count = 0;\n\n function handleClick() {\n count += 1;\n }\n</script>\n\n<button on:click={handleClick}>{count}</button>\n```\n\n```text\nfunction create_fragment(ctx) {\n let button;\n let t;\n let dispose;\n\n return {\n c() {\n button = element(\"button\");\n t = text(/*count*/ ctx[0]);\n dispose = listen(button, \"click\", /*handleClick*/ ctx[1]);\n },\n m(target, anchor) {\n insert(target, button, anchor);\n append(button, t);\n },\n p(ctx, [dirty]) {\n if (dirty & /*count*/ 1) set_data(t, /*count*/ ctx[0]);\n },\n i: noop,\n o: noop,\n d(detaching) {\n if (detaching) detach(button);\n dispose();\n }\n };\n}\n```\n\n```text\nfunction element(name) {\n return document.createElement(name);\n}\n```\n\n```text\nfunction instance($$self, $$props, $$invalidate) {\n let count = 0;\n\n function handleClick() {\n $$invalidate(0, count += 1);\n }\n\n return [count, handleClick];\n}\n```\n\n```text\noutput: {\n sourcemap: false,\n format: 'iife',\n name: 'app',\n file: 'public/build/bundle.js'\n },\n plugins: [\n svelte({\n dev: false,\n```\n\n```text\nconsole.dir(app)\n```\n\n```text\nApp\n $$: \n fragment: {c: ƒ, m: ƒ, p: ƒ, i: ƒ, o: ƒ, …}\n ctx: (2) [0, ƒ]\n props: {count: 0}\n update: ƒ noop()\n not_equal: ƒ safe_not_equal(a, b)\n bound: {}\n on_mount: []\n on_destroy: []\n before_update: []\n after_update: []\n context: Map(0) {}\n callbacks: {}\n dirty: [-1]\n __proto__: Object\n $set: $$props => {…}\n```\n\n```text\napp.$set({count: 10})\n```\n\n========================================\n\nComments:\n- Yea I kind of get the gist of it. But I was expecting a little more behind the scenes and inner workings a bit more\n- Very detailed and understandable. Thank you","metadata":{"transformedAt":"2026-08-18T18:33:40.696Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":129,"estimatedTokens":904}}513{"id":"stack-57181704","source":"stackoverflow","questionId":57181704,"title":"Svelte components store - load state into - from URL hash parameters","tags":["javascript","svelte","svelte-3"],"text":"Title: Svelte components store - load state into - from URL hash parameters\nTags: javascript, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nIf we have a **S**ingle **P**age **A**pplication built with **Svelte** with a bunch of components and a store where we keep our current app state, is there an recommended way to store the store state changes into the **# hash part of the current URL** and be able to re-load the same state from the full URL?\n\nIt can be done manually by parsing the current URL with `location.search()`.\n\nStoring of parameters can be done with `location.search(\"key\", \"value\")`.\n\nSome questions:\n\nWhen to load the state from URL? What would be the App init entry\npoint?\nWhen to store the state from the store to the URL? Is there a generic\nway to do this?\n\n========================================\n\nCode:\n```text\nlocation.search()\n```\n\n```text\nlocation.search(\"key\", \"value\")\n```\n\n```text\nimport 'url-search-params-polyfill';\n\nexport function deserializeConfig(serializedConfig, resultConfig) {\n let hashParams = new URLSearchParams(serializedConfig);\n for (const hashParameterAndValue of hashParams.entries()) {\n const key = hashParameterAndValue[0];\n const value = hashParameterAndValue[1];\n\n const decodedKey = decodeUrlParameterKey(key);\n const decodedValue = decodeUrlParameterValue(value);\n\n resultConfig[decodedKey] = decodedValue;\n }\n\n\nexport function serializeConfig(config) {\n const hashParams = new URLSearchParams(\"\");\n\n for (const key in config) {\n const value = config[key];\n const encodedValue = encodeParameterValue(value);\n const encodedKey = encodeParameterKey(key);;\n hashParams.set(encodedKey, encodedValue);\n }\n\n const serializedConfig = hashParams.toString();\n return serializedConfig;\n}\n```\n\n```text\nimport { configFromStore } from \"./stores.js\";\n\nlet config = {};\n\n// when config from store changes\nconfigFromStore.subscribe(updatedConfig => {\n config = updatedConfig;\n\n // check if the config was really modified and does not match the default\n if (!isEquivalent(updatedConfig, defaultConfig)) {\n // update URL hash after store value has been changed\n const serializedConfig = serializeConfig(updatedConfig);\n window.location.hash = \"#\" + serializedConfig;\n }\n}\n\n// on main app start, parse state from URL hash\nconst hash = window.location.hash;\nif (hash && hash.length > 1) {\n const serializedConfig = hash.substr(1);\n deserializeConfig(serializedConfig, config);\n configFromStore.set(config);\n}\n```\n\n========================================\n\nComments:\n- never used it but looks like `svelte-spa-router` provides querystring support out of the box.\n- @skyboyer thanks, have not seen it. This is all new to me so when you are learning you tend to re-implement the wheel.\n- could you append your answer? other people how will land here by searching will not check comments for sure :(","metadata":{"transformedAt":"2026-08-18T18:33:40.696Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":92,"estimatedTokens":726}}514{"id":"stack-66079772","source":"stackoverflow","questionId":66079772,"title":"Svelte: Modify Await Reference?","tags":["javascript","svelte"],"text":"Title: Svelte: Modify Await Reference?\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nSay I have:\n\n```\n{#await showMinePromise}\n ...Loading\n\n{:then entries} \n // do stuff \n{/await}\n```\n\nIs there a way to update the entries variable to add in items (as when the user adds something, etc)? By that I mean manually insert an item into the array external to the await -- no call to update the promise.\n\n========================================\n\nCode:\n```html\n{#await showMinePromise}\n <p>...Loading</p>\n{:then entries} \n // do stuff \n{/await}\n```\n\n```html\n<script>\n\n let fetchSomething = ... // some Promise\n let datas;\n\n fetchSomething.then(r => datas = r);\n</script>\n\n{#await fetchSomething}\n <p>Loading</p>\n{:then}\n // use datas. it's updatable\n{/await}\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.696Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":44,"estimatedTokens":197}}515{"id":"stack-72323330","source":"stackoverflow","questionId":72323330,"title":"How to split slugs in Svelte router in all possible options?","tags":["svelte","sveltekit"],"text":"Title: How to split slugs in Svelte router in all possible options?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI want to build URL patter, like this `[lang]/category/[name]-[suffix]`, where:\n\n- `suffix` is one of a few strings, for example: `['super-product', 'great-gadget', 'ta-ta-ta']`\n\n- `name` is a multiple word slug, like `a-bb-ccc`\n\nTo implement it, I decided to use Matching:\n\n```\nexport function match(param) {\n let result = /^(super-product|great-gadget|ta-ta-ta)/.test(param); \n return a;\n}\n```\n\nFor the URL `/en/category/a-bb-ccc-super-product/`, `param` is `bb-ccc-super-product`.\nQ: How to make Svelte splits URL into slugs in all possible options, like: `a` + `bb-ccc-super-product`, `a-bb` + `ccc-super-product`, ..., `a-bb-ccc-super` + `product`, and not just in one `a` + `bb-ccc-super-product`?\n\nAlso, I tried to use handlers to resolve this issue, failed as I was not able to change URL.\n\n- \"@sveltejs/kit\": \"1.0.0-next.310\"\n\n- \"svelte\": \"3.47.0\"\n\n========================================\n\nCode:\n```text\nexport function match(param) {\n let result = /^(super-product|great-gadget|ta-ta-ta)/.test(param); \n return a;\n}\n```\n\n```text\n[lang]/category/[name]-[suffix]\n```\n\n```text\nsuffix\n```\n\n```text\n['super-product', 'great-gadget', 'ta-ta-ta']\n```\n\n```text\nname\n```\n\n```text\na-bb-ccc\n```\n\n```text\n/en/category/a-bb-ccc-super-product/\n```\n\n```text\nparam\n```\n\n```text\nbb-ccc-super-product\n```\n\n```text\na\n```\n\n```text\nbb-ccc-super-product\n```\n\n```text\na-bb\n```\n\n```text\nccc-super-product\n```\n\n```text\na-bb-ccc-super\n```\n\n```text\nproduct\n```\n\n```text\na\n```\n\n```text\nbb-ccc-super-product\n```\n\n```text\n[name]-[suffix]\n```\n\n```text\nname\n```\n\n```text\n-\n```\n\n```text\nsuffix\n```\n\n```text\n_\n```\n\n```text\n--\n```\n\n```text\nname\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.696Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":24,"totalLines":130,"estimatedTokens":438}}516{"id":"stack-61581094","source":"stackoverflow","questionId":61581094,"title":"SCSS in Svelte not recognized by Visual Studio Code","tags":["visual-studio-code","svelte"],"text":"Title: SCSS in Svelte not recognized by Visual Studio Code\nTags: visual-studio-code, svelte\nSource: Stack Overflow\n\nQuestion:\nVSCode does not recognize the scss that I include within a svelte file. It thinks they are css styles and, the first nesting css that it meets, gives me error.\nI tried to disable the validation of the css in the settings through but it doesn't seem to have any effect: \"css.validate\": false,\nThe svelte application works correctly, either by launching it locally or by compiling the bundle for production (it's not a problem of my code).\nIt's just a problem with how VSCode controls my styles. For this problem, most of my svelte components seem wrong even if they are not really.\nTo compile styles like scss I include the attribute `type=\"text/scss\"` to the tag:\n\n```\n\n```\n\nhttps://i.sstatic.net/XX8AK.png\n\nhttps://i.sstatic.net/swa7S.png\n\nAll errors have code: \"`css-syntax-error`\".\nI think that the reason is because VS Code doesn't recognize that it's SCSS and not CSS.\n\nI have these extensions for sass in svelte:\n\n- SCSS IntelliSense\n\n- Beautify css/scss/sass/less\n\n- Live SASS Compiler\n\n- Svelte plugin 0.9.3\n\nhttps://i.sstatic.net/nc6JC.png\n\nMy VSCode settings:\n\n```\n{\n \"svelte.language-server.runtime\": \"......\",\n \"scss.lint.important\": \"warning\",\n \"editor.formatOnPaste\": true,\n \"css.completion.triggerPropertyValueCompletion\": false,\n \"css.completion.completePropertyWithSemicolon\": false,\n \"css.lint.argumentsInColorFunction\": \"ignore\",\n \"css.lint.hexColorLength\": \"ignore\",\n \"css.lint.duplicateProperties\": \"warning\",\n \"editor.suggestSelection\": \"first\",\n \"vsintellicode.modify.editor.suggestSelection\": \"automaticallyOverrodeDefaultValue\",\n \"workbench.colorTheme\": \"Material Theme Darker\",\n \"css.validate\": false,\n \"editor.codeActionsOnSave\": {},\n \"git.enableSmartCommit\": true,\n \"css.fileExtensions\": [\n \"css\",\n \"scss\"\n ],\n \"beautify.options\": {\n\n },\n}\n```\n\n========================================\n\nCode:\n```text\n<style type=\"text/scss\">\n```\n\n```text\n{\n \"svelte.language-server.runtime\": \"......\",\n \"scss.lint.important\": \"warning\",\n \"editor.formatOnPaste\": true,\n \"css.completion.triggerPropertyValueCompletion\": false,\n \"css.completion.completePropertyWithSemicolon\": false,\n \"css.lint.argumentsInColorFunction\": \"ignore\",\n \"css.lint.hexColorLength\": \"ignore\",\n \"css.lint.duplicateProperties\": \"warning\",\n \"editor.suggestSelection\": \"first\",\n \"vsintellicode.modify.editor.suggestSelection\": \"automaticallyOverrodeDefaultValue\",\n \"workbench.colorTheme\": \"Material Theme Darker\",\n \"css.validate\": false,\n \"editor.codeActionsOnSave\": {},\n \"git.enableSmartCommit\": true,\n \"css.fileExtensions\": [\n \"css\",\n \"scss\"\n ],\n \"beautify.options\": {\n\n },\n}\n```\n\n```text\ntype=\"text/scss\"\n```\n\n```text\ncss-syntax-error\n```\n\n```text\nconst sveltePreprocess = require(\"svelte-preprocess\");\n\nmodule.exports = {\n preprocess: sveltePreprocess(),\n};\n```\n\n```text\nsvelte.config.js\n```\n\n========================================\n\nComments:\n- Which Svelte Plugin do use use? \"Svelte\" or \"Svelte Beta\"? I recommend to use the latter as it's going to become the official Svelte Plugin. Also, what exactly does the error say (if you hover over it; including the error source which is to the right of the message in gray)? General note: SASS is not supported, only SCSS.\n- Thanks for the comment. I edited my question with more informations. I use the 0.9.3 version of the plugin from James Birtles (I have included a screenshot above). Is it the correct version? I have those errors in all the svelte components with SCSS styles but only for the first SCSS code fragment. The error code is the same for all: css-syntax-error (like VS Code doesn't not recognize it like scss). I'm not using SASS.","metadata":{"transformedAt":"2026-08-18T18:33:40.698Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":120,"estimatedTokens":934}}517{"id":"stack-71228938","source":"stackoverflow","questionId":71228938,"title":"Sveltekit communication between layout, routes and components","tags":["svelte","sveltekit"],"text":"Title: Sveltekit communication between layout, routes and components\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm trying to move a svelte SPA into Sveltekit.\n\nIn my SPA, the communication schema is what I would call a \"controller component\" which takes care of displaying some components, listen to their events and update the app accordingly. By and large it looks like this REPL:\n\nhttps://svelte.dev/repl/47bd3f8004624a3c95653b1f1aefd8ee?version=3.46.4\n\nAs you can see in this example, the sequence is fairly trivial:\nApp state 1) App shows CompA and CommonComp\nApp state 2) CompA triggers the doSomething function just after being mounted\nApp state 3) App then call commonComp.setTitle and show CompB in place of CompA\n\nIn SvelteKit, I struggle to do something similar cause I don't understand how to pass data from a slotted sub component to the Component containing the slot and conversely.\nAnyway, this led me to this attempt:\n\nI need 2 routes:\n\n- PageA.svelte for when CompA & CommonComp are displayed\n\n- PageB.svelte for when CompB & CommonComp are displayed\n\nBecause CommonComp is always visible in every states, I would think that it should resides in a __layout.svelte file.\n\n...This took me to the draft below with the comments explaining the access problem I encounter.\n\n***/src/routes/__layout.svelte***\n\n```\n\n```\n\n***/src/routes/PageA.svelte***\n\n```\n\n import { goto } from \"$app/navigation\";\n import CompA from \"$lib/CompA.svelte\";\n\n function handleDoSomethingFinished() {\n goto(\"/test/pageB\");\n }\n\n```\n\n***/src/lib/CompA.svelte***\n\n```\n\n import { onMount } from \"svelte\";\n import { createEventDispatcher } from \"svelte\";\n\n const dispatch = createEventDispatcher();\n\n onMount(() => {\n setTimeout(() => dispatch(\"do_something_finished\"), 3000);\n });\n\nComponent A\n\n```\n\n***/src/routes/PageB.svelte***\n\n```\n\n import CompB from \"$lib/CompB.svelte\";\n\n // How to call CommonComp.setTitle function from here ?\n \n\n```\n\n***/src/lib/CompB.svelte***\n\n```\nComponent B\n\n```\n\n***/src/lib/CommonComp.svelte***\n\n```\n\n let title = \"Common Component\";\n import { createEventDispatcher } from \"svelte\";\n\n const dispatch = createEventDispatcher();\n\n export function setTitle(t) {\n title = t;\n dispatch(\"title-modified\");\n }\n\n{title}\n\n```\n\nI guess I may have tried to some stores and check they value into reactive statements to trigger the appropriate actions but when I'm thinking of it, I see a can of worms so I'm missing something here. Thank you for your help.\n\n========================================\n\nCode:\n```js\n<slot />\n<CommonComp />\n```\n\n```js\n<script>\n import { goto } from \"$app/navigation\";\n import CompA from \"$lib/CompA.svelte\";\n\n function handleDoSomethingFinished() {\n goto(\"/test/pageB\");\n }\n</script>\n\n<CompA on:do_something_finished={handleDoSomethingFinished} />\n```\n\n```js\n<script>\n import { onMount } from \"svelte\";\n import { createEventDispatcher } from \"svelte\";\n\n const dispatch = createEventDispatcher();\n\n onMount(() => {\n setTimeout(() => dispatch(\"do_something_finished\"), 3000);\n });\n</script>\n\n<p>Component A</p>\n```\n\n```js\n<script>\n import CompB from \"$lib/CompB.svelte\";\n\n // How to call CommonComp.setTitle function from here ?\n \n</script>\n\n<CompB />\n```\n\n```js\n<p>Component B</p>\n```\n\n```js\n<script>\n let title = \"Common Component\";\n import { createEventDispatcher } from \"svelte\";\n\n const dispatch = createEventDispatcher();\n\n export function setTitle(t) {\n title = t;\n dispatch(\"title-modified\");\n }\n</script>\n\n<p>{title}</p>\n```\n\n```js\n$: title = $page.stuff.ccTitle || \"Common Component\"\n```\n\n```js\nimport { writable } from 'svelte/store';\n\nconst title = writable('Common Component');\n\nexport default title;\n```\n\n```js\n<script>\n import title from \"$lib/stores/title\";\n</script>\n\n<p>{$title}</p>\n```\n\n```js\n<script>\n import CompB from \"$lib/CompB.svelte\";\n import title from \"$lib/stores/title\";\n\n $title = \"Custom Title\";\n // or say you wanted to set it reactively based on a 'foo' variable:\n // $: $title = foo\n</script>\n\n<CompB />\n```\n\n```text\nexport\n```\n\n```text\nCommonComp\n```\n\n```text\nbind:this\n```\n\n```text\nsetTitle\n```\n\n```text\nslot\n```\n\n```text\nload\n```\n\n```text\nstuff\n```\n\n```text\nccTitle\n```\n\n```text\nstuff\n```\n\n```text\npage\n```\n\n```text\n$app/stores\n```\n\n```text\nCommonComp\n```\n\n```text\nstuff\n```\n\n```text\nload\n```\n\n```text\nload\n```\n\n```text\nstuff\n```\n\n```text\ntitle\n```\n\n```text\nCommonComp\n```\n\n```text\nload\n```\n\n```text\nCommonComp\n```\n\n```text\n$commonComp.setTitle()\n```\n\n========================================\n\nComments:\n- The last Update is a clever approach. I'm surprise to see the need of a reactive statement for the assignment of the component reference to the store here `$: $commonComp = ccRef;` in `__layout.svelte` as I thought stores were already reactive but here it's needed to work properly. Thank you so much :)\n- This reactive statement is needed because `ccRef` will be null/undefined before the component mounts. An alternative would be to do a simple `$commonComp = ccRef` assignment inside the `onMount` lifecycle function, but this is just simpler ;) And you're welcome!","metadata":{"transformedAt":"2026-08-18T18:33:40.698Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":31,"totalLines":292,"estimatedTokens":1274}}518{"id":"stack-58262835","source":"stackoverflow","questionId":58262835,"title":"How to use more than one URL parameter in sapper/svelte","tags":["svelte","sapper"],"text":"Title: How to use more than one URL parameter in sapper/svelte\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI just started learning svelte. After reading some of sapper documentation i saw that sapper use file names and folder structure for routing and if i want something like /blog/:article its possible create a folder with 'blog' name and file '[slug].svelte' inside, how i can construct more complex routes? Example: /blog/:article/comments/:commentId\n\n========================================\n\nCode:\n```text\nsrc/routes/blog/[article]/comments/[commentId].svelte\n```\n\n```text\nsrc/routes/blog/[article]/comments/[commentId]/index.svelte\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.698Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":17,"estimatedTokens":164}}519{"id":"stack-72734643","source":"stackoverflow","questionId":72734643,"title":"Import TypeScript interfaces in SvelteKit?","tags":["typescript","svelte","sveltekit"],"text":"Title: Import TypeScript interfaces in SvelteKit?\nTags: typescript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a starting SvelteKit project. I am trying to reuse an interface in multiple places.\n\nThe file is placed in `/src/lib/choice.ts`.\n\n```\nexport interface Choice {\n id: number;\n value: string;\n}\n```\n\nHowever, when I try to reference this interface in a Svelte component like so:\n\n```\n\n import {Choice} from \"$lib/choice\";\n\n```\n\nI get this error:\n\n```\n500\nThe requested module '/src/lib/choice.ts' does not provide an export named 'Choice'\nSyntaxError: The requested module '/src/lib/choice.ts' does not provide an export named 'Choice'\n```\n\nMy IDE, however, thinks this is perfectly valid, up to and including allowing click-navigation to the Choice declaration.\n\nIf, however, I change the declaration to this:\n\n```\nexport class Choice {\n id!: number;\n value!: string;\n}\n```\n\nEverything works and my IDE is happy.\n\nWhat's going on here? I don't understand why the interface doesn't work but the class declaration does.\n\n========================================\n\nCode:\n```text\nexport interface Choice {\n id: number;\n value: string;\n}\n```\n\n```text\n<script lang=\"ts\">\n import {Choice} from \"$lib/choice\";\n</script>\n```\n\n```text\n500\nThe requested module '/src/lib/choice.ts' does not provide an export named 'Choice'\nSyntaxError: The requested module '/src/lib/choice.ts' does not provide an export named 'Choice'\n```\n\n```text\nexport class Choice {\n id!: number;\n value!: string;\n}\n```\n\n```text\n/src/lib/choice.ts\n```\n\n```js\nimport type { Choice } from \"$lib/choice\";\n```\n\n```text\n{\n \"compilerOptions\": {\n // this ensures that types are explicitly\n // imported with `import type`, which is\n // necessary as svelte-preprocess cannot\n // otherwise compile components correctly\n \"importsNotUsedAsValues\": \"error\",\n```\n\n```text\ntsconfig.json\n```\n\n========================================\n\nComments:\n- thanks so much for asking this question - I could not understand what was happening and it took a lot of googling to find this.\n- That was it, adding type allowed it to work. I've accepted the answer, but is there a bit more explanation? Is this because interfaces just \"vanish\" when compiled to JS by TypeScript, or is there something else going on...?\n- @WillIverson It is because of components being processed in isolation. See this issue.\n- Very interesting. I can tell I'm getting better at TypeScript as I can [most] of that thread. ;) Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:40.698Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":105,"estimatedTokens":624}}520{"id":"stack-64371716","source":"stackoverflow","questionId":64371716,"title":"How to integrate a Svelte page with Express?","tags":["node.js","express","web","backend","svelte"],"text":"Title: How to integrate a Svelte page with Express?\nTags: node.js, express, web, backend, svelte\nSource: Stack Overflow\n\nQuestion:\nSo I want to use a form in my svelte page to send emails with nodemailer. I want to integrate my svelte form with my contact.js file. I have a template contact.js file, but it uses express-handlebars to integrate with a contact.handlebars form. So instead of using handlebars, I am using svelte here. How can I integrate them??\n\nthe contact.js template:\n\n```\nconst bodyParser = require('body-parser');\nconst exphbs = require('express-handlebars');\nconst mailer = require('nodemailer');\n\nconst app = express();\n\napp.engine('handlebars', exphbs());\napp.set('view engine', 'handlebars');\n\napp.use(bodyParser.urlencoded({ extended: false }));\napp.use(bodyParser.json());\n\napp.get('/contact', (req, res) => {\n res.render('contact');\n});\n```\n\nthe svelte form inside contact.svelte:\n\n```\n\n \n \n\n### Contact Us\n\n Send us a message about your questions or suggestions of any kind.\n\n \n \n \n \n \n \n \n \n {#if state === 'loading'}\n \n {:else}\n Send\n {/if}\n \n \n \n\n```\n\nI'm a newbie in node.js and svelte :( thank you in advance!\n\n========================================\n\nCode:\n```text\nconst bodyParser = require('body-parser');\nconst exphbs = require('express-handlebars');\nconst mailer = require('nodemailer');\n\nconst app = express();\n\napp.engine('handlebars', exphbs());\napp.set('view engine', 'handlebars');\n\napp.use(bodyParser.urlencoded({ extended: false }));\napp.use(bodyParser.json());\n\napp.get('/contact', (req, res) => {\n res.render('contact');\n});\n```\n\n```text\n<CourseWrapper {user}>\n <main>\n <h2>Contact Us</h2>\n <p>Send us a message about your questions or suggestions of any kind.</p>\n <ShadowedCard>\n <form on:submit|preventDefault={submit}>\n <InputGeneric label=\"Name\" bind:value={name} placeholder=\"Enter your name\" />\n <InputGeneric\n label=\"Email\"\n type=\"email\"\n bind:value={email}\n placeholder=\"Enter your email\" />\n <InputGeneric label=\"Subject\" bind:value={subject} placeholder=\"Enter your email subject\" />\n <InputGeneric label=\"Feedback\" type={null}>\n <textarea bind:value={message} placeholder=\"Enter your message\" />\n </InputGeneric>\n {#if state === 'loading'}\n <Loader.ThreeWavyBalls />\n {:else}\n <Button type=\"submit\" color>Send</Button>\n {/if}\n </form>\n </ShadowedCard>\n </main>\n</CourseWrapper>\n```\n\n```text\nconst bodyParser = require('body-parser');\nconst svelteViewEngine = require(\"svelte-view-engine\");\nconst mailer = require('nodemailer');\n\nconst app = express();\n\nlet engine = svelteViewEngine({\n env: \"dev\",\n template: \"./template.html\",\n dir: \"./pages\",\n type: \"html\",\n buildDir: \"../artifacts/pages\",\n});\n \napp.engine(engine.type, engine.render);\napp.set(\"view engine\", engine.type);\napp.set(\"views\", engine.dir);\n\napp.use(bodyParser.urlencoded({ extended: false }));\napp.use(bodyParser.json());\n\napp.get('/contact', (req, res) => {\n // pass user object to template\n res.render('contact', { user: //tbd });\n});\n```\n\n========================================\n\nComments:\n- hi! thank you for the help! by the way, i'm still confused on the \"template\", \"dir\", and \"buildDir\" part, because my contact.svelte and contact.js are inside the same folder. So should I set template to contact.svelte? and what shall i set dir and buildDir to? Thanks!\n- Actually I haven't worked with it before, but it's explained in detail on the github-page: github.com/svelte-view-engine/svelte-view-engine#root-templa‌​te\n- Thank you so much! ^^\n- Please don't forget to accept my answer by clicking the checkmark to the left, if this solved your problem:)\n- Any idea if it's possible to mix view engines in the same app? I'd really like if I could slowly translate all my Pug files into Svelte, one by one, instead of having to do all of them at once.","metadata":{"transformedAt":"2026-08-18T18:33:40.698Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":144,"estimatedTokens":1031}}521{"id":"stack-79050957","source":"stackoverflow","questionId":79050957,"title":"Sending query parameter via SvelteKit form action","tags":["javascript","forms","svelte","query-string","sveltekit"],"text":"Title: Sending query parameter via SvelteKit form action\nTags: javascript, forms, svelte, query-string, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have created a website using SvelteKit. I am using form action for handling login form.\n\n`src/routes/(beforeAuth)/login/+page.svelte` have login form\n\n```\n\n Username:\n \n\n Password:\n \n\n \n\n```\n\n`src/routes/(beforeAuth)/login/+page.server.js` have login action\n\n```\nexport const actions = {\n login: async ({ cookies, request }) => {\n const data = await request.formData();\n let body\n try{\n body = await api.post(\"account/login/\", {\n username: data.get('username'),\n password: data.get('password')\n });\n }catch(err) {\n return {\n message: \"username or password is not vailid\",\n login: false\n }\n }\n \n if (body.status === 401) {\n return fail(401, { tryAgain: true })\n \n }\n if(body.status == 400) {\n return {\n message: body.data.message,\n login: false\n }\n }\n \n if(body.status == 200) {\n const value = btoa(JSON.stringify(body));\n cookies.set('jwt', value, { secure: false, path: '/', maxAge:60 * 60 * 6 });\n redirect(307, '/my-profile')\n \n } else {\n return {\n message: \"username or password is not vailid\",\n login: false\n }\n }\n },\n logout: async ({ cookies, locals }) => {\n cookies.delete('jwt', {path:'/'});\n locals.user = null;\n },\n};\n```\n\nThis login form and action is woring fine. But now I want to send query parameter via form action. So I tried set action to `/login?/login?redirect=some-path`\n\ne.g.\n\n```\n\n```\n\nThis is giving me error\n\n```\nSvelteKitError: No action with name 'login?redirect' found\n```\n\nWhat is right way to send query parameter via form action in SvelteKit?\n\n========================================\n\nCode:\n```js\n<form use:enhance method=\"post\" action=\"/login?/login\">\n\n <label>Username:</lable>\n <input type=\"text\" name=\"username\" />\n\n <label>Password:</lable>\n <input type=\"password\" name=\"password\" />\n\n <Button text=\"Sign In\" type=\"submit\" />\n<form>\n```\n\n```js\nexport const actions = {\n login: async ({ cookies, request }) => {\n const data = await request.formData();\n let body\n try{\n body = await api.post(\"account/login/\", {\n username: data.get('username'),\n password: data.get('password')\n });\n }catch(err) {\n return {\n message: \"username or password is not vailid\",\n login: false\n }\n }\n \n if (body.status === 401) {\n return fail(401, { tryAgain: true })\n \n }\n if(body.status == 400) {\n return {\n message: body.data.message,\n login: false\n }\n }\n \n if(body.status == 200) {\n const value = btoa(JSON.stringify(body));\n cookies.set('jwt', value, { secure: false, path: '/', maxAge:60 * 60 * 6 });\n redirect(307, '/my-profile')\n \n } else {\n return {\n message: \"username or password is not vailid\",\n login: false\n }\n }\n },\n logout: async ({ cookies, locals }) => {\n cookies.delete('jwt', {path:'/'});\n locals.user = null;\n },\n};\n```\n\n```html\n<form use:enhance method=\"post\" action=\"/login?/login?redirect=some-path\">\n```\n\n```text\nSvelteKitError: No action with name 'login?redirect' found\n```\n\n```text\nsrc/routes/(beforeAuth)/login/+page.svelte\n```\n\n```text\nsrc/routes/(beforeAuth)/login/+page.server.js\n```\n\n```text\n/login?/login?redirect=some-path\n```\n\n```text\n/\n```\n\n```text\n/login?/login\n```\n\n```text\n?\n```\n\n```text\n?\n```\n\n```text\nlogin?redirect\n```\n\n```text\n/login?/login&redirect=some-path\n```\n\n```text\n?\n```\n\n```text\n/login\n```\n\n```text\n/\n```\n\n```text\n&\n```\n\n```text\nredirect=some-path\n```\n\n```text\nurl\n```\n\n```text\nsearchParams\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.698Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":220,"estimatedTokens":965}}522{"id":"stack-75812548","source":"stackoverflow","questionId":75812548,"title":"SvelteKit stores don't match client-side and server-side","tags":["javascript","svelte","server-side-rendering","store","sveltekit"],"text":"Title: SvelteKit stores don't match client-side and server-side\nTags: javascript, svelte, server-side-rendering, store, sveltekit\nSource: Stack Overflow\n\nQuestion:\nIn SvelteKit, it seems that stores do not sync between the client-side and server-side. In other words, if one modifies a store on the client-side, when it is retrieved on the server-side, it will not be modified, and vice versa.\n\nYou can see this behaviour in the minimal reproducible example below:\n\nhttps://stackblitz.com/edit/sveltejs-kit-template-default-fpp2y8?file=src/routes/+page.svelte\n\n**My question is: What is the idiomatic, or normal way to modify a server-side store when on the client-side?**\n\nTo avoid the XY Problem, what I am trying to do specifically is the following:\n\nThe user of an EPOS system has a 'currentSale' store, which is loaded on accessing the `/epos` route on the server-side, specifically so that Prisma can get more information about the products, customer attached etc.\n\nHowever, the problem arises when, for example, the user tries to increment the quantity of a product in the EPOS sale. Trying to update the store does not work, as it doesn't save server-side. And using a whole API route, or form action seems overkill and not optimized/optimal.\n\n========================================\n\nCode:\n```text\n/epos\n```\n\n========================================\n\nComments:\n- I see; How should I store this data then? It needs to be loaded server-side due to `Prisma` only allowing server-side access, but at the same time, it needs to be editable client-side for quick and responsive modification - I was thinking of `localStorage` but that has a similar pitfall in being client-side specific. Is there some Svelte/SvelteKit feature I'm forgetting about, or how should I go about this?\n- Stores have very specific purposes, most of the time you do not need them at all. All state within a component is reactive by default. Data from the server should be provided by a `load` function, if it has to execute on the server, put it in `+page.server.js`/`ts`. If you change something via a form action, the data is invalidated automatically and reloaded if you use `enhance`.","metadata":{"transformedAt":"2026-08-18T18:33:40.698Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":31,"estimatedTokens":542}}523{"id":"stack-75929119","source":"stackoverflow","questionId":75929119,"title":"How can I include \"example projects\" for my Svelte component module?","tags":["npm","svelte","sveltekit","directory-structure","svelte-component"],"text":"Title: How can I include \"example projects\" for my Svelte component module?\nTags: npm, svelte, sveltekit, directory-structure, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI'm developing a Svelte module for publishing as an npm package. I'd like to include examples that are longer than a few lines. What's the standard approach for this?\n\nI don't think it makes sense to burden the original module with additional dependencies needed for examples. I could create a separate Github project mymodule-examples, but it also feels wrong to separate the module and examples into two repositories. Due to the nature of sveltekit, each example requires several files.\n\n========================================\n\nTop Answer:\nAppears to me the following ways:\n\n### /examples directory:\n\nCreate an /examples folder in your module's repo with separate subdirectories for each example. Add a README.md for instructions and include /examples in .npmignore to avoid publishing it to npm.\n\n### Monorepo:\n\nUse a /packages folder in your repo containing your main module and separate example projects. Each example will have its own package.json for managing dependencies.\n\n### Submodules:\n\nCreate separate repositories for each example and include them as submodules in your main module's repo inside an /examples folder. Provide instructions for cloning and initializing submodules in your README.md.\n\n========================================\n\nCode:\n```text\nfiles\n```\n\n```text\npackage.json\n```\n\n```text\nfiles\n```\n\n```text\n.npmignore\n```\n\n```text\ndependencies\n```\n\n```text\ndevDependencies\n```\n\n```text\ndependencies\n```\n\n```text\ndevDependencies\n```\n\n========================================\n\nComments:\n- I haven't used it myself yet, but: kit.svelte.dev/docs/packaging\n- Thanks for chiming in @voscausa. I've read that part of the docs but can't find any suggestions on where to put example apps using my module.\n- I don't think an NPM package is the correct place to add examples. You should just include a README that points to an examples repository. Why should you force consumers to download samples every time? Developers should just read the documentation, learn from the examples, and that should be it.\n- Thanks for taking your time. My main question is what the standard approach is for supplying examples for my (svelte) npm package?\n- Ah, are you suggesting that I include the examples in the github repository, but upload the package without examples (and example dependencies) to npm?\n- @Anna: Correct. (Include the examples in the github repository, but upload the package without examples (and example dependencies) to npm)\n- @Anna: I updated my answer with a quote from the Kit docs.\n- Thank you. Would you put the github pages in the main repository?\n- Yeah, you would create a repository just for your docs portion of the web app / api. I suggest looking at Laravel & torchlight for highlighting of your codeblock. This is how laravel handles it for the docs on their official site github.com/laravel/docs & github.com/laravel/laravel.com","metadata":{"transformedAt":"2026-08-18T18:33:40.699Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":73,"estimatedTokens":762}}524{"id":"stack-74944587","source":"stackoverflow","questionId":74944587,"title":"How to update rendered content when my variable changes in Svelte/Svelte Kit","tags":["svelte","sveltekit"],"text":"Title: How to update rendered content when my variable changes in Svelte/Svelte Kit\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a simple svelte page in sveltekit:\n\n```\n\n let array = [1, 2, 3, 4, 5];\n\n{#each array as item}\n \n- {item}\n{/each}\n\n {\n array.push('4');\n console.log(array);\n }}>Click Me\n```\n\nPretty simple concept. When I update my array, I want the content on the page to be updated as well. Can someone help me on the road to figuring out what I need to do this? Thanks IA!\n\nPS-- The array is successfully updating on the button click\n\n========================================\n\nCode:\n```text\n<script>\n let array = [1, 2, 3, 4, 5];\n</script>\n\n{#each array as item}\n <li>{item}</li>\n{/each}\n\n<button\n on:click={() => {\n array.push('4');\n console.log(array);\n }}>Click Me</button\n>\n```\n\n```html\n<script>\n let array = [1, 2, 3, 4, 5];\n</script>\n\n{#each array as item}\n <li>{item}</li>\n{/each}\n\n<button\n on:click={() => {\n array.push('4');\n array = array;\n }}\n>\n Click Me\n</button>\n```\n\n```text\npush\n```\n\n```text\narray = array\n```\n\n========================================\n\nComments:\n- This is a bit verbose as you can do `array = [...array, 4]`","metadata":{"transformedAt":"2026-08-18T18:33:40.699Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":77,"estimatedTokens":307}}525{"id":"stack-72544499","source":"stackoverflow","questionId":72544499,"title":"Object in store and reactive statements","tags":["svelte"],"text":"Title: Object in store and reactive statements\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI have a store holding an object. I want to be able to have several reactive statements, each reacting to a change in a given property of the object.\n\nHere's an example (REPL: https://svelte.dev/repl/38f15dc921034532be8dd2d774ca2096?version=3.48.0):\n\n```\n\nimport { writable } from \"svelte/store\";\nconst catalogue = writable({ currentBook: \"War'n'Peace\", currentFood: \"Authentic Napoli frozen pizza\" });\n\n$: $catalogue.currentBook, console.log(\"Current book has changed\");\n$: $catalogue.currentFood, console.log(\"Current food has changed\");\n\nfunction changeBook() { $catalogue.currentBook = \"Putin's People\"; }\nfunction changeFood() { $catalogue.currentFood = \"Authentic Valencia chorizo and mussels paella\"; }\n\nChange book\nChange food\n```\n\nA click on \"change food\", for instance, triggers the two reactive statements, not just the one intended to react to a change on the `food` property.\n\nI'm not certain how stores and reactive statements play together, but it seems that reactivity happens even without a variable assignment. Unfortunately, it seems also that *any* change in the object triggers all the reactive statements referencing the store, which is not what I hoped.\n\nIs there a solution you could suggest along those lines, or another approach?\n\n========================================\n\nCode:\n```html\n<script>\nimport { writable } from \"svelte/store\";\nconst catalogue = writable({ currentBook: \"War'n'Peace\", currentFood: \"Authentic Napoli frozen pizza\" });\n\n$: $catalogue.currentBook, console.log(\"Current book has changed\");\n$: $catalogue.currentFood, console.log(\"Current food has changed\");\n\nfunction changeBook() { $catalogue.currentBook = \"Putin's People\"; }\nfunction changeFood() { $catalogue.currentFood = \"Authentic Valencia chorizo and mussels paella\"; }\n</script>\n\n<button on:click={changeBook}>Change book</button>\n<button on:click={changeFood}>Change food</button>\n```\n\n```text\nfood\n```\n\n```js\n$: ({ currentBook, currentFood } = $catalogue);\n$: currentBook, console.log(\"Current book has changed\");\n$: currentFood, console.log(\"Current food has changed\");\n```\n\n```js\nconst currentBook = derived(catalogue, c => c.currentBook);\nconst currentFood = derived(catalogue, c => c.currentFood);\n$: $currentBook, console.log(\"Current book has changed\");\n$: $currentFood, console.log(\"Current food has changed\");\n```\n\n========================================\n\nComments:\n- Thanks for your answer, it was helpful. In my case, derived stores won't work because I also need to be able to update the values. I finally think that the simplest solution is to not structure the store as an object, but to have a store attached to each variable. Using a separate module for the store, something like: `export const currentBook = writable(\"\"); export const currentFood = writable(\"\");` instead of `export const catalogue = writable({ currentBook: \"\", currentFood: \"\" })`. (Only minor drawback is that I lose the \"namespacing\" of the object.)","metadata":{"transformedAt":"2026-08-18T18:33:40.699Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":70,"estimatedTokens":760}}526{"id":"stack-73294831","source":"stackoverflow","questionId":73294831,"title":"API request blocked by CORS policy with Confluent Cloud and Kafka","tags":["cors","fetch-api","aws-amplify","svelte","confluent-cloud"],"text":"Title: API request blocked by CORS policy with Confluent Cloud and Kafka\nTags: cors, fetch-api, aws-amplify, svelte, confluent-cloud\nSource: Stack Overflow\n\nQuestion:\nI'm trying to post a message on a Kafka cluster on Confluent cloud. It works fine on Postman, but when I try on my Svelte app, I got this error:\n\nAccess to fetch at from origin 'http://localhost:3000'\nhas been blocked by CORS policy: Response to preflight request doesn't\npass access control check: No 'Access-Control-Allow-Origin' header is\npresent on the requested resource. If an opaque response serves your\nneeds, set the request's mode to 'no-cors' to fetch the resource with\nCORS disabled.\n\n**The request looks like this:**\n\n\r\n\r\n\n```\nvar apiHeaders = new Headers();\napiHeaders.append(\"Content-Type\", \"application/json\");\napiHeaders.append(\"Authorization\", \"Basic \");\n\nconst clusterId = '';\nconst restEndpoint = '';\n\nconst postMessage = (data, topic) => {\n let raw = JSON.stringify({\n \"value\": {\n \"type\": \"JSON\",\n \"data\": {\n data\n }\n }\n });\n\n let requestOptions = {\n method: 'POST',\n headers: apiHeaders,\n body: raw,\n redirect: ''\n };\n\n fetch(`${restEndpoint}/kafka/v3/clusters/${clusterId}/topics/${topic}/records`, requestOptions)\n .then(response => response.text())\n .then(result => console.log(result))\n .catch(error => console.log('error', error));\n}\n\nexport const sendLogMessage = (data) => {\n postMessage(data, '');\n}\n```\n\n\r\n\r\n\r\n\n**My headers are set like this on AWS Amplify:**\n\nhttps://i.sstatic.net/Nv8hI.png\n\n**And also my headers are set like this on `svelte.config.js`:**\n\n\r\n\r\n\n```\nimport adapter from '@sveltejs/adapter-static';\n// import adapter from '@sveltejs/adapter-node';\n// import adapter from '@sveltejs/adapter-auto';\n// import firebase from \"svelte-adapter-firebase\";\n\n/** @type {import('vite').Plugin} */\nconst viteServerConfig = {\n name: 'log-request-middleware',\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.setHeader(\"Access-Control-Allow-Methods\", \"GET, HEAD, POST\");\n res.setHeader(\"Cross-Origin-Resource-Policy\", \"cross-origin\");\n res.setHeader(\"Cross-Origin-Opener-Policy\", \"same-origin\");\n res.setHeader(\"Cross-Origin-Embedder-Policy\", \"require-corp\");\n res.setHeader(\"Access-Control-Allow-Headers\", \"Content-Type,X-Amz-Date,Authorization,X-Api-Key,x-requested-with\");\n next();\n });\n }\n};\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n kit: {\n adapter: adapter(), // for the firebase adapter use \"firebase()\" instead of \"adapter()\"\n vite: {\n plugins: [viteServerConfig]\n },\n prerender: {\n default: true\n },\n trailingSlash: 'never'\n }\n};\n\nexport default config;\n```\n\n========================================\n\nTop Answer:\nThere's not much details on how the application is set up, nor am I an expert with Confluent Cloud.\n\nBut, if your Svelte app is running in http://localhost:3000 and it tries to send requests to Confluent Cloud API (I assume this is the ENDPOINT shown in the example), then you should be making the CORS configurations in the Confluent Cloud end to enable communications from the app to Confluent.\n\nHow the Confluent end can be configured, unfortunately don't have knowledge on that.\n\n========================================\n\nCode:\n```js\nvar apiHeaders = new Headers();\napiHeaders.append(\"Content-Type\", \"application/json\");\napiHeaders.append(\"Authorization\", \"Basic <BASE64>\");\n\nconst clusterId = '<CLUSTERID>';\nconst restEndpoint = '<ENDPOINT>';\n\nconst postMessage = (data, topic) => {\n let raw = JSON.stringify({\n \"value\": {\n \"type\": \"JSON\",\n \"data\": {\n data\n }\n }\n });\n\n let requestOptions = {\n method: 'POST',\n headers: apiHeaders,\n body: raw,\n redirect: 'follow'\n };\n\n fetch(`${restEndpoint}/kafka/v3/clusters/${clusterId}/topics/${topic}/records`, requestOptions)\n .then(response => response.text())\n .then(result => console.log(result))\n .catch(error => console.log('error', error));\n}\n\n\n\nexport const sendLogMessage = (data) => {\n postMessage(data, '<TOPICNAME>');\n}\n```\n\n```js\nimport adapter from '@sveltejs/adapter-static';\n// import adapter from '@sveltejs/adapter-node';\n// import adapter from '@sveltejs/adapter-auto';\n// import firebase from \"svelte-adapter-firebase\";\n\n/** @type {import('vite').Plugin} */\nconst viteServerConfig = {\n name: 'log-request-middleware',\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.setHeader(\"Access-Control-Allow-Methods\", \"GET, HEAD, POST\");\n res.setHeader(\"Cross-Origin-Resource-Policy\", \"cross-origin\");\n res.setHeader(\"Cross-Origin-Opener-Policy\", \"same-origin\");\n res.setHeader(\"Cross-Origin-Embedder-Policy\", \"require-corp\");\n res.setHeader(\"Access-Control-Allow-Headers\", \"Content-Type,X-Amz-Date,Authorization,X-Api-Key,x-requested-with\");\n next();\n });\n }\n};\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n kit: {\n adapter: adapter(), // for the firebase adapter use \"firebase()\" instead of \"adapter()\"\n vite: {\n plugins: [viteServerConfig]\n },\n prerender: {\n default: true\n },\n trailingSlash: 'never'\n }\n};\n\nexport default config;\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nKAFKA_REST_ACCESS_CONTROL_ALLOW_ORIGIN: \"*\"\nKAFKA_REST_ACCESS_CONTROL_ALLOW_METHODS: \"GET,POST,PUT,DELETE\"\nKAFKA_REST_ACCESS_CONTROL_ALLOW_HEADERS: \"origin,content-type,accept,authorization\"\n```\n\n```text\nOPTIONS\n```\n\n```text\nOPTIONS\n```\n\n```text\nrest-proxy.yml\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.699Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":217,"estimatedTokens":1431}}527{"id":"stack-70863311","source":"stackoverflow","questionId":70863311,"title":"How to import a typescript module into Svelte Component","tags":["typescript","svelte"],"text":"Title: How to import a typescript module into Svelte Component\nTags: typescript, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to import a self-written TypeScript module into a svelte component. But I'm receiving the error that the module was not exported from its file even though I have done that.\nDoes anybody have an idea how to solve this problem ?\n\n**My Code:**\n\ntelegram_bot.ts\n\n```\nexport class TelegramBotForSafetyMania {...}\n```\n\nHome.svelte\n\n```\nimport * as telegramBot from './../telegram_bot';\nlet bot = TelegramBotForSafetyMania.startBot();\n```\n\n========================================\n\nTop Answer:\nAssuming `startBot` is a static method on your class:\n\n`telegram_bot.ts`:\n\n```\nexport class TelegramBotForSafetyMania {...}\n```\n\n`Home.svelte`:\n\n```\nimport * as telegramBot from './../telegram_bot';\n\nconst {TelegramBotForSafetyMania} = telegramBot;\n\nlet bot = TelegramBotForSafetyMania.startBot();\n```\n\n========================================\n\nCode:\n```text\nexport class TelegramBotForSafetyMania {...}\n```\n\n```text\nimport * as telegramBot from './../telegram_bot';\nlet bot = TelegramBotForSafetyMania.startBot();\n```\n\n```text\n./\n```\n\n```text\nimport {TelegramBotForSafetyMania} from '../telegram_bot'\n```\n\n```ts\nexport class TelegramBotForSafetyMania {...}\n```\n\n```ts\nimport * as telegramBot from './../telegram_bot';\n\nconst {TelegramBotForSafetyMania} = telegramBot;\n\nlet bot = TelegramBotForSafetyMania.startBot();\n```\n\n```text\nstartBot\n```\n\n```text\ntelegram_bot.ts\n```\n\n```text\nHome.svelte\n```\n\n========================================\n\nComments:\n- Thank you for your answer @jsejcksn! I found out that I should have imported the module without the `./` at the beginning. So the line `import {TelegramBotForSafetyMania} from '../telegram_bot'` solved this issue.\n- However, now I'm facing another error while importing the module. I created a question to it. I will really appreciate it if you could help me with solving it. stackoverflow.com/questions/70876587/…","metadata":{"transformedAt":"2026-08-18T18:33:40.699Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":93,"estimatedTokens":501}}528{"id":"stack-73009430","source":"stackoverflow","questionId":73009430,"title":"SvelteKit returns window.innerWidth as undefined on initial page load","tags":["svelte","sveltekit"],"text":"Title: SvelteKit returns window.innerWidth as undefined on initial page load\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have two separate components, one that is intended for mobile devices and the other for desktop. Only one component should displayed at a time, depending on width of the user's browser window. Here's a condensed version that I have:\n\n```\n\n let innerWidth\n\n Inner Width: {innerWidth}\n\n{#if innerWidth > 800}\n Desktop Content\n{:else}\n Mobile Content\n{/if}\n```\n\nI noticed that when I load the page, `{innerWidth}` quickly switches from `undefined` to the appropriate value. For desktop users, this is a problem because the Mobile content is displayed because at the time of evaluating `{#if innerWidth > 800}`, Svelte has `innerWidth = undefined`.\n\nInterestingly enough, this problem only occurs when I load the page directly. If I had this feature on /subpage, the intended functionality would work if I visited /index and then /subpage.\n\nIs there a way to return the appropriate value on initial page load without it recognizing `undefined`? I would like to avoid using CSS media queries, but it is a last resort.\n\n========================================\n\nTop Answer:\nIs there a way to return the appropriate value on initial page load without it recognizing `undefined`?\n\nNot with the default configuration as SvelteKit uses server-side rendering on the first page load. There is no way to get that information on the server.\n\nIf you want to prevent displaying the wrong content you can also wrap your content in an additional `#if`.\n\n```\n{#if innerWidth != null}\n {#if innerWidth > 800}\n Desktop Content\n {:else}\n Mobile Content\n {/if}\n{/if}\n```\n\n========================================\n\nCode:\n```text\n<script>\n let innerWidth\n</script>\n\n<svelte:window bind:innerWidth />\n\n<p>\n Inner Width: {innerWidth}\n</p>\n\n{#if innerWidth > 800}\n Desktop Content\n{:else}\n Mobile Content\n{/if}\n```\n\n```text\n{innerWidth}\n```\n\n```text\nundefined\n```\n\n```text\n{#if innerWidth > 800}\n```\n\n```text\ninnerWidth = undefined\n```\n\n```text\nundefined\n```\n\n```text\n<script>\n import Vnav from './Vnav.svelte';\n import Hnav from './Hnav.svelte';\n let screenWidth;\n $: if (screenWidth > 800) {\n <!-- close sidebar -->\n } else {\n <!-- open sidebar -->\n }\n </script>\n\n <svelte:window bind:innerWidth={screenWidth} />\n\n {#if screenWidth > 800}\n <Hnav />\n {:else}\n <Vnav />\n {/if}\n```\n\n```text\ninnerWidth\n```\n\n```text\n/index\n```\n\n```text\n/subpage\n```\n\n```text\ninnerWidth\n```\n\n```html\n{#if innerWidth != null}\n {#if innerWidth > 800}\n Desktop Content\n {:else}\n Mobile Content\n {/if}\n{/if}\n```\n\n```text\nundefined\n```\n\n```text\n#if\n```\n\n```text\n<script>\n import { browser } from '$app/env';\n\n let innerWidth // you can also set your default width\n\n if (browser){\n innerWidth = window.innerWidth;\n }\n</script>\n\n\n{#if innerWidth > 800}\n <DesktopContent />\n{:else}\n <MobileContent />\n{/if}\n```\n\n```text\n<script>\n import { browser } from '$app/env';\n\n let innerWidth // you can also set your default width\n\n const updateWindowSize = () =>{\n innerWidth = window.innerWidth;\n }\n if (browser){\n updateWindowSize() // to set the initial window size\n window.onresize = updateWindowSize; // run when ever the window size change\n \n }\n</script>\n```\n\n========================================\n\nComments:\n- \"Cannot find module '$app/env'\"","metadata":{"transformedAt":"2026-08-18T18:33:40.699Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":181,"estimatedTokens":867}}529{"id":"stack-71404333","source":"stackoverflow","questionId":71404333,"title":"Error in svelte.config.js and Error: Identifier is expected in scss style tag - Svelte","tags":["sass","svelte","sveltekit"],"text":"Title: Error in svelte.config.js and Error: Identifier is expected in scss style tag - Svelte\nTags: sass, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm getting the following error in some of my .svelte files that contain `` tags.\n\n```\nError in svelte.config.js\n\nError: Identifier is expected (23:9)\n21: flex-direction: column;\n22: align-items: center;\n23: * {\n ^\n24: padding: 0 0 1rem 0;\n25: width: 50vw;\n```\n\nThe error always points to the same file, `/src/routes/blog/_blog.svelte`, which is the layout file for mdsvex. I would just ignore the error as the page works without issue otherwise, but the error prevents me from running the dev server, building, or previewing. I can get around the issue by removing the offending style tag, starting the server, and then adding it back. After uncommenting it and saving the page loads fine and the server doesn't error.\n\nThe offending style tag is:\n\n```\n\n .container {\n display: flex;\n flex-direction: column;\n align-items: center;\n * {\n padding: 0 0 1rem 0;\n width: 50vw;\n :global(p) {\n padding-bottom: 1rem;\n }\n :global(blockquote) {\n margin: .5rem 0 1rem 1rem;\n padding: 1rem .5rem 0 1rem;\n border-left: 2px solid $orange;\n }\n :global(ul) {\n margin-top: .5rem;\n }\n :global(li) {\n margin-left: 1.5rem;\n }\n :global(code) {\n font-family: 'Courier New', Courier, monospace;\n background-color: $bg-secondary;\n padding: .25rem;\n border-radius: 5px;\n }\n :global(pre) {\n font-family: 'Courier New', Courier, monospace;\n background-color: $bg-secondary;\n padding: .25rem;\n border-radius: 5px;\n max-width: fit-content;\n margin-bottom: .5rem;\n }\n :global(img) {\n max-width: 50vw;\n }\n }\n h1,h2,h3 {\n padding-bottom: 0;\n }\n }\n\n```\n\nMy svelte.config.js is:\n\n```\nimport adapter from '@sveltejs/adapter-auto';\nimport sveltePreprocess from 'svelte-preprocess';\nimport { mdsvex } from 'mdsvex'\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n kit: {\n adapter: adapter()\n },\n\n extensions: ['.svelte', '.md'],\n \n preprocess: [\n sveltePreprocess({\n scss: {\n prependData: `@import './src/style/app.scss';`\n } \n }),\n mdsvex({\n extensions: ['.md'],\n layout: {\n blog: 'src/routes/blog/_blog.svelte'\n }\n })\n ],\n\n};\nexport default config;\n```\n\nMy versions are:\n\nsvelte: v3.46.4\n\nsvelte-preprocess: v4.10.4\n\nsass: v1.49.9\n\nmdsvex: v0.10.5\n\n========================================\n\nTop Answer:\nThis is related to MDsveX issue:116 as pointed out by Bob Fanger. The current workaround is to \"wrap your actual Layout in another 'plain' svelte component, that only passes down frontmatter props\" (from jfcieslak in the GH thread).\n\nThe new files are:\n\n`svelte.config.js`\n\n```\n...\npreprocess: [\n sveltePreprocess({\n scss: {\n prependData: `@import './src/style/app.scss';`\n } \n }),\n mdsvex({\n extensions: ['.md'],\n layout: {\n blog: 'src/routes/blog/blogLayout.svelte'\n }\n })\n ],\n...\n```\n\n`blogLayout.svelte`\n\n```\n\n import Layout from './_blog.svelte'\n export let title\n export let date\n\n \n\n```\n\n`_blog.svelte` is unchanged.\n\n========================================\n\nCode:\n```text\nError in svelte.config.js\n\nError: Identifier is expected (23:9)\n21: flex-direction: column;\n22: align-items: center;\n23: * {\n ^\n24: padding: 0 0 1rem 0;\n25: width: 50vw;\n```\n\n```text\n<style lang=\"scss\">\n .container {\n display: flex;\n flex-direction: column;\n align-items: center;\n * {\n padding: 0 0 1rem 0;\n width: 50vw;\n :global(p) {\n padding-bottom: 1rem;\n }\n :global(blockquote) {\n margin: .5rem 0 1rem 1rem;\n padding: 1rem .5rem 0 1rem;\n border-left: 2px solid $orange;\n }\n :global(ul) {\n margin-top: .5rem;\n }\n :global(li) {\n margin-left: 1.5rem;\n }\n :global(code) {\n font-family: 'Courier New', Courier, monospace;\n background-color: $bg-secondary;\n padding: .25rem;\n border-radius: 5px;\n }\n :global(pre) {\n font-family: 'Courier New', Courier, monospace;\n background-color: $bg-secondary;\n padding: .25rem;\n border-radius: 5px;\n max-width: fit-content;\n margin-bottom: .5rem;\n }\n :global(img) {\n max-width: 50vw;\n }\n }\n h1,h2,h3 {\n padding-bottom: 0;\n }\n }\n</style>\n```\n\n```js\nimport adapter from '@sveltejs/adapter-auto';\nimport sveltePreprocess from 'svelte-preprocess';\nimport { mdsvex } from 'mdsvex'\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n kit: {\n adapter: adapter()\n },\n\n extensions: ['.svelte', '.md'],\n \n preprocess: [\n sveltePreprocess({\n scss: {\n prependData: `@import './src/style/app.scss';`\n } \n }),\n mdsvex({\n extensions: ['.md'],\n layout: {\n blog: 'src/routes/blog/_blog.svelte'\n }\n })\n ],\n\n};\nexport default config;\n```\n\n```text\n<style lang=\"scss\">\n```\n\n```text\n/src/routes/blog/_blog.svelte\n```\n\n```js\n...\npreprocess: [\n sveltePreprocess({\n scss: {\n prependData: `@import './src/style/app.scss';`\n } \n }),\n mdsvex({\n extensions: ['.md'],\n layout: {\n blog: 'src/routes/blog/blogLayout.svelte'\n }\n })\n ],\n...\n```\n\n```html\n<script lang=\"ts\">\n import Layout from './_blog.svelte'\n export let title\n export let date\n</script>\n\n<Layout title={title} date={date}>\n <slot />\n</Layout>\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nblogLayout.svelte\n```\n\n```text\n_blog.svelte\n```\n\n========================================\n\nComments:\n- I'll have to try the workaround there, thanks!\n- The workaround in that thread worked! I added it as a new answer here, again ty!","metadata":{"transformedAt":"2026-08-18T18:33:40.699Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":304,"estimatedTokens":1512}}530{"id":"stack-67512558","source":"stackoverflow","questionId":67512558,"title":"Sveltekit serverless adapter like vercel or adapter static?","tags":["svelte","vercel","sveltekit"],"text":"Title: Sveltekit serverless adapter like vercel or adapter static?\nTags: svelte, vercel, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI developed a site with sveltekit:svelte: (@sveltejs/kit\": \"1.0.0-next.95). The articles are written markdown so I am using mdsvex for the conent.\n\nI deployed the site both with adapter vercel and adapter static in cloudflare pages.\n\nBoth scripts run fine and I am just trying to understand the benefits of using the severless function with vercel adapter vs running the site as a static export with the adapter static that would work anywhere (including vercel even without their adapter that has a severless function).\n\n========================================\n\nComments:\n- With adapter-static, should I be able to run the site locally from index.html file in the build directory? And, also, just by dropping the contents of the build directory into my standard shared hosting? (I can't, so wondering whether this is expected behaviour or whether I have other problems.)\n- You can host the site locally from the build directory using IIS or Node - it doesn't seem to just work from the file system.","metadata":{"transformedAt":"2026-08-18T18:33:40.699Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":16,"estimatedTokens":284}}531{"id":"stack-71206401","source":"stackoverflow","questionId":71206401,"title":"How to run animation only on first page visit","tags":["svelte","sveltekit"],"text":"Title: How to run animation only on first page visit\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\non the sveltekit website I'm currently building I want to play a simple intro animation on the index page if it is the entrypoint to the app. If a user used the navigation to load the index page the animation should not play.\n\nSo i'm looking for a simple way to detect if a page is the entrypoint from that session or not.\n\nHere is an example page with such functionality reed.be/\n\n========================================\n\nTop Answer:\nI assume you want to use `in:` with a custom transition. Since there are no ways (that I know of) to enable or disable a transition conditionally on an element, you could send a custom parameter to the transition function that indicates if it is the first load or not, and if it is you can enable or disable (i.e. set duration to 0 or something like that) the transition in the transition code itself. The first load variable could be a global store.\n\nNot recommended but another way I see is to have two if blocks on the first load variable so you have two sets of the dom code but one is without the `in:` transition.\n\n========================================\n\nCode:\n```html\n<script>\n import { afterNavigate } from '$app/navigation';\n import { fade } from 'svelte/transition';\n\n // hide by default\n let visible = false;\n\n let duration;\n\n afterNavigate(({ from }) => {\n // only animate if the navigation came from outside the page\n duration = from === null ? 600 : 0;\n // toggle visbility in any case\n visible = true;\n });\n</script>\n\n{#if visible}\n <h1 in:fade={{ duration }}>Welcome to SvelteKit</h1>\n{/if}\n```\n\n```text\nafterNavigate\n```\n\n```text\nin:\n```\n\n```text\nin:\n```\n\n========================================\n\nComments:\n- Thank you for the ideas, ich think i will create a custom transition function with an enable/disable parameter\n- Thanks a lot for the snippet, thats exactly what I needed :)","metadata":{"transformedAt":"2026-08-18T18:33:40.699Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":61,"estimatedTokens":501}}532{"id":"stack-60977647","source":"stackoverflow","questionId":60977647,"title":"Is it possible to bind the same variable across multiple components with Svelte?","tags":["svelte","svelte-component"],"text":"Title: Is it possible to bind the same variable across multiple components with Svelte?\nTags: svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nIf the same component is used multiple times from the same context, is it possible for the bound property to be shared across their instances?\n\nFor instance, if I have a component that creates checkboxes, how can the selection (`bind:group`) be combined for the letter selector and the number selector?\n\nWith this example, if multiple letters are selected, the selection is properly propagated and bound. However, if numbers are then selected, the letter selection is replace with the selected numbers, instead of joining the selected numbers to the selected letters.\n\n```\n// App.svelte\n\n import Selector from './Selector.svelte';\n\n let selection = [];\n\n $: console.log(selection);\n\n### Letters\n\n### Numbers\n\n// Selector.svelte\n\n export let options;\n export let selection;\n\n {#each options as option}\n \n \n {option}\n \n {/each}\n\n```\n\nREPL: https://svelte.dev/repl/f97f859ea567473b9732b8933db870f7?version=3.20.1\n\n========================================\n\nCode:\n```html\n// App.svelte\n<script>\n import Selector from './Selector.svelte';\n\n let selection = [];\n\n $: console.log(selection);\n</script>\n\n<h2>Letters</h2>\n<Selector options={['A', 'B', 'C']} bind:selection />\n\n<h2>Numbers</h2>\n<Selector options={[1, 2, 3]} bind:selection />\n\n// Selector.svelte\n<script>\n export let options;\n export let selection;\n</script>\n\n\n<div class=\"selector\">\n {#each options as option}\n <label>\n <input type=\"checkbox\" value={option} bind:group={selection} />\n {option}\n </label>\n {/each}\n</div>\n```\n\n```text\nbind:group\n```\n\n```js\nselection = value;\n```\n\n```js\nlet selection = {};\n```\n\n```js\n<script>\n export let options;\n export let selection;\n\n let group = []\n $: for (const option of options) {\n selection[option] = group.includes(option)\n }\n</script>\n\n\n<div class=\"selector\">\n {#each options as option}\n <label>\n <input type=\"checkbox\" value={option} bind:group />\n {option}\n </label>\n {/each}\n</div>\n```\n\n```html\n<script>\n export let options;\n export let selection;\n\n let group = []\n\n const update = () => {\n selection = selection\n .filter(x => !options.includes(x))\n .concat(group)\n }\n\n // when group changes, update\n $: group, update()\n</script>\n\n<div class=\"selector\">\n {#each options as option}\n <label>\n <input type=\"checkbox\" value={option} bind:group />\n {option}\n </label>\n {/each}\n</div>\n```\n\n```text\n===\n```\n\n```text\nbind:group\n```\n\n```text\nselection\n```\n\n```text\nselection\n```\n\n```text\nselection\n```\n\n```text\nselection = selection.filter(x => !options.includes(x)).concat(group)\n```\n\n```text\nselection\n```\n\n```text\ngroup\n```\n\n========================================\n\nComments:\n- Thanks! Great answer. Much cleaner than the work around I had bodged.\n- Note: unchecked values are removed from `selection`.\n- Oops, sorry you're right. I didn't think it through. I've updated the example with something that should work better.","metadata":{"transformedAt":"2026-08-18T18:33:40.699Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":175,"estimatedTokens":785}}533{"id":"stack-59022302","source":"stackoverflow","questionId":59022302,"title":"Passing multiple parameters on Svelte action","tags":["javascript","svelte"],"text":"Title: Passing multiple parameters on Svelte action\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nAccordingly to the Svelte documentation:\n\n Actions are functions that are called when an element is created. They can return an object with a destroy method that is called after the element is unmounted\n\nI want to pass multiple parameters to a Svelte action function, but only the last one is recogonized\n\n**DEMO**\n\n```\n\n function example(node, arg1, arg2) {\n // the node has been mounted in the DOM\n console.log(arg1, arg2) // Should display 'a b', but actually only displays 'b undefined'\n return {\n destroy() {\n // the node has been removed from the DOM\n }\n }\n }\n\nHello World!\n```\n\nIs there any viable solution that avoid the use of a single object as parameter?\n\n```\n\n function example(node, arg) {\n // the node has been mounted in the DOM\n console.log(arg) // Returns a object with the arguments\n return {\n destroy() {\n // the node has been removed from the DOM\n }\n }\n }\n\nHello World!\n\n### Works like a charm!\n\n```\n\n========================================\n\nTop Answer:\nYou also can use an array.\n\nBelow a snippet of my code:\n\n```\nexport function initMapDesc(mapMark) {\n\n // make the entry (obj) and the composed search regex reactive\n return (node, [obj, pRex]) => {\n // the node has been mounted in the DOM\n node.innerHTML = mapObj(node, obj, pRex, mapMark);\n\n return {\n update([obj, pRex]) {\n node.innerHTML = mapObj(node, obj, pRex, mapMark);\n },\n // destroy the node to clear the view (on session change)\n destroy() {\n node.innerHTML = '';\n }\n };\n };\n};\n```\n\nThis code renders an object into a table `` node. The regex stream is used to search nodes and mark the search results. \n\nThe code below shows the call of the use function. A closure is used to pass an object to the use function and to receive the regex search results.\n\n```\nconst mapMark = { // mapMark Obj\n markedIds: [], // marked result row ids \n skipProps: ['kind', 'method', 'type', 'bic']\n};\nconst mapper = initMapDesc(mapMark);\n```\n\nand in the HTML:\n\n```\n\n```\n\nI have submitted a proposal to allow object and class methods to be used in a use directive.\n\n========================================\n\nCode:\n```text\n<script>\n function example(node, arg1, arg2) {\n // the node has been mounted in the DOM\n console.log(arg1, arg2) // Should display 'a b', but actually only displays 'b undefined'\n return {\n destroy() {\n // the node has been removed from the DOM\n }\n }\n }\n</script>\n\n<h1 use:example={'a', 'b'}>Hello World!</div>\n```\n\n```text\n<script>\n function example(node, arg) {\n // the node has been mounted in the DOM\n console.log(arg) // Returns a object with the arguments\n return {\n destroy() {\n // the node has been removed from the DOM\n }\n }\n }\n</script>\n\n<h1 use:example>Hello World!</div>\n\n<!-- Passing parameters -->\n<h1 use:example={{\n arg1: [50, 75, 100],\n arg2: true\n}}>Works like a charm!</h1>\n```\n\n```html\n<script>\n function example(node, [arg1, arg2]) {\n console.log(arg1, arg2)\n return {\n destroy() {\n // the node has been removed from the DOM\n }\n }\n }\n</script>\n\n<h1 use:example=\"{['a', 'b']}\">Hello World!</h1>\n```\n\n```text\n{}\n```\n\n```text\n'a', 'b'\n```\n\n```text\n'b'\n```\n\n```text\nexport function initMapDesc(mapMark) {\n\n // make the entry (obj) and the composed search regex reactive\n return (node, [obj, pRex]) => {\n // the node has been mounted in the DOM\n node.innerHTML = mapObj(node, obj, pRex, mapMark);\n\n return {\n update([obj, pRex]) {\n node.innerHTML = mapObj(node, obj, pRex, mapMark);\n },\n // destroy the node to clear the view (on session change)\n destroy() {\n node.innerHTML = '';\n }\n };\n };\n};\n```\n\n```text\nconst mapMark = { // mapMark Obj\n markedIds: [], // marked result row ids \n skipProps: ['kind', 'method', 'type', 'bic']\n};\nconst mapper = initMapDesc(mapMark);\n```\n\n```text\n<td id=\"{key}\" class=\"space-normal\" use:mapper={[$norm.map[key], $pseudoRex]}></td>\n```\n\n```text\n<td>\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.699Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":200,"estimatedTokens":1038}}534{"id":"stack-58740228","source":"stackoverflow","questionId":58740228,"title":"How can I change the class name of a svelte component?","tags":["javascript","svelte","svelte-component"],"text":"Title: How can I change the class name of a svelte component?\nTags: javascript, svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI've got multiple files named the same thing, but coming from totally different locations. Here's a simplified example:\n\n```\nAdminViews/Item.svelte\nClientViews/Item.svelte\nDefaultViews/Item.svelte\n```\n\nI try to import them all from within the same file, like so:\n\n```\nimport AdminItem from 'AdminViews/Item.svelte';\nimport ClientItem from 'ClientViews/Item.svelte';\nimport DefaultItem from 'DefaultViews/Item.svelte';\n```\n\nEven though I'm importing them as different names, they all reference whichever one is imported last. After investigating, it looks like this is because svelte sets the class name to whatever the filename is, regardless of path, e.g.:\n\n```\nclass Item extends _internal.SvelteComponentDev {\n```\n\nIt's identical for all of them, so when they're imported they each override the one above.\n\nSo my question is: how do I fix this collision without changing the filenames? Surely there's a way to change the class name of the component, I just can't find it in the docs.\n\nIf there isn't a way to fix it, then how does svelte deal with the fact that people often re-use common names, like `utils` or `index`?\n\n========================================\n\nCode:\n```text\nAdminViews/Item.svelte\nClientViews/Item.svelte\nDefaultViews/Item.svelte\n```\n\n```js\nimport AdminItem from 'AdminViews/Item.svelte';\nimport ClientItem from 'ClientViews/Item.svelte';\nimport DefaultItem from 'DefaultViews/Item.svelte';\n```\n\n```js\nclass Item extends _internal.SvelteComponentDev {\n```\n\n```text\nutils\n```\n\n```text\nindex\n```\n\n```js\nconst compiled = svelte.compile(code, {\n name: 'Potato'\n});\n```\n\n```text\nname\n```\n\n```text\nfilename => name\n```\n\n```text\nsrc/Thingamajig/index.svelte\n```\n\n```text\nindex\n```\n\n```text\nThingamajig\n```\n\n```text\nItem\n```\n\n```text\nItem\n```\n\n```text\nItem\n```\n\n========================================\n\nComments:\n- Thanks for the knowledge drop! It would be nice for the bundler plugins to be able to forward on a custom name. For anyone else that finds this - part of my issue was a stale cache also colliding with these names. So if you're seeing these sorts of issues I'd suggest wiping the cache clean - it might help.","metadata":{"transformedAt":"2026-08-18T18:33:40.699Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":102,"estimatedTokens":570}}535{"id":"stack-58460214","source":"stackoverflow","questionId":58460214,"title":"Svelte Serving Wrong Project","tags":["javascript","webpack-dev-server","svelte"],"text":"Title: Svelte Serving Wrong Project\nTags: javascript, webpack-dev-server, svelte\nSource: Stack Overflow\n\nQuestion:\nI created a new svelte project, opened the new directory in visual studio code and when I run `npm run dev` in the terminal and open my web browser, the project I see isn't the one I just created its one I previously worked on. \n\nSo my initial reaction was to delete the previous project, as it wasn't important, then ran the command again and to my surprise the project that no longer exist is still being served at the address. I've restarted my system and so on. \n\n**Does anyone know why this might be happening?**\n\n========================================\n\nCode:\n```text\nnpm run dev\n```\n\n========================================\n\nComments:\n- Have you tried list all processes and searching for another server running? stackoverflow.com/a/35189508/112233 add more information about the output of the commands in that link.\n- I tried doing as you said and it didn't seem to work but after a quick google search I found if you press ctrl+F5 it will clear the cache on refresh. Thanks so much!\n- @Maria Miller, this should be added to the answer. (cmd + shift + r for Mac).\n- No... I meant to say you should add what OP wrote in his comment: \"ctrl+F5 it will clear the cache on refresh\" - this is how you do a **hard refresh** on Windows. and for Mac: `cmd+shift+r`, this is what helped the OP (and me too multiple times...), and that's why I think it should be added to your answer...\n- Sorry for the confusion. Done.","metadata":{"transformedAt":"2026-08-18T18:33:40.699Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":26,"estimatedTokens":384}}536{"id":"stack-71520052","source":"stackoverflow","questionId":71520052,"title":"Excluding unused Svelte components from any given request's bundle","tags":["svelte","sveltekit"],"text":"Title: Excluding unused Svelte components from any given request's bundle\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nThe following question is specific to SvelteKit.\n\nI have a page that could potentially render a subset of various components based upon what the server determines from the request. But since the server is already going to determine what should/should not be displayed, I don't want to include any of the other components in the final bundle shipped to the client since the client will never need that code for that specific request.\n\nTo illustrate, in the example code below, if there is no error, I don't want the code for `ErrorToast` included in the bundle.\n\n```\n\n {#if error}\n \n {/if}\n\n {#if hasImages}\n \n {/if}\n\n {#if showUsage}\n \n {/if}\n\n```\n\nIs there any way of doing this with SvelteKit?\n\nI attempted dynamic imports (using `await import(\"$lib/path/to/Component.svelte\")`), but that resulted in *only* client side rendering with no SSR (definitely not ok). I also attempted to pass the component to the page from the corresponding endpoint via props, but that seemed to automatically import as a Server-side component.\n\n========================================\n\nCode:\n```html\n<main>\n {#if error}\n <ErrorToast {message} />\n {/if}\n\n {#if hasImages}\n <ImageGallery {images} />\n {/if}\n\n {#if showUsage}\n <UsageChart {data} />\n {/if}\n</main>\n```\n\n```text\nErrorToast\n```\n\n```text\nawait import(\"$lib/path/to/Component.svelte\")\n```\n\n```js\n<script context=\"module\">\n export async function load() {\n const { error, hasImages, showUsage } = get_props_somehow();\n\n if (error) {\n return {\n props: {\n component: (await import('./ErrorToast.svelte')).default,\n props: message\n }\n }\n }\n\n if (hasImages) {\n // ...\n }\n\n if (showUsage) {\n // ...\n }\n }\n</script>\n\n<script>\n export let component;\n export let props;\n</script>\n\n<svelte:component this={component} {...props}/>\n```\n\n```text\nerror\n```\n\n========================================\n\nComments:\n- Have you ever looked upon ``? This might help you get where you want. svelte.dev/tutorial/svelte-component\n- Yep! It's definitely one piece of the puzzle. It doesn't solve excluding it from the bundle, though.","metadata":{"transformedAt":"2026-08-18T18:33:40.699Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":99,"estimatedTokens":599}}537{"id":"stack-75539021","source":"stackoverflow","questionId":75539021,"title":"Playwright not waiting for elements to be visible","tags":["svelte","playwright"],"text":"Title: Playwright not waiting for elements to be visible\nTags: svelte, playwright\nSource: Stack Overflow\n\nQuestion:\nI'm trying to write a \"hello world\" test using Playwright to start testing my Svelte app. The app shows a loading screen for about two seconds, then shows the app itself, which shows some data in a table. I want to simply detect that there is a table on the screen.\n\nTo get past the loading screen, I'm using the waitFor() method, but it keeps timing out after about two seconds no matter what I put for the timeout value in the Playwright config. I even put it to 100000ms and it still times out after about two seconds (same amount of time as the loading screen is on the screen). The error that appears is that the 100000ms timeout has been exceeded, which obviously isn't true. I even tried the page.slow() option, but then it just says I've exceeded the 300000ms timeout.\n\nHere's the test I'm trying to get to work. Any help would be hugely appreciated.\n\n```\ntest('The table is present after the loading screen disappears', async ({page}) => {\n await page.goto('localhost:3000');\n const tbl = await page.locator('table');\n await tbl.waitFor();\n await expect(tbl.count()).toBeGreaterThan(0);\n});\n```\n\nHere's what the relevant part of my playwright.config.ts look like:\n\n```\nexport default defineConfig({\n testDir: './e2e',\n /* Maximum time one test can run for. */\n timeout: 100 * 1000,\n expect: {\n /**\n * Maximum time expect() should wait for the condition to be met.\n * For example in `await expect(locator).toHaveText();`\n */\n timeout: 500000000\n },\n```\n\nHere's the error:\nhttps://i.sstatic.net/grDf8.png\n\n========================================\n\nCode:\n```text\ntest('The table is present after the loading screen disappears', async ({page}) => {\n await page.goto('localhost:3000');\n const tbl = await page.locator('table');\n await tbl.waitFor();\n await expect(tbl.count()).toBeGreaterThan(0);\n});\n```\n\n```text\nexport default defineConfig({\n testDir: './e2e',\n /* Maximum time one test can run for. */\n timeout: 100 * 1000,\n expect: {\n /**\n * Maximum time expect() should wait for the condition to be met.\n * For example in `await expect(locator).toHaveText();`\n */\n timeout: 500000000\n },\n```\n\n```text\ntest('The table is present after the loading screen disappears', async ({page}) => {\n // wait for the 'load' event\n // which probably doesn't help in your case\n await page.goto('localhost:3000');\n const tbl = page.locator('table');\n // waits until `tbl` becomes visible\n // timeout in your case is `500000000`\n await expect(tbl).toBeVisible();\n});\n```\n\n```text\nnpx playwright test --debug\n```\n\n```text\nexpect\n```\n\n```text\nwaitFor\n```\n\n```text\nawait expect(locator).toBeVisible()\n```\n\n```text\ntable\n```\n\n========================================\n\nComments:\n- Try removing the `await` before `page.locator('table')` as that does not return a promise. That has the potential to cause issues.\n- @AJG `await`ing a value that’s not a Promise just silently wraps the value in a promise resolved to the value, thus will give the value just the same, and doesn’t affect any functionality, albeit redundant.\n- @David I feel like I ran into that quirkiness as well where it gives an error like that when it’s not the true culprit. I believe it actually may be due to an unhandled promise, basically the promise is still being resolved when the test ends, and maybe causes an issue with the context trying to close. Not sure about the context close piece, but if I’m right on the cause/issue, `count()` returns a promise, which isn’t being awaited nor is expect told to wait and unwrap it so it doesn’t wait, just checking if the promise is greater than 0. You need .resolves, like so: (Continued in next comment\n- `await expect(tbl.count()).resolves.toBeGreaterThan(0); });` See jestjs.io/docs/expect#resolves. Not 100% confident that’s causing what you’re seeing, so let me know and if so I’ll post an actual answer. That will definitely be needed for the test to work as you intended though, just not sure if it’s causing the error you’re seeing. (Though it would explain why it happens right after loading finishes, since the expect then immediately happens and fails, ending the test)\n- Thank you @DavidR, that did indeed cause the test to pass. I've also marked the answer below as correct, because I think that code provided is the way this should be done if possible, rather than manually resolving promises. Though I didn't know about .resolve, and I imagine it is going to be extremely useful, thanks for bringing it to my attention!\n- @David awesome! I admit, I was half asleep while writing, and for your use case where the goal what asserting/expecting it to be visible, that would be my recommended approach too. There are still times to use waitFor instead, but not when it’s part of the assertion you’re trying to make since the indicated assertions are available.\n- The provided code does solve the issue, thank you. Just a quick note: the recommendation to use --debug won't be helpful for people facing an issue like the one I was facing, because the test always passed in --debug mode. When the debugger came up, it would allow enough time for the loading screen to go away, and the table was always found.\n- Well. happy it's resolved. :)","metadata":{"transformedAt":"2026-08-18T18:33:40.700Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":108,"estimatedTokens":1332}}538{"id":"stack-57349973","source":"stackoverflow","questionId":57349973,"title":"Bundle only the main component with Svelte","tags":["webpack","rollup","svelte"],"text":"Title: Bundle only the main component with Svelte\nTags: webpack, rollup, svelte\nSource: Stack Overflow\n\nQuestion:\nI would like to bundle only the main component in a Svelte application and bootstrap the application myself in a script tag with the container of my choice.\n\nIn the Svelte template (rollup and bootstrap), the application is bootstrap in the main.js, which import the App.svelte. I would like bundle only the App.svelte and instanciate the App class myself. The objective is to be able to reuse the app in whatever plateform I want and be able to choose the target (ex: use a component in a CMS, SharePoint, etc.).\n\nSo do :\n\n```\nconst app = new App({\n target: document.body,\n props: {}\n});\n```\n\nmyself in a script tag in the index.html\n\nI am novice to webpack and I can't find how to bundle and then call the App class in the index.html\n\n========================================\n\nTop Answer:\nIf you check the compile options of Svelte, you will notice that there's an option to compile as a web component, **customElement**. This is what you are looking for, along with the **tag** options.\n\n========================================\n\nCode:\n```text\nconst app = new App({\n target: document.body,\n props: {}\n});\n```\n\n```text\nimport App from './App.svelte';\n\nexport default App;\n```\n\n```text\n<body>\n <div id=\"app-container\"></div>\n <script src='/bundle.js'></script>\n <script>\n var myapp= new app({\n \"target\": document.getElementById(\"app-container\"),\n \"props\": {\n \"name\": 'world'\n }\n })\n </script>\n</body>\n```\n\n```text\nentry: './src/App.svelte',\nresolve: {\n alias: {\n svelte: path.resolve('node_modules', 'svelte')\n },\n extensions: ['.mjs', '.js', '.svelte'],\n mainFields: ['svelte', 'browser', 'module', 'main']\n},\noutput: {\n path: __dirname + '/public',\n filename: 'bundle.js',\n chunkFilename: 'bundle.[id].js',\n library: 'app',\n libraryExport: 'default',\n libraryTarget: 'var'\n},\n...\n```\n\n========================================\n\nComments:\n- Do you mean \"customElement\" ?\n- I see but that doesnt explain how to configure webpack or rollup, can you show me a config example ? Should I set the app.svelte as entry point ? How can I get the exported class in a script tag in index.html ?\n- @2pha you are right, I updated with the exact option name. @PortePoisse If you are using rollup, you should have a plugin named `svelte` you can add the options to. The App.svelte component will be your custom element. You can find a more detailled guide here\n- Thanks for sharing your experiences. Btw if you are babel-ing in your webpack you may be able to `export { default } from './src/App.svelte'`","metadata":{"transformedAt":"2026-08-18T18:33:40.700Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":85,"estimatedTokens":683}}539{"id":"stack-75687080","source":"stackoverflow","questionId":75687080,"title":"Can I set once and global in an Svelte project?","tags":["typescript","svelte"],"text":"Title: Can I set once and global in an Svelte project?\nTags: typescript, svelte\nSource: Stack Overflow\n\nQuestion:\nI would like know if it is possible to set the used language once and global in an Svelte project.\n\nMy `file.svelte` would look like:\n\n```\n// Without lang=\"ts\"\n\n // TypeScript Code\n\n // HTML Code\n\n```\n\n========================================\n\nCode:\n```text\n// Without lang=\"ts\"\n<script>\n // TypeScript Code\n</script>\n\n<div>\n // HTML Code\n</div>\n```\n\n```text\nfile.svelte\n```\n\n```text\nsvelte-preprocess\n```\n\n========================================\n\nComments:\n- That's really disappointing. I was looking forward to learning Svelte, but having TypeScript as a second class citizen isn't appealing to me. Defaults matter. Especially on green-field projects.\n- What I ended up doing instead is configuring the eslint config with the rule `svelte/block-lang` to add lang attributes by default with the correct values. So in \"rules\" of `eslint.config.js` I added: `\"svelte/block-lang\": [\"error\", { script: \"ts\" }],`. You still have `lang=\"\"` in your code everywhere, but at least it's consistent and added automatically.","metadata":{"transformedAt":"2026-08-18T18:33:40.700Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":45,"estimatedTokens":285}}540{"id":"stack-72682047","source":"stackoverflow","questionId":72682047,"title":"Sveltekit: Importing ESM package produces errors that works with vite","tags":["svelte","es6-modules","commonjs","arcgis-js-api","sveltekit"],"text":"Title: Sveltekit: Importing ESM package produces errors that works with vite\nTags: svelte, es6-modules, commonjs, arcgis-js-api, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am trying to get Esri ArcGis's NPM package to work with SvelteKit.\n\nThe `@arcgis/core` is supposed to be ESM per the linked documentation. However, when I try to import it into SvelteKit as shown here I get an error about CommonJS. In a new SvelteKit app change `index.svelte` to\n\n```\n\n import Map from \"@arcgis/core/Map\";\n import MapView from \"@arcgis/core/views/MapView\";\n\n const map = new Map({\n basemap: \"arcgis-topographic\" // Basemap layer service\n });\n\n```\n\nWill produce the error\n\nNamed export 'setAssetPath' not found. The requested module '@esri/calcite-components/dist/components/index.js' is a CommonJS module, which may not support all module.exports as named exports. CommonJS modules can always be imported via the default export, for example using:\n\n```\nimport pkg from '@esri/calcite-components/dist/components/index.js';\nconst {setAssetPath: o} = pkg;\n```\n\nSandbox demonstrating error here.\n\nFirst off, I thought this issue had to do with Vite. So I imported `@arcgis/core` in vite as this tutorial shows. It works fine.\n\nIf I go and look at `@esri/calcite-components/package.json`, which `@arcgis/core` imports, I see that `@esri/calcite-components/package.json` does not have `\"type\": \"module\"` set. It appears that `@arcgis/core` is importing a CommonJS module.\n\nWhen I tried to debug further I realized `calcite-components` is a Stencil project which does include ESM though the error claims the package is CommonJS. Either way, the error itself had a recommended fix. When I go into the problem file and apply the fix:\n\n`node_modules/@arcgis/core/widgets/support/componentsUtils.js`\n\n```\n// import{setAssetPath as o}from\"@esri/calcite-components/dist/components/index.js\" Old import statement\nimport pkg from '@esri/calcite-components/dist/components/index.js';\nconst {setAssetPath: o} = pkg;\n```\n\nit fixes the issue. Then a new one is created, which I believe is different, in the file `node_modules/@arcgis/core/widgets/support/chartUtils.js`:\n\nThe first line of that file is:\n\n```\nimport{chartColorSets as t}from\"@esri/calcite-colors\";\n```\n\nWith the error\n\nThe requested module '@esri/calcite-colors' does not provide an export named 'chartColorSets'.\n\nThis is strange to me because `calcite-colors` is ESM and does have named exports. If I remove all the imports from `@arcgis/core` and just copy / paste `import{chartColorSets as t}from\"@esri/calcite-colors\"` into my `index.svelte` it works fine.\n\nWhy does a Vite project work just fine and why does SvelteKit report `calcite-colors` does not have a named export only when it is imported via `@arcgis/core` and not via my `index.svelte`?\n\nOthers have had this issue on the esri forums\n\n========================================\n\nCode:\n```text\n<script>\n import Map from \"@arcgis/core/Map\";\n import MapView from \"@arcgis/core/views/MapView\";\n\n const map = new Map({\n basemap: \"arcgis-topographic\" // Basemap layer service\n });\n</script>\n```\n\n```text\nimport pkg from '@esri/calcite-components/dist/components/index.js';\nconst {setAssetPath: o} = pkg;\n```\n\n```text\n// import{setAssetPath as o}from\"@esri/calcite-components/dist/components/index.js\" Old import statement\nimport pkg from '@esri/calcite-components/dist/components/index.js';\nconst {setAssetPath: o} = pkg;\n```\n\n```text\nimport{chartColorSets as t}from\"@esri/calcite-colors\";\n```\n\n```text\n@arcgis/core\n```\n\n```text\nindex.svelte\n```\n\n```text\n@arcgis/core\n```\n\n```text\n@esri/calcite-components/package.json\n```\n\n```text\n@arcgis/core\n```\n\n```text\n@esri/calcite-components/package.json\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\n@arcgis/core\n```\n\n```text\ncalcite-components\n```\n\n```text\nnode_modules/@arcgis/core/widgets/support/componentsUtils.js\n```\n\n```text\nnode_modules/@arcgis/core/widgets/support/chartUtils.js\n```\n\n```text\ncalcite-colors\n```\n\n```text\n@arcgis/core\n```\n\n```text\nimport{chartColorSets as t}from\"@esri/calcite-colors\"\n```\n\n```text\nindex.svelte\n```\n\n```text\ncalcite-colors\n```\n\n```text\n@arcgis/core\n```\n\n```text\nindex.svelte\n```\n\n```html\n<script lang=\"ts\">\n import { onMount } from 'svelte';\n\n onMount(async () => {\n const Map = (await import('@arcgis/core/Map')).default;\n const MapView = (await import('@arcgis/core/views/MapView')).default;\n\n const map = new Map({\n basemap: 'gray-vector'\n });\n\n const view = new MapView({\n container: 'viewDiv',\n map: map\n });\n\n view.when(() => {\n console.debug('Map loaded');\n });\n });\n</script>\n\n<div id=\"viewDiv\" />\n\n<style>\n @import '@arcgis/core/assets/esri/themes/light/main.css';\n \n #viewDiv {\n min-height: 500px;\n }\n</style>\n```\n\n========================================\n\nComments:\n- What version of nodejs are you running?\n- @jfriend00 16.14.2\n- So, that package is poorly or inaccurately documented. I tried following their directions exactly from scratch and it simply does not work as they say it should. You need to go find where you can get support and see what they say.\n- @jfriend00 thank you for taking the time to do that. I will contact them.\n- This is the only solution that I have seen which works so far. Thank you! Does importing via onMount remove the tree shaking? kit.svelte.dev/faq makes it appear that it does. Do you think `@arcgis` can be used as a normal import if the commonJS imports are removed from the `@arcgis` package, or is this the permanent solution?","metadata":{"transformedAt":"2026-08-18T18:33:40.700Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":206,"estimatedTokens":1396}}541{"id":"stack-68563086","source":"stackoverflow","questionId":68563086,"title":"Swiper with Sveltekit: no \"swiping\"","tags":["svelte","swiper.js","sveltekit"],"text":"Title: Swiper with Sveltekit: no \"swiping\"\nTags: svelte, swiper.js, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have tried to use swiper 6.8.0 with sveltekit 1.0.0-next.137.\nI have installed swiper with `npm i swiper`.\nThere is a detailed description how to use swiper at the end of this page:\nhttps://swiperjs.com/svelte\n\nThis is the code:\n\n```\n\n import SwiperCore, { Navigation, Pagination } from 'swiper';\n /* Import Swiper and SwiperSlide components from .svelte files */\n import Swiper from 'swiper/esm/svelte/swiper.svelte';\n import SwiperSlide from 'swiper/esm/svelte/swiper-slide.svelte';\n\n Slide 1\n Slide 2 \n\n```\n\nResult: there is no \"swipe-effect\", no error messages.\n\nI have put this example to the sandbox (with svelte, not with sveltekit):\nhttps://codesandbox.io/s/frosty-engelbart-tj8ub?file=/App.svelte\n\n========================================\n\nTop Answer:\nThis issue has been adressed on here: https://github.com/nolimits4web/swiper/issues/4574\nand then fixed here: https://github.com/nolimits4web/swiper/pull/4768\n\nYou can check out the demo that slava-viktorov made:\nhttps://codesandbox.io/s/sveltekit-swiper-forked-iin8p?file=/src/routes/index.svelte\n\nFor me, i tried to implement the \"*EffectCoverflow*\" and the only solution was to put this: https://github.com/nolimits4web/swiper/issues/4574#issuecomment-852646322 inside a component called **\"Swiper.svete\"**, then inside the **\"index.svelte\"**, add:\n\n```\n\nimport Swiper from '../lib/components/Swiper.svelte';\n\nimport SwiperCore, { Autoplay, EffectCoverflow, Navigation } from 'swiper/core';\nSwiperCore.use([Autoplay, EffectCoverflow, Navigation]);\n\n```\n\nI hope that this solution is any help for you.\nI'm sorry for the edits, i'm only trying to give a good answer.\n\n========================================\n\nCode:\n```text\n<script>\n import SwiperCore, { Navigation, Pagination } from 'swiper';\n /* Import Swiper and SwiperSlide components from .svelte files */\n import Swiper from 'swiper/esm/svelte/swiper.svelte';\n import SwiperSlide from 'swiper/esm/svelte/swiper-slide.svelte';\n</script>\n\n<!-- Pass core modules in \"modules\" prop -->\n<Swiper modules=\"{[ Navigation, Pagination ]}\">\n <SwiperSlide>Slide 1</SwiperSlide>\n <SwiperSlide>Slide 2</SwiperSlide> \n</Swiper>\n```\n\n```text\nnpm i swiper\n```\n\n```text\n<script>\n /* Import Swiper and SwiperSlide components from .svelte files */\n import Swiper from 'swiper/esm/svelte/swiper.svelte';\n import SwiperSlide from 'swiper/esm/svelte/swiper-slide.svelte';\n\n import { Autoplay, Navigation, Pagination } from 'swiper/core';\n\n import \"swiper/swiper.min.css\";\n import \"swiper/components/pagination/pagination.min.css\";\n import \"swiper/components/navigation/navigation.min.css\";\n \n const items = [\n {\n name: \"Leonardo\",\n age: 26,\n location: \"Italy\"\n },\n {\n name: \"Maria\",\n age: 27,\n location: \"Brazil\"\n },\n {\n name: \"Oliver\",\n age: 28,\n location: \"United States\"\n },\n {\n name: \"Margarida\",\n age: 29,\n location: \"Portugal\"\n }\n ];\n \n\n</script>\n\n<style>\n #swiper-container {\n width: 50vw;\n height: 300px;\n }\n</style>\n\n<div id=\"swiper-container\">\n <Swiper \n loop={true}\n spaceBetween={0}\n slidesPerView={1}\n autoplay={{\n delay: 1000,\n disableOnInteraction: true\n }}\n navigation={true}\n pagination={true}\n modules={[Autoplay, Navigation, Pagination]}\n >\n {#each items as item, i}\n <SwiperSlide>\n <div style=\"padding: 30px 8px; text-align: center; background: #ECE; border-radius: 5px;\">\n <strong>{item.name}</strong> ({item.age})\n from {item.location}\n </div>\n </SwiperSlide>\n {/each}\n </Swiper>\n\n</div>\n```\n\n```text\n<script context=\"module\" lang=\"ts\">\nimport Swiper from '../lib/components/Swiper.svelte';\n\nimport SwiperCore, { Autoplay, EffectCoverflow, Navigation } from 'swiper/core';\nSwiperCore.use([Autoplay, EffectCoverflow, Navigation]);\n</script>\n\n<Swiper />\n```\n\n========================================\n\nComments:\n- Awwwwwww, maaaaaaan!\n- Thank you. No, that does not solve the problem. \"svelte\" and \"sveltekit\" apparently require different code. That's why I pointed out where the code example came from: at the bottom of the swiperjs.com/svelte page there is this example for sveltekit, but it just doesn't work for me.\n- Did my last answer solve your issue? maybe i forgot something...\n- I'm sorry that I'm only answering now. On the one hand, I was still working on another issue. On the other hand, I haven't worked with codesandboy enough and couldn't get the example at codesandbox.io/s/sveltekit-swiper-forked-iin8p?file=/src/rou‌​tes/… to work with my data. Thanks for the github example, I will try it next. But shouldn't this work a little easier? \"i wanna learn 🧠 why this works : codesandbox.io/s/h91ee but this does not : codesandbox.io/s/5jix6\" interests me too.\n- yes, it was my bad on that, i found that method afther i responded here, i mean, i responded here with a example of code that worked on dev, and then when i was going to build it, i found it was an incomplete answer... there is also the thing that im not knowing if you are using that exact effect or not. This is my first answer on Stackoverflow, so, im sorry for everything.","metadata":{"transformedAt":"2026-08-18T18:33:40.700Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":164,"estimatedTokens":1350}}542{"id":"stack-48960847","source":"stackoverflow","questionId":48960847,"title":"Automatically passing html attributes to svelte components","tags":["svelte"],"text":"Title: Automatically passing html attributes to svelte components\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nIs it not possible to allow svelte components to automatically apply all regular html attributes to the top most element within the component?\n\nComponent.html\n\n```\n\n \n\n```\n\nApplication.html\n\n```\n\n \n Some text\n \n\n```\n\nAnd have the .extend added to the div inside the Component?\n\n========================================\n\nTop Answer:\n```\n\n```\n\nIt's possible but not recommended. Straight from the docs: https://svelte.dev/docs\n\n`$$props` References all props that are passed to a component, including ones\nthat are not declared with export. It is not generally recommended, as\nit is difficult for Svelte to optimise. But it can be useful in rare\ncases – for example, when you don't know at compile time what props\nmight be passed to a component.\n\n========================================\n\nCode:\n```text\n<div>\n <slot></slot>\n</div>\n```\n\n```text\n<div>\n <Component class=\"extend\">\n Some text\n </Component>\n</div>\n```\n\n```text\n<Widget {...$$props}/>\n<input {...$$restProps}>\n```\n\n```text\n$$props\n```\n\n========================================\n\nComments:\n- Thank you for your answer. That could be an okay solution. Would it work with server side rendering, or would the hook only get called on the client, and would find(\"element\") work on the server?\n- Just saw this github.com/sveltejs/svelte/pull/148 and hooks are not called on the server. So this would not work with serverside rendering. Unless there is some other way of hooking into the creation of the dom node this doesn't seem feasible.\n- This would still display an error as prop is not declared tho ?","metadata":{"transformedAt":"2026-08-18T18:33:40.700Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":74,"estimatedTokens":419}}543{"id":"stack-71367087","source":"stackoverflow","questionId":71367087,"title":"static adapter not working with nginx and refreshing pages","tags":["svelte","svelte-3","sveltekit"],"text":"Title: static adapter not working with nginx and refreshing pages\nTags: svelte, svelte-3, sveltekit\nSource: Stack Overflow\n\nQuestion:\nThis is my config:\n\n```\nimport adapter from '@sveltejs/adapter-static';\nimport preprocess from 'svelte-preprocess';\nimport path from 'path';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: preprocess(),\n\n kit: {\n // hydrate the element in src/app.html\n target: '#svelte',\n adapter: adapter({\n // default options are shown\n pages: 'build',\n assets: 'build',\n fallback: null\n }),\n vite: {\n resolve: {\n alias: {\n $components: path.resolve('./src/components'),\n $stores: path.resolve('./src/stores'),\n $api: path.resolve('./src/api')\n }\n }\n }\n }\n};\n\nexport default config;\n```\n\nhowever if I refresh any page in browser I get a 404....\n\nindex works, but nothing else if I refresh page.\n\n========================================\n\nTop Answer:\nThis worked for me: `try_files $uri $uri/index.html $uri.html /index.html;`\n\n========================================\n\nCode:\n```text\nimport adapter from '@sveltejs/adapter-static';\nimport preprocess from 'svelte-preprocess';\nimport path from 'path';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: preprocess(),\n\n kit: {\n // hydrate the <div id=\"svelte\"> element in src/app.html\n target: '#svelte',\n adapter: adapter({\n // default options are shown\n pages: 'build',\n assets: 'build',\n fallback: null\n }),\n vite: {\n resolve: {\n alias: {\n $components: path.resolve('./src/components'),\n $stores: path.resolve('./src/stores'),\n $api: path.resolve('./src/api')\n }\n }\n }\n }\n};\n\nexport default config;\n```\n\n```text\ntry_files $uri $uri/ /index.html;\n```\n\n```text\ntry_files $uri $uri/index.html $uri.html /index.html;\n```\n\n========================================\n\nComments:\n- Since you're mentioning nginx, I'm assuming you're encountering this issue in production? What were your build & deploy steps, and what does your nginx config look like for this app?\n- so it looks like a 404 during build will cause static routing to not work in production. Not sure if that's a bug.\n- Did you ever figure this out? I'm having the same issue on an Apache server (DreamHost).\n- Yes. I added an answer\n- You should mentioned what you listed *after* the word `try_files`. Here's what I ended up using that seemed to work: `try_files $uri $uri/index.html $uri.html /index.html;` The /index.html at the end needs to match the `fallback: 'index.html'` part of your adapter-static config. Otherwise going directly to a route that doesn't have a matching file at that path -- such as any route with a dynamic param like `[id]` -- will result in a 404.\n- updated answer.\n- not having luck with similar setup & static build; setting the nginx try_files last part of string to `/index.html` and Sveltekit fallback to `index.html` will redirect my dynamic routes yes to the Svelte src/routes/index.svelte but the client side router does not invoke so the page does not change (it should re-render with the correct dynamic route template).\n- I've given up on svelte and gone back to native ssr with mojolicious\n- this settings worked for me: location /my-site { default_type \"text/html\"; alias /path; try_files $uri $uri/index.html $uri.html /index.html; }`\n- Can you explain why this works?","metadata":{"transformedAt":"2026-08-18T18:33:40.700Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":110,"estimatedTokens":930}}544{"id":"stack-73311486","source":"stackoverflow","questionId":73311486,"title":"Use reactive Variables Between Components in Svelte","tags":["components","svelte"],"text":"Title: Use reactive Variables Between Components in Svelte\nTags: components, svelte\nSource: Stack Overflow\n\nQuestion:\nI have a question regarding using reactive variables from component3 in my example in component 2. I have two checkboxes in component2 and I am having a reactive array that I want to use in component 2 but it does not quite work the way I want it to work. The repl can be found here: https://svelte.dev/repl/b8109591f22541949309be8404336afa?version=3.49.0\n\nThis is the main app\n\n```\n\n import Component2 from './Component2.svelte';\n import Component3 from './Component3.svelte';\n\n```\n\nComponent 2:\n\n```\n\n import a2 from './Component3.svelte';\n\n{#if a2[0]}\n\n Hi\n\n{:else}\n\n Not Hi\n\n{/if}\n```\n\nComponent 3\n\n```\n\n let initial_categories = [\n {name: 'SPINS', checked: true}, \n {name: 'TRAIN', checked: true}\n ]\n let vec_names = [\n 'SPINS', 'TRAIN'\n ]\n \n export let a2 = [];\n $: {\n a2 = [];\n for(let i = 0; i \n\n{#each initial_categories as { name, checked }}\n \n \n {name}\n \n{/each}\n\n{a2}\n```\n\n========================================\n\nCode:\n```text\n<script>\n import Component2 from './Component2.svelte';\n import Component3 from './Component3.svelte';\n</script>\n\n\n<Component3/>\n<Component2/>\n```\n\n```text\n<script>\n import a2 from './Component3.svelte';\n</script>\n\n{#if a2[0]}\n<p>\n Hi\n</p>\n{:else}\n<p>\n Not Hi\n</p>\n{/if}\n```\n\n```text\n<script>\n let initial_categories = [\n {name: 'SPINS', checked: true}, \n {name: 'TRAIN', checked: true}\n ]\n let vec_names = [\n 'SPINS', 'TRAIN'\n ]\n \n export let a2 = [];\n $: {\n a2 = [];\n for(let i = 0; i < initial_categories.length; i++) {\n let stringify = JSON.stringify(initial_categories[i]);\n stringify = JSON.parse(stringify)[\"checked\"];\n a2 = a2.concat(stringify);\n }\n }\n</script>\n\n{#each initial_categories as { name, checked }}\n <label class=\"cats\">\n <input type=checkbox bind:group={vec_names} bind:checked={checked} name=\"Category\" value={name}>\n {name}\n </label>\n{/each}\n\n{a2}\n```\n\n```html\n<script>\n import a2 from './Component3.svelte';\n</script>\n```\n\n```html\n<script context=\"module\">\n import { writable } from 'svelte/store';\n export let a2 = writable([]);\n</script>\n<script>\n // ...\n $a2 = [];\n for(let i = 0; i < initial_categories.length; i++) {\n // ...\n $a2 = $a2.concat(stringify);\n }\n</script>\n```\n\n```html\n<script>\n import { a2 } from './Component3.svelte';\n</script>\n\n{#if $a2[0]}\n <p>Hi</p>\n{:else}\n <p>Not Hi</p>\n{/if}\n```\n\n```html\n<script>\n import Component2 from './Component2.svelte';\n import Component3 from './Component3.svelte';\n \n let state = [];\n</script>\n\n\n<Component3 bind:state />\n<Component2 {state} />\n```\n\n```text\na2\n```\n\n```text\nComponent3\n```\n\n```text\ncontext=\"module\"\n```\n\n```text\nbind:\n```\n\n```text\nexport let state\n```\n\n========================================\n\nComments:\n- I would not recommend doing this. It creates a mess with the dependencies, it would be cleaner to define the shared state at the top level and pass it down, either via props or a context.\n- I added to my answer to illustrate what I wrote in the comment\n- Thank you for providing the better way of doing it!","metadata":{"transformedAt":"2026-08-18T18:33:40.700Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":193,"estimatedTokens":807}}545{"id":"stack-64041479","source":"stackoverflow","questionId":64041479,"title":"How to focus back on input after clicking button in Svelte?","tags":["svelte"],"text":"Title: How to focus back on input after clicking button in Svelte?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\n**Use Case**\n\nI am building a chat application so whenever a user types in a message in the chat box and clicks on send, ideally it should focus back on the input. Currently, this requires the user to click on the input again to start typing.\n\nHow can this be achieved in Svelte? I tried to use the `bind:this` and `use:` directives.\n\nEdit: This is a Svelte Sapper project.\n\n========================================\n\nCode:\n```text\nbind:this\n```\n\n```text\nuse:\n```\n\n```html\n<script>\n let message = \"\"\n\n let inputRef\n\n const onSend = () => {\n inputRef.focus()\n }\n</script>\n\n<input bind:this={inputRef} value={message}>\n<button on:click={onSend}>Send Message</button>\n```\n\n```text\nbind:this={myComponentRef}\n```\n\n```text\nmyComponentRef.focus()\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.700Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":46,"estimatedTokens":216}}546{"id":"stack-73508081","source":"stackoverflow","questionId":73508081,"title":"Play a sound effect when a page loads","tags":["svelte"],"text":"Title: Play a sound effect when a page loads\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to play a sound effect when a page loads using Svelte. I tried onMount, but there is no sound.\n\nHere is what I have so far:\n\n```\n\n import { onMount } from 'svelte';\n\n let celebration: HTMLAudioElement;\n\n onMount(() => {\n celebration.play();\n\n setTimeout(() => {\n celebration.pause();\n celebration.currentTime = 0;\n }, 1000);\n });\n\n \n\n```\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n\n import { onMount } from 'svelte';\n\n\n let celebration: HTMLAudioElement;\n\n onMount(() => {\n celebration.play();\n\n setTimeout(() => {\n celebration.pause();\n celebration.currentTime = 0;\n }, 1000);\n });\n</script>\n\n<audio\n src='https://sveltejs.github.io/assets/music/strauss.mp3'\n preload=\"auto\"\n bind:this={celebration}\n controls\n>\n <track kind=\"captions\" />\n</audio>\n```\n\n========================================\n\nComments:\n- Have you tried increasing the time on your setTimeout? Maybe no sound is happening at the beginning of this clip of audio and you're turning it off too quick. Try 5000 and see if anything happens.\n- Have a look at the console, Chrome gives `DOMException: play() failed because the user didn't interact with the document first.`","metadata":{"transformedAt":"2026-08-18T18:33:40.700Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":64,"estimatedTokens":336}}547{"id":"stack-66725886","source":"stackoverflow","questionId":66725886,"title":"Angular change detection vs Svelte change detection","tags":["angular","svelte","svelte-3","angular-changedetection"],"text":"Title: Angular change detection vs Svelte change detection\nTags: angular, svelte, svelte-3, angular-changedetection\nSource: Stack Overflow\n\nQuestion:\nI use Angular for my day job and am learning Svelte on the side. I understand that neither Angular or Svelte use a virtual dom and diffing. I understand that both have other change detection mechanisms, and, from what I've researched, they look similar. Can someone explain to me how each method is unique and how Angular and Svelte's change detection mechanisms differ?\n\n========================================\n\nCode:\n```text\nZone.js\n```\n\n```text\nsetInterval\n```\n\n```text\n$$invalidate\n```\n\n```text\nfoo = 'bar'\n```\n\n```text\n$$invalidate(.., foo = \"bar\");\n```\n\n```text\narray.push(item)\n```\n\n========================================\n\nComments:\n- That helps. Thank you.","metadata":{"transformedAt":"2026-08-18T18:33:40.700Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":38,"estimatedTokens":205}}548{"id":"stack-56356230","source":"stackoverflow","questionId":56356230,"title":"Exporting Separate Custom Elements from Svelte Components","tags":["svelte","svelte-component"],"text":"Title: Exporting Separate Custom Elements from Svelte Components\nTags: svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI'm trying to find out if it's possible to export each Svelte component as a separate Custom Element (with Shadow DOM) in its own js file (with imports for any child elements - i.e. dependencies aren't included in the same file). Is it even possible?\n\nThanks\n\n========================================\n\nCode:\n```js\nimport svelte from 'rollup-plugin-svelte';\n\nexport default [\n {\n input: ['src/main-a.js', 'src/main-b.js'],\n output: {\n dir: 'public/module',\n format: 'es',\n sourcemap: true\n },\n plugins: [svelte()],\n experimentalCodeSplitting: true,\n experimentalDynamicImport: true\n },\n];\n```\n\n```text\nrollup\n```\n\n```text\nrollup-plugin-svelte\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.700Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":37,"estimatedTokens":214}}549{"id":"stack-63637662","source":"stackoverflow","questionId":63637662,"title":"Add .js/.css files to .svelte component","tags":["svelte","swiper.js"],"text":"Title: Add .js/.css files to .svelte component\nTags: svelte, swiper.js\nSource: Stack Overflow\n\nQuestion:\nI want to add swiper slider to svelte, my question is:\n\n- Its possible to add css in script tag, like this:\n\n```\n import from \"styles.css\" ... \n```\n\nBecause import to head is tricky (Import css in node_modules to svelte)\n\n- I add `swiper.js` file to svelte, and it almost works. It works on touch (mouse), but buttons don't (`.swiper-button-next` `.swiper-button-prev`). Do exist special import .js files rules ?\n\nCode example: https://codesandbox.io/s/musing-leavitt-ygstx?file=/App.svelte:224-243\n\n========================================\n\nCode:\n```html\n<script> import from \"styles.css\" ... </script>\n```\n\n```text\nswiper.js\n```\n\n```text\n.swiper-button-next\n```\n\n```text\n.swiper-button-prev\n```\n\n```html\n<script>\n import { onMount } from \"svelte\";\n import \"swiper/swiper-bundle.min.css\"; // <- just import your css\n ...\n</script>\n```\n\n```js\n// core version + navigation, pagination modules:\nimport Swiper, { Navigation, Pagination } from 'swiper';\n\n// configure Swiper to use modules\nSwiper.use([Navigation, Pagination]);\n\n// init Swiper:\nconst swiper = new Swiper(...);\n```\n\n```html\n<script>\n import { onMount } from \"svelte\";\n import \"swiper/swiper-bundle.min.css\";\n import Swiper, { Navigation } from \"swiper\";\n\n Swiper.use([Navigation]);\n\n onMount(() => {\n const swiper = new Swiper(\".swiper-container\", {\n navigation: {\n nextEl: \".swiper-button-next\",\n prevEl: \".swiper-button-prev\"\n }\n });\n });\n</script>\n```\n\n```text\n.js\n```\n\n========================================\n\nComments:\n- Thanks for the answer, i insert your example to project (routify template - routify.dev/guide/installation) and get the error: [!] Error: Unexpected character '@' (Note that you need plugins to import files that are not JavaScript). It disappear when i remove - import \"swiper/swiper-bundle.min.css\";\n- it wokrs with sapper, looks like need to add some loader to rollup\n- Yes you will need a plugin like [rollup-plugin-css-only ](npmjs.com/package/rollup-plugin-css-only) for example. So does it respond your question?\n- Yes, you helped me a lot. Thanks, and pls add to answer the plugin, mb its help somebody :)\n- @vladbelozertsev Could you also please don't forget to upvote my answer ? :)","metadata":{"transformedAt":"2026-08-18T18:33:40.700Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":88,"estimatedTokens":581}}550{"id":"stack-56636268","source":"stackoverflow","questionId":56636268,"title":"Error while mounting a component on a div instead of a body","tags":["svelte"],"text":"Title: Error while mounting a component on a div instead of a body\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI am trying to mount a component on a div element using document.querySelector('.widget') but it throws an error\n\nmain.js looks like\n\n```\nconst app = new App({\n target: document.querySelector('.widget'),\n});\n```\n\nindex.html looks like\n\n```\n\n \n \n \n```\n\nI get an error \nUncaught Error: 'target' is a required option\n\n========================================\n\nCode:\n```js\nconst app = new App({\n target: document.querySelector('.widget'),\n});\n```\n\n```html\n<body>\n <script src='bundle.js'></script>\n <div class=\"widget\" id=\"widget\"></div>\n </body>\n```\n\n```html\n<body>\n <div class=\"widget\" id=\"widget\"></div>\n <script src='bundle.js'></script>\n</body>\n```\n\n```text\nbundle.js\n```\n\n========================================\n\nComments:\n- In addition to @Tholle's answer, note that your selector (`.widget`) is referencing an element with a *class* of `\"widget\"`, rather than an *ID*.\n- Haha wow! Caught by ancient bug. Guess I'm not onReady yet ;)","metadata":{"transformedAt":"2026-08-18T18:33:40.700Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":59,"estimatedTokens":267}}551{"id":"stack-65802995","source":"stackoverflow","questionId":65802995,"title":"Code breaks with error: $$slots is an illegal variable name","tags":["svelte"],"text":"Title: Code breaks with error: $$slots is an illegal variable name\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI want to make an optional slot for my component, followed the instruction from the tutorial down to my local machine in VS Code, but it's not working and the view are not showing.\n\nCan't find any resources & fixes from the net, how can I fix this?\n\n`Stacktrace`\n\n```\n[0] rollup v2.26.4\n[0] bundles src/main.js → public\\build\\bundle.js...\n[0] [!] (plugin svelte) ValidationError: $$slots is an illegal variable name\n[0] src\\views\\Settings\\SettingsItem.svelte\n[0] 16: \n[0] 17:\n[0] 18: {#if $$slots.trailing}\n[0] ^\n[0] 19: \n[0] 20: {:else}\n[0] ValidationError: $$slots is an illegal variable name\n[0] at error (C:\\Users\\Fukka\\Documents\\Electron\\maze-player-svelte\\node_modules\\svelte\\src\\compiler\\utils\\error.ts:25:16)\n[0] at Component.error (C:\\Users\\Fukka\\Documents\\Electron\\maze-player-svelte\\node_modules\\svelte\\src\\compiler\\compile\\Component.ts:406:3)\n[0] at Component.warn_if_undefined (C:\\Users\\Fukka\\Documents\\Electron\\maze-player-svelte\\node_modules\\svelte\\src\\compiler\\compile\\Component.ts:1300:10)\n[0] at Object.enter (C:\\Users\\Fukka\\Documents\\Electron\\maze-player-svelte\\node_modules\\svelte\\src\\compiler\\compile\\nodes\\shared\\Expression.ts:114:17)\n[0] at visit (C:\\Users\\Fukka\\Documents\\Electron\\maze-player-svelte\\node_modules\\svelte\\node_modules\\estree-walker\\src\\estree-walker.js:51:10)\n[0] at walk (C:\\Users\\Fukka\\Documents\\Electron\\maze-player-svelte\\node_modules\\svelte\\node_modules\\estree-walker\\src\\estree-walker.js:2:9)\n[0] at new Expression (C:\\Users\\Fukka\\Documents\\Electron\\maze-player-svelte\\node_modules\\svelte\\src\\compiler\\compile\\nodes\\shared\\Expression.ts:63:3)\n[0] at new IfBlock$1 (C:\\Users\\Fukka\\Documents\\Electron\\maze-player-svelte\\node_modules\\svelte\\src\\compiler\\compile\\nodes\\IfBlock.ts:14:21)\n[0] at C:\\Users\\Fukka\\Documents\\Electron\\maze-player-svelte\\node_modules\\svelte\\src\\compiler\\compile\\nodes\\shared\\map_children.ts:53:16\n[0] at Array.map ()\n```\n\n`Settings.svelte`\n\n```\n\n```\n\n`SettingsItem.svelte`\n\n```\n\n import { link } from \"svelte-spa-router\";\n\n export let href;\n export let title = \"No title given\";\n export let subtitle;\n\n \n {title}\n\n {#if subtitle}\n {subtitle}\n\n {/if}\n \n\n \n {#if $$slots.trailing}\n \n {:else}\n \n {/if}\n\n```\n\n========================================\n\nTop Answer:\nFor those who can't update svelte to the specified version in @juliomalves's answer for some reason, placing the `` tag inside the slot works perfectly.\n\n`SettingsItem.svelte`\n\n```\n\n \n {title}\n\n {#if subtitle}\n {subtitle}\n\n {/if}\n \n\n \n \n \n\n```\n\n`Settings.svelte`\n\n```\n\n some neat text in the slot\n\n```\n\n========================================\n\nCode:\n```text\n[0] rollup v2.26.4\n[0] bundles src/main.js → public\\build\\bundle.js...\n[0] [!] (plugin svelte) ValidationError: $$slots is an illegal variable name\n[0] src\\views\\Settings\\SettingsItem.svelte\n[0] 16: </div>\n[0] 17:\n[0] 18: {#if $$slots.trailing}\n[0] ^\n[0] 19: <slot name=\"trailing\" />\n[0] 20: {:else}\n[0] ValidationError: $$slots is an illegal variable name\n[0] at error (C:\\Users\\Fukka\\Documents\\Electron\\maze-player-svelte\\node_modules\\svelte\\src\\compiler\\utils\\error.ts:25:16)\n[0] at Component.error (C:\\Users\\Fukka\\Documents\\Electron\\maze-player-svelte\\node_modules\\svelte\\src\\compiler\\compile\\Component.ts:406:3)\n[0] at Component.warn_if_undefined (C:\\Users\\Fukka\\Documents\\Electron\\maze-player-svelte\\node_modules\\svelte\\src\\compiler\\compile\\Component.ts:1300:10)\n[0] at Object.enter (C:\\Users\\Fukka\\Documents\\Electron\\maze-player-svelte\\node_modules\\svelte\\src\\compiler\\compile\\nodes\\shared\\Expression.ts:114:17)\n[0] at visit (C:\\Users\\Fukka\\Documents\\Electron\\maze-player-svelte\\node_modules\\svelte\\node_modules\\estree-walker\\src\\estree-walker.js:51:10)\n[0] at walk (C:\\Users\\Fukka\\Documents\\Electron\\maze-player-svelte\\node_modules\\svelte\\node_modules\\estree-walker\\src\\estree-walker.js:2:9)\n[0] at new Expression (C:\\Users\\Fukka\\Documents\\Electron\\maze-player-svelte\\node_modules\\svelte\\src\\compiler\\compile\\nodes\\shared\\Expression.ts:63:3)\n[0] at new IfBlock$1 (C:\\Users\\Fukka\\Documents\\Electron\\maze-player-svelte\\node_modules\\svelte\\src\\compiler\\compile\\nodes\\IfBlock.ts:14:21)\n[0] at C:\\Users\\Fukka\\Documents\\Electron\\maze-player-svelte\\node_modules\\svelte\\src\\compiler\\compile\\nodes\\shared\\map_children.ts:53:16\n[0] at Array.map (<anonymous>)\n```\n\n```html\n<SettingsItem\n href=\"/settings\"\n title=\"Music Path\"\n subtitle=\"Choose where we look for music\"\n/>\n```\n\n```html\n<script>\n import { link } from \"svelte-spa-router\";\n\n export let href;\n export let title = \"No title given\";\n export let subtitle;\n</script>\n\n<a use:link {href} class=\"settings-item\">\n <div class=\"detail\">\n <p class=\"title\">{title}</p>\n\n {#if subtitle}\n <p class=\"subtitle\">{subtitle}</p>\n {/if}\n </div>\n\n <!-- HERE -->\n {#if $$slots.trailing}\n <slot name=\"trailing\" />\n {:else}\n <i class=\"bx bx-chevron-right icon\" />\n {/if}\n</a>\n```\n\n```text\nStacktrace\n```\n\n```text\nSettings.svelte\n```\n\n```text\nSettingsItem.svelte\n```\n\n```text\n$$slots\n```\n\n```text\n3.25.0\n```\n\n```text\nsvelte\n```\n\n```text\n3.25.0\n```\n\n```html\n<div class=\"settings-item\" on:click>\n <div class=\"detail\">\n <p class=\"title\">{title}</p>\n\n {#if subtitle}\n <p class=\"subtitle\">{subtitle}</p>\n {/if}\n </div>\n\n <slot name=\"trailing\">\n <i class=\"bx bx-chevron-right icon\" />\n </slot>\n</div>\n```\n\n```html\n<SettingsItem\n title=\"Music Path\"\n subtitle=\"Choose where we look for music\"\n on:click={toggleModal}\n>\n <p slot=\"trailing\">some neat text in the slot</p>\n</SettingsItem>\n\n<SettingsItem\n title=\"Metadata\"\n subtitle=\"Automatically retrieve and update missing album art and metadata (requires internet)\"\n/>\n```\n\n```text\n<i>\n```\n\n```text\nSettingsItem.svelte\n```\n\n```text\nSettings.svelte\n```\n\n========================================\n\nComments:\n- You don't show an example of using the slot, the example usage of `SettingsItem` doesn't allow for passing in slot contents. So I wonder whether the compiler works that out and knows there's no chance of `$$slots` being usable?\n- @Fukka What `svelte` version are you using?\n- @ianmjones I thought `slot` here works similar to vue's `slot`... I didn't show it because I don't need it to be filled (yet) but later on the other items. And I think that's how slot should work. am I wrong?\n- @juliomalves version `3.24.1`","metadata":{"transformedAt":"2026-08-18T18:33:40.700Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":241,"estimatedTokens":1605}}552{"id":"stack-70425327","source":"stackoverflow","questionId":70425327,"title":"SvelteKit + Vercel Broken path","tags":["svelte","vercel","sveltekit"],"text":"Title: SvelteKit + Vercel Broken path\nTags: svelte, vercel, sveltekit\nSource: Stack Overflow\n\nQuestion:\nIm having a problem using readdirSync when using SvelteKit + vercel. The site deploys successfully but one of the serverside load functions fails on a path\n\nThe problem does not occur locally if i use `npm run dev` and it doesnt appear with a local production build via `npm run build && npm run preview`. The problem appears to be with the path that `readdirsync()` looks for. But im unable to figure out how to fix this\n\n[index].json.js\n\n```\nimport fs from 'fs';\nimport dayjs from 'dayjs';\n\nexport function get() {\n let posts = fs\n .readdirSync(`src/posts`) // /.+\\.md$/.test(fileName))\n .map((fileName) => {\n const { metadata, content } = process(`src/posts/${fileName}`);\n return {\n content,\n metadata,\n slug: fileName.slice(0, -3)\n };\n });\n // sort the posts by create date.\n posts.sort(\n (a, b) => dayjs(a.metadata.date, 'MMM D, YYYY') - dayjs(b.metadata.date, 'MMM D, YYYY')\n );\n let body = JSON.stringify(posts);\n\n return {\n body\n };\n}\n```\n\nThis is the logs i see in Vercel. Its obvious the path is broken possibly due to incorrect base path, but how do i fix it?\n\n```\n[HEAD] /\n11:50:50:04\n2021-12-20T16:50:50.092Z d7448652-906d-49d1-b9f0-938984ab2d18 ERROR Error: ENOENT: no such file or directory, scandir 'src/posts'\n at Object.readdirSync (fs.js:1047:3)\n at get (/var/task/index.js:56304:33)\n at render_endpoint (/var/task/index.js:56582:26)\n at processTicksAndRejections (internal/process/task_queues.js:95:5)\n at async resolve (/var/task/index.js:57661:56)\n at async Object.handle (/var/task/index.js:57999:24)\n at async respond (/var/task/index.js:57644:12)\n at async fetch (/var/task/index.js:57182:28)\n at async load2 (/var/task/index.js:56440:17)\n at async load_node (/var/task/index.js:57265:14)\n2021-12-20T16:50:50.093Z d7448652-906d-49d1-b9f0-938984ab2d18 ERROR SyntaxError: Unexpected token E in JSON at position 0\n at JSON.parse ()\n at Proxy. (/var/task/index.js:57247:31)\n at processTicksAndRejections (internal/process/task_queues.js:95:5)\n at async load2 (/var/task/index.js:56440:17)\n at async load_node (/var/task/index.js:57265:14)\n at async respond$1 (/var/task/index.js:57387:22)\n at async render_page (/var/task/index.js:57516:20)\n at async resolve (/var/task/index.js:57661:104)\n at async Object.handle (/var/task/index.js:57999:24)\n at async respond (/var/task/index.js:57644:12)\n```\n\n========================================\n\nCode:\n```text\nimport fs from 'fs';\nimport dayjs from 'dayjs';\n\nexport function get() {\n let posts = fs\n .readdirSync(`src/posts`) // <-- this path breaks when deployed with vercel\n .filter((fileName) => /.+\\.md$/.test(fileName))\n .map((fileName) => {\n const { metadata, content } = process(`src/posts/${fileName}`);\n return {\n content,\n metadata,\n slug: fileName.slice(0, -3)\n };\n });\n // sort the posts by create date.\n posts.sort(\n (a, b) => dayjs(a.metadata.date, 'MMM D, YYYY') - dayjs(b.metadata.date, 'MMM D, YYYY')\n );\n let body = JSON.stringify(posts);\n\n return {\n body\n };\n}\n```\n\n```text\n[HEAD] /\n11:50:50:04\n2021-12-20T16:50:50.092Z d7448652-906d-49d1-b9f0-938984ab2d18 ERROR Error: ENOENT: no such file or directory, scandir 'src/posts'\n at Object.readdirSync (fs.js:1047:3)\n at get (/var/task/index.js:56304:33)\n at render_endpoint (/var/task/index.js:56582:26)\n at processTicksAndRejections (internal/process/task_queues.js:95:5)\n at async resolve (/var/task/index.js:57661:56)\n at async Object.handle (/var/task/index.js:57999:24)\n at async respond (/var/task/index.js:57644:12)\n at async fetch (/var/task/index.js:57182:28)\n at async load2 (/var/task/index.js:56440:17)\n at async load_node (/var/task/index.js:57265:14)\n2021-12-20T16:50:50.093Z d7448652-906d-49d1-b9f0-938984ab2d18 ERROR SyntaxError: Unexpected token E in JSON at position 0\n at JSON.parse (<anonymous>)\n at Proxy.<anonymous> (/var/task/index.js:57247:31)\n at processTicksAndRejections (internal/process/task_queues.js:95:5)\n at async load2 (/var/task/index.js:56440:17)\n at async load_node (/var/task/index.js:57265:14)\n at async respond$1 (/var/task/index.js:57387:22)\n at async render_page (/var/task/index.js:57516:20)\n at async resolve (/var/task/index.js:57661:104)\n at async Object.handle (/var/task/index.js:57999:24)\n at async respond (/var/task/index.js:57644:12)\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run build && npm run preview\n```\n\n```text\nreaddirsync()\n```\n\n```text\nimport { slugFromPath } from '$lib/util';\n\n/** @type {import('@sveltejs/kit').RequestHandler} */\nexport async function get({ query }) {\n const modules = import.meta.glob('./*.{md,svx,svelte.md}');\n\n const postPromises = [];\n const limit = Number(query.get('limit') ?? Infinity);\n\n if (Number.isNaN(limit)) {\n return {\n status: 400\n };\n }\n\n for (let [path, resolver] of Object.entries(modules)) {\n const slug = slugFromPath(path);\n const promise = resolver().then((post) => ({\n slug,\n ...post.metadata\n }));\n\n postPromises.push(promise);\n }\n\n const posts = await Promise.all(postPromises);\n const publishedPosts = posts.filter((post) => post.published).slice(0, limit);\n\n publishedPosts.sort((a, b) => (new Date(a.date) > new Date(b.date) ? -1 : 1));\n\n return {\n body: publishedPosts.slice(0, limit)\n };\n```\n\n```text\nreaddirSync\n```\n\n```text\nimport.meta.glob\n```\n\n========================================\n\nComments:\n- Please tell me you found a solution for this :'(\n- yes i have a workaround/fix, i wasnt able to get it working with readdirSync, i ended up using import.meta.glob() which is a vite utility for reading from the filesystem AFAIK i will post my refactored code as the answer","metadata":{"transformedAt":"2026-08-18T18:33:40.700Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":186,"estimatedTokens":1489}}553{"id":"stack-69761867","source":"stackoverflow","questionId":69761867,"title":"Preventing Svelte component parameter reactivity","tags":["svelte","reactive-variable"],"text":"Title: Preventing Svelte component parameter reactivity\nTags: svelte, reactive-variable\nSource: Stack Overflow\n\nQuestion:\nI've written a modal component in Svelte that has multiple exported variables for controlling behavior. The values of these variables can vary from invocation to invocation, but once a modal is showing, the only value that can be expected to change is that of `isOpen`. This suggests that `isOpen` is the only variable requiring reactivity, but if my understanding is correct, the presence of other variables in the HTML will cause Svelte to unnecessarily generate reactive code for all those variables too, unnecessarily fattening the code base.\n\nMy question is, what strategies are available for preventing reactive code from being generated for component parameters when it is not needed?\n\nIn the following, `message` will not change while the modal is displayed, so it seems that only `isOpen` need be reactive. The Svelte compiler cannot know this, though, so I have to explicitly do something that inhibits this reactive behavior.\n\n```\n\n import { closeModal } from 'svelte-modals';\n\n export let isOpen: boolean;\n export let message: string;\n\n{#if isOpen}\n \n {message}\n\n OK\n \n{/if}\n```\n\nThe only technique I'm aware of is to move the variable out into a function, as follows:\n\n```\n\n import { closeModal } from 'svelte-modals';\n\n export let isOpen: boolean;\n export let message: string;\n \n const getMessage = () => message;\n\n{#if isOpen}\n \n {getMessage()}\n\n OK\n \n{/if}\n```\n\nIs there a more succinct or more conventional way to accomplish this? For a technology so well thought out as Svelte, I find myself believing that there has to be a less clunky way to do this. A person who comes along to maintain code after me might see this as unnecessarily verbose and eliminate the indirection, unwittingly fattening up the code base (should they do this wholesale). It seems like there ought to be something more explicit.\n\nOr perhaps there is a way to require that *all* reactive variables be explicitly designated, such as with a preceding `$:`?\n\n========================================\n\nCode:\n```html\n<script lang=\"ts\">\n import { closeModal } from 'svelte-modals';\n\n export let isOpen: boolean;\n export let message: string;\n</script>\n\n{#if isOpen}\n <div class=\"contents\">\n <p>{message}</p>\n <button on:click={closeModal}>OK</button>\n </div>\n{/if}\n```\n\n```html\n<script lang=\"ts\">\n import { closeModal } from 'svelte-modals';\n\n export let isOpen: boolean;\n export let message: string;\n \n const getMessage = () => message;\n</script>\n\n{#if isOpen}\n <div class=\"contents\">\n <p>{getMessage()}</p>\n <button on:click={closeModal}>OK</button>\n </div>\n{/if}\n```\n\n```text\nisOpen\n```\n\n```text\nisOpen\n```\n\n```text\nmessage\n```\n\n```text\nisOpen\n```\n\n```text\n$:\n```\n\n```html\n<script>\n export let message;\n export let isOpen =true;\n const originalMessage=message;\n</script>\n\n<div>\n Message: {originalMessage}\n</div>\n<div>\n isOpen: {isOpen}\n</div>\n```\n\n========================================\n\nComments:\n- Oh interesting! That is a bit cleaner than a function call. Thank you! Maybe I'd call it `nonreactiveMessage` to make the reason clear.\n- This is working perfectly. I'd rather declare variables only once, indicating whether they are reactive or not, but until I learn otherwise, I'll assume this is the best way to do things. Thanks for your help!\n- It's a slightly odd usecase because you are changing the standard way that Svelte works. An alternative is that you could use the functionality to pass throught the message instead of a prop. This way, your modal component wont have a 'message' variable at all. Example here: svelte.dev/repl/161aac81eb00450b9449e5bcc1db8c4f?version=3.4‌​4.0 Its still reactive, but then the responsibilty is on the parent component.\n- The message property would suit well, but my other properties have to do with duration of the message and cancellation behavior. The HTML checks whether a duration was provided to decide what HTML to show.","metadata":{"transformedAt":"2026-08-18T18:33:40.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":130,"estimatedTokens":1010}}554{"id":"stack-64631522","source":"stackoverflow","questionId":64631522,"title":"create components based on object in svelte","tags":["svelte","svelte-3","svelte-component"],"text":"Title: create components based on object in svelte\nTags: svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nim looking to generate components based on input array of objects lets say:\n\n```\nlet components = [\n { Hero: { componentData: {} },\n { AnotherComponent: { componentData: {} }\n]\n```\n\nwhere 'Hero' and 'AnotherComponent' are component names that are used in import.\nall possible components are imported - i know in advance all components that could be used, i just dont know which will be used and in what order.\n\nthen i would like to do something like below\n*pseudo-code* as i know Object.keys(components)[0] is a string not a component class\n\n```\n{#each components as component}\n \n{/each}\n```\n\nmaybe there is a way to get a list of all imported components in svelte so i could map string names to components classes?\n\n========================================\n\nCode:\n```text\nlet components = [\n { Hero: { componentData: {} },\n { AnotherComponent: { componentData: {} }\n]\n```\n\n```text\n{#each components as component}\n <svelte:component this={Object.keys(components)[0]} data={component.componentData} />\n{/each}\n```\n\n```js\n// the Hero variable will probably become something like `a` after minify\nimport Hero from './Hero.svelte'\n```\n\n```js\nimport Hero from './Hero.svelte'\nimport OtherComponent from './OtherComponent.svelte'\n\n// NOTE should survive minification 'cause object keys are strings\nconst components = {\n Hero,\n OtherComponent,\n}\n\n...\n```\n\n```js\nexport { default as Hero } from './Hero.svelte'\nexport { default as OtherComponent } from './OtherComponent.svelte'\n```\n\n```html\n<script>\n import * as components from './components.js'\n\n export let cmp = 'Hero'\n</script>\n\n<svelte:component this={comoponents[cmp]} />\n```\n\n```html\n<script>\n import Hero from './Hero.svelte'\n import OtherComponent from './OtherComponent.svelte'\n\n const components = [\n { component: Hero, componentData: {} },\n { component: OtherComponent, componentData: {} },\n ]\n</script>\n\n<svelte:component this={components[0].component} />\n```\n\n```text\ncomponents.js\n```\n\n```text\ncomponents.js\n```\n\n```text\nConsumer.svelte\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":102,"estimatedTokens":536}}555{"id":"stack-77770599","source":"stackoverflow","questionId":77770599,"title":"Keep page scroll position of a page in Svelte","tags":["javascript","svelte"],"text":"Title: Keep page scroll position of a page in Svelte\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm using Svelte, and trying to keep the scroll position on a single page such when a user navigates to another page and then navigates back (through back in the browser or the navbar) the page loads and keeps same scroll position.\n\nI've tried doing this using a store, and the `` element. According to the note here I should use `onMount` to scroll the page on mount. This is what I've tried:\n\n```\n// scrollPosition.ts\nimport { writable } from 'svelte/store'\n\nexport const y = writable(0)\n\n// component.svelte\n\nimport { y } from '$lib/stores'\nimport { onMount } from 'svelte'\n\nonMount(() => {\n scrollTo(0, $y)\n})\n\n...\n```\n\nI've verified the store is updated with scroll position, and when the component mounts it is being reset to 0. So no scroll actually happens on mount.\n\nAny suggestions how to solve this?\n\n========================================\n\nCode:\n```js\n// scrollPosition.ts\nimport { writable } from 'svelte/store'\n\nexport const y = writable(0)\n\n// component.svelte\n<script lang=\"ts\">\nimport { y } from '$lib/stores'\nimport { onMount } from 'svelte'\n\nonMount(() => {\n scrollTo(0, $y)\n})\n</script>\n\n<svelte:window bind:scrollY={$y} />\n...\n```\n\n```text\n<svelte:window>\n```\n\n```text\nonMount\n```\n\n```text\nonDestroy(() => ($y = window.scrollY))\nonMount(async () => {\n await tick()\n scrollTo(0, $y)\n})\n```\n\n```text\n<svelte:window>\n```\n\n```text\nonDestroy\n```\n\n```text\nonMount\n```\n\n========================================\n\nComments:\n- You don't use SvelteKit? You get this functionality for free if you do.\n- No, my backend is implemented using diff language\n- @PeppeL-G What is the solution on sveltekit ?\n- If you load your data with the `load()` function you don't need to do anything else to get this functionality. SvelteKit will add client-side JS that remember scroll positions and go back to them when you click on the back button and the data has finished loading and rendering on the previous page.","metadata":{"transformedAt":"2026-08-18T18:33:40.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":89,"estimatedTokens":508}}556{"id":"stack-61603840","source":"stackoverflow","questionId":61603840,"title":"Svelte {#await}..{:then} block duplicating html with new data","tags":["async-await","svelte","sapper","svelte-3"],"text":"Title: Svelte {#await}..{:then} block duplicating html with new data\nTags: async-await, svelte, sapper, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use Sveltes `{#await}..{:then}` block to show NASA's image of the day but I'm getting a strange intermittent outcome. On the first page load the image and data loads in just fine. When I change the date using the date-picker on the page, it's supposed to replace the current image and description with the image and description for the selected date that is retrieved asynchronously. However, what's happening is sometimes the html with the new data just get's appended to the bottom of the page so the image and description for the previously selected date is still there. \n\nCan anyone tell me how I can make sure the previous data is removed? Or could this be some kind of race condition?\n\n```\n\n import { fade } from 'svelte/transition';\n import Loader from '../components/Loader.svelte';\n import {getContext} from 'svelte';\n import { format, parseISO } from 'date-fns'\n\n let todaysDate = format(new Date(), 'y-MM-dd');\n let selectedDate = todaysDate;\n\n async function getPhotoOfTheDay() {\n let data = \"\";\n if (selectedDate !== todaysDate) {\n let response = await fetch(`https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=` + selectedDate);\n data = await response.json();\n } else {\n console.log(\"use in memory data\");\n data = getContext('dailyImage');\n }\n return data;\n }\n\n $: imageData = getPhotoOfTheDay(selectedDate);\n $: formattedDate = format(parseISO(selectedDate), 'MMMM d, y')\n\n All About Space: Photo of the day\n\n \n\n### Photo of the day on {formattedDate}\n\n Choose a day to see the photo of the day for that date:\n \n \n\n {#if imageData===\"\"}\n error.. no data for the selected date\n\n {:else}\n {#await imageData}\n \n {:then image}\n \n \n\n### {image.title}\n\n \n \n {image.explanation}\n \n\n \n {:catch error}\n\n {error.message}\n\n {/await}\n\n {/if}\n\n #content {\n background: rgba(0,0,0,0.8);\n backdrop-filter: blur(6px);\n border-radius: 5px;\n width: 75%;\n margin: 0 auto;\n padding: 1rem 2rem;\n\n &:after {\n clear: both;\n content: \"\";\n display: block;\n width: 100%;\n }\n }\n\n .instructions {\n border-bottom: 1px solid gray;\n padding-bottom: 2rem;\n }\n\n input {\n padding: 0.5rem 1rem;\n font-size: 1rem;\n cursor: pointer;\n border: 0;\n border-radius: 3px;\n }\n\n img {\n float: left;\n padding: 0 1rem 1rem 0;\n max-width: 50%;\n }\n\n```\n\n========================================\n\nCode:\n```text\n<script>\n import { fade } from 'svelte/transition';\n import Loader from '../components/Loader.svelte';\n import {getContext} from 'svelte';\n import { format, parseISO } from 'date-fns'\n\n let todaysDate = format(new Date(), 'y-MM-dd');\n let selectedDate = todaysDate;\n\n async function getPhotoOfTheDay() {\n let data = \"\";\n if (selectedDate !== todaysDate) {\n let response = await fetch(`https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=` + selectedDate);\n data = await response.json();\n } else {\n console.log(\"use in memory data\");\n data = getContext('dailyImage');\n }\n return data;\n }\n\n $: imageData = getPhotoOfTheDay(selectedDate);\n $: formattedDate = format(parseISO(selectedDate), 'MMMM d, y')\n</script>\n\n<svelte:head>\n <title>All About Space: Photo of the day</title>\n</svelte:head>\n\n<div id=\"content\">\n <h1>Photo of the day on {formattedDate}</h1>\n <p class=\"instructions\">Choose a day to see the photo of the day for that date:\n <input type=\"date\" bind:value=\"{selectedDate}\" max=\"{todaysDate}\" >\n </p>\n\n {#if imageData===\"\"}\n <p>error.. no data for the selected date</p>\n {:else}\n {#await imageData}\n <Loader show=\"true\"/>\n {:then image}\n <div class=\"image-result\" transition:fade=\"{{duration: 300}}\">\n <h2>{image.title}</h2>\n <p>\n <img src=\"{image.url}\" alt=\"{image.title}\" title=\"{image.title}\"/>\n {image.explanation}\n </p>\n </div>\n {:catch error}\n\n {error.message}\n\n {/await}\n\n {/if}\n</div>\n\n<style lang=\"stylus\">\n #content {\n background: rgba(0,0,0,0.8);\n backdrop-filter: blur(6px);\n border-radius: 5px;\n width: 75%;\n margin: 0 auto;\n padding: 1rem 2rem;\n\n &:after {\n clear: both;\n content: \"\";\n display: block;\n width: 100%;\n }\n }\n\n .instructions {\n border-bottom: 1px solid gray;\n padding-bottom: 2rem;\n }\n\n input {\n padding: 0.5rem 1rem;\n font-size: 1rem;\n cursor: pointer;\n border: 0;\n border-radius: 3px;\n }\n\n img {\n float: left;\n padding: 0 1rem 1rem 0;\n max-width: 50%;\n }\n</style>\n```\n\n```text\n{#await}..{:then}\n```\n\n========================================\n\nComments:\n- That would do it. Thanks for finding this!","metadata":{"transformedAt":"2026-08-18T18:33:40.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":214,"estimatedTokens":1244}}557{"id":"stack-71743867","source":"stackoverflow","questionId":71743867,"title":"Refresh current page in SvelteKit","tags":["svelte","sveltekit"],"text":"Title: Refresh current page in SvelteKit\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nIs there any way to refresh page in every 10 seconds using SvelteKit?\nI have to refresh page to get output from endpoint.\n\nLoading data in `src/routes/[id].svelte` from `src/routes/[id].ts`.\n\n========================================\n\nTop Answer:\nTo refresh an endpoint you can use invalidate in your page route.\n\n```\nimport { onDestroy } from \"svelte\";\nimport { invalidate } from \"$app/navigation\";\n\nexport your_end_point_prop;\n\n// resfresh your_end_point_prop\nconst apiInterval = setInterval(async () => {\n await invalidate(\"/your_endpoint\");\n}, 1000000); \n\n... code to handle your end_point_prop\n\nonDestroy(() => {\n clearInterval(apiInterval);\n});\n```\n\n========================================\n\nCode:\n```text\nsrc/routes/[id].svelte\n```\n\n```text\nsrc/routes/[id].ts\n```\n\n```text\nimport { onDestroy } from \"svelte\";\nimport { invalidate } from \"$app/navigation\";\n\nexport your_end_point_prop;\n\n// resfresh your_end_point_prop\nconst apiInterval = setInterval(async () => {\n await invalidate(\"/your_endpoint\");\n}, 1000000); \n\n... code to handle your end_point_prop\n\nonDestroy(() => {\n clearInterval(apiInterval);\n});\n```\n\n========================================\n\nComments:\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:40.701Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":66,"estimatedTokens":379}}558{"id":"stack-73201528","source":"stackoverflow","questionId":73201528,"title":"How to include css into bundled js instead of seperate file with esbuild?","tags":["svelte","esbuild"],"text":"Title: How to include css into bundled js instead of seperate file with esbuild?\nTags: svelte, esbuild\nSource: Stack Overflow\n\nQuestion:\nIt always generates two files - main.js and main.css, how can I force it to include css into main.js?\nI looked through documentation but there seem to be no mentions on how to do it.\nHere is my config:\n\n```\nimport process from 'process';\nimport esbuild from 'esbuild';\nimport builtins from 'builtin-modules';\nimport esbuildSvelte from 'esbuild-svelte';\nimport sveltePreprocess from 'svelte-preprocess';\n\nconst banner = `/*\n`;\n\nconst prod = process.argv[2] === 'production';\nconst dev = process.argv[2] === 'development';\n\nesbuild\n .build({\n banner: {\n js: banner,\n },\n bundle: true,\n entryPoints: ['./src/main.ts'],\n external: [...builtins],\n loader: { '.mp3': 'dataurl' },\n format: 'cjs',\n logLevel: 'info',\n minify: prod ? true : false,\n outfile: 'main.js',\n plugins: [\n esbuildSvelte({\n preprocess: sveltePreprocess(),\n }),\n ],\n sourcemap: 'inline',\n target: 'es2016',\n treeShaking: true,\n watch: !prod && !dev,\n })\n .catch(() => process.exit(1));\n```\n\n========================================\n\nCode:\n```js\nimport process from 'process';\nimport esbuild from 'esbuild';\nimport builtins from 'builtin-modules';\nimport esbuildSvelte from 'esbuild-svelte';\nimport sveltePreprocess from 'svelte-preprocess';\n\nconst banner = `/*\n`;\n\nconst prod = process.argv[2] === 'production';\nconst dev = process.argv[2] === 'development';\n\nesbuild\n .build({\n banner: {\n js: banner,\n },\n bundle: true,\n entryPoints: ['./src/main.ts'],\n external: [...builtins],\n loader: { '.mp3': 'dataurl' },\n format: 'cjs',\n logLevel: 'info',\n minify: prod ? true : false,\n outfile: 'main.js',\n plugins: [\n esbuildSvelte({\n preprocess: sveltePreprocess(),\n }),\n ],\n sourcemap: 'inline',\n target: 'es2016',\n treeShaking: true,\n watch: !prod && !dev,\n })\n .catch(() => process.exit(1));\n```\n\n```text\nesbuildSvelte({\n compilerOptions:{ css: true },\n preprocess: sveltePreprocess(),\n}),\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":96,"estimatedTokens":518}}559{"id":"stack-70582006","source":"stackoverflow","questionId":70582006,"title":"TypeError: Class extends value undefined is not a constructor or null (svelte redis)","tags":["javascript","node.js","redis","svelte"],"text":"Title: TypeError: Class extends value undefined is not a constructor or null (svelte redis)\nTags: javascript, node.js, redis, svelte\nSource: Stack Overflow\n\nQuestion:\nI just got started with svelte and was trying to make an app with redis as the db. I made a typescript file with all the db functions I would need and tried to import it into my svelte components, but when I did that I got the following error\n\n```\nClass extends value undefined is not a constructor or null\nTypeError: Class extends value undefined is not a constructor or null\n at node_modules/@node-redis/client/dist/lib/client/socket.js (http://localhost:3000/node_modules/.vite/chunk-L35TFNQI.js?v=60c87e0f:6515:46)\n at __require (http://localhost:3000/node_modules/.vite/chunk-VP3FZ6LR.js?v=60c87e0f:25:44)\n at node_modules/@node-redis/client/dist/lib/client/index.js (http://localhost:3000/node_modules/.vite/chunk-L35TFNQI.js?v=60c87e0f:9192:20)\n at __require (http://localhost:3000/node_modules/.vite/chunk-VP3FZ6LR.js?v=60c87e0f:25:44)\n at node_modules/@node-redis/client/dist/index.js (http://localhost:3000/node_modules/.vite/redis.js?v=60c87e0f:852:20)\n at __require (http://localhost:3000/node_modules/.vite/chunk-VP3FZ6LR.js?v=60c87e0f:25:44)\n at node_modules/redis/dist/index.js (http://localhost:3000/node_modules/.vite/redis.js?v=60c87e0f:2589:20)\n at __require (http://localhost:3000/node_modules/.vite/chunk-VP3FZ6LR.js?v=60c87e0f:25:44)\n at http://localhost:3000/node_modules/.vite/redis.js?v=60c87e0f:2615:21\n```\n\nThis is my redis file (even with only this much, I get the same error)\n\n```\nimport redis from 'redis'\n\nexport var str = \"sample string\"\n```\n\nThis is my svelte component's script\n\n```\n\n import { str } from \"../redis_test\";\n\n```\n\n========================================\n\nTop Answer:\nI've had a similar problem and my understanding from reading the above is that it caused because the browser client is trying to read the db which is on the server.\nI am also using sveltekit and I resolved by problem by making sure my code was in an endpoint, which only runs on the server and then invoked the endpoint to get my data.\n\n========================================\n\nCode:\n```text\nClass extends value undefined is not a constructor or null\nTypeError: Class extends value undefined is not a constructor or null\n at node_modules/@node-redis/client/dist/lib/client/socket.js (http://localhost:3000/node_modules/.vite/chunk-L35TFNQI.js?v=60c87e0f:6515:46)\n at __require (http://localhost:3000/node_modules/.vite/chunk-VP3FZ6LR.js?v=60c87e0f:25:44)\n at node_modules/@node-redis/client/dist/lib/client/index.js (http://localhost:3000/node_modules/.vite/chunk-L35TFNQI.js?v=60c87e0f:9192:20)\n at __require (http://localhost:3000/node_modules/.vite/chunk-VP3FZ6LR.js?v=60c87e0f:25:44)\n at node_modules/@node-redis/client/dist/index.js (http://localhost:3000/node_modules/.vite/redis.js?v=60c87e0f:852:20)\n at __require (http://localhost:3000/node_modules/.vite/chunk-VP3FZ6LR.js?v=60c87e0f:25:44)\n at node_modules/redis/dist/index.js (http://localhost:3000/node_modules/.vite/redis.js?v=60c87e0f:2589:20)\n at __require (http://localhost:3000/node_modules/.vite/chunk-VP3FZ6LR.js?v=60c87e0f:25:44)\n at http://localhost:3000/node_modules/.vite/redis.js?v=60c87e0f:2615:21\n```\n\n```text\nimport redis from 'redis'\n\nexport var str = \"sample string\"\n```\n\n```text\n<script lang=\"ts\">\n import { str } from \"../redis_test\";\n</script>\n```\n\n```text\nbrowserify\n```\n\n```ts\nimport { main } from \"code-scanner\";\nimport type { PageServerLoad } from './$types';\n\nexport const load: PageServerLoad = async ({ params }) => {\n return {\n post: await main()\n };\n}\n```\n\n```ts\n<script lang=\"ts\">\n import type { PageProps } from './$types';\n\n let { data }: PageProps = $props();\n console.log(data);\n</script>\n```\n\n```text\nTypeError: Class extends value undefined is not a constructor or null\n```\n\n```text\n+page.svelte\n```\n\n```text\n+page.server.ts\n```\n\n```text\n+page.server.ts\n```\n\n```text\n+page.svelte\n```\n\n```text\n$props()\n```\n\n```text\nimport * as redis from 'redis';\n\nconst client = redis.createClient();\n\nclient.connect();\n\nexport default client;\n```\n\n```text\nredis-test.ts\n```\n\n```text\nredis-test.ts\n```\n\n========================================\n\nComments:\n- ok, i tried to import redis directly into the svelte component and i am still getting the error\n- @Shoejep thanks for the info, I am looking into that now, but I wanted to ask you, is this the correct way to fetch data from a database, or do people do something else, like are we supposed to make a REST API for this on the backend or something?\n- Can I connect directly to a Redis server from JavaScript running in a browser? Normally, you would have a server side that connects to the database.\n- @Shoejep thanks a lot, so just to make sure I got everything right, what people normally do is, have a server side which connects to the database, and the front end makes requests (REST/GraphQL) to the server (backend) which handles those requests appropriately\n- Yeah, that sounds right to me\n- @Shoejep okay, thanks for explaining :)\n- Even though it may happen for the error message, I don't think this is OP's issue, base don the existing comments.","metadata":{"transformedAt":"2026-08-18T18:33:40.701Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":148,"estimatedTokens":1307}}560{"id":"stack-72969271","source":"stackoverflow","questionId":72969271,"title":"Svelte select specific object data from JSON","tags":["javascript","json","svelte","sveltekit"],"text":"Title: Svelte select specific object data from JSON\nTags: javascript, json, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI need help accessing specific objects in a JSON file based on a name value in Svelte.\n\nI am using JSON as a data source and am able to pull it into my page and loop through it with each.\n\nThe JSON looks like so:\n\n```\n[\n {\n \"id\": 1,\n \"title\": \"Project 1\",\n \"body\": \"Project 1 text\"\n },\n {\n \"id\": 2,\n \"title\": \"Project 2\",\n \"body\": \"Project 2 text\"\n }\n ]\n```\n\nI access the JSON like this:\n\n```\n\n export const load = async ({ fetch }) => {\n const res = await fetch(\"https://amarton.github.io/amcom-portfolio-svelte/static/port.json\");\n const projects = await res.json();\n return {\n props: {\n projects,\n }\n }\n }\n \n\n export let projects; \n\n```\n\nAnd then loop through and display it like this:\n\n```\n{#each projects as project}\n \n\n### {project.title}\n\n {project.body}\n\n {/each}\n```\n\nI'd like to be able to access objects based on my assigned ids. For example, how do I grab JUST the object with the id of 2 and display its title and body in my page?\n\nSorry if this is a very basic question and thanks for much for any help you can provide.\n\n========================================\n\nCode:\n```text\n[\n {\n \"id\": 1,\n \"title\": \"Project 1\",\n \"body\": \"Project 1 text\"\n },\n {\n \"id\": 2,\n \"title\": \"Project 2\",\n \"body\": \"Project 2 text\"\n }\n ]\n```\n\n```text\n<script context=\"module\">\n export const load = async ({ fetch }) => {\n const res = await fetch(\"https://amarton.github.io/amcom-portfolio-svelte/static/port.json\");\n const projects = await res.json();\n return {\n props: {\n projects,\n }\n }\n }\n \n</script>\n\n<script>\n export let projects; \n</script>\n```\n\n```text\n{#each projects as project}\n <h2>{project.title}</h2>\n <p>{project.body}</p>\n {/each}\n```\n\n```js\n$: project = projects.find(p => p.id == '2');\n```\n\n```html\n<script>\n export let projects = [];\n\n let id = '';\n $: project = projects.find(p => p.id == id);\n</script>\n\n<label>\n Project\n <select bind:value={id}>\n <option />\n {#each projects as p}\n <option value={p.id} label={p.title} />\n {/each}\n </select>\n</label>\n\n{#if project}\n <h2>{project.title}</h2>\n <p>{project.body}</p>\n{/if}\n```\n\n```text\n{#each}\n```\n\n```text\nproject\n```\n\n```text\nselect\n```\n\n```text\n$:\n```\n\n```text\nproject\n```\n\n```text\nprojects\n```\n\n```text\nid\n```\n\n========================================\n\nComments:\n- Thanks so much, this got me there and taught me a bit more along the way.","metadata":{"transformedAt":"2026-08-18T18:33:40.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":166,"estimatedTokens":658}}561{"id":"stack-73703303","source":"stackoverflow","questionId":73703303,"title":"Storybook Gitlab Pages: script importing from wrong URL resulting in CORS errors","tags":["gitlab","cors","gitlab-ci","svelte","storybook"],"text":"Title: Storybook Gitlab Pages: script importing from wrong URL resulting in CORS errors\nTags: gitlab, cors, gitlab-ci, svelte, storybook\nSource: Stack Overflow\n\nQuestion:\nI am trying to use Gitlab CI to build and host a storybook page when I push an update to any branch. Here is the current CI script:\n\n### CI Script\n\n```\nimage: node:16\n\nstages:\n - setup\n - build-and-test\n - deployment\n - pages\n\n# stage: setup\n\nsetup:\n stage: setup\n cache:\n key: ${CI_COMMIT_REF_SLUG}\n paths:\n - node_modules/\n artifacts:\n paths:\n - node_modules/\n script:\n - yarn\n\n# stage: build-and-test (here I run linter, unit tests, and everything I want to build or test)\n\nbuild:\n stage: build-and-test\n artifacts:\n paths:\n - dist/\n script:\n - yarn build\n\nstorybook:\n stage: build-and-test\n artifacts:\n expire_in: 2 weeks\n when: always\n paths:\n - storybook/\n script:\n - yarn build-storybook --output-dir storybook\n\n# stage: deployment (here I deploy my app to specific stages or other artefacts like storybook)\n\ndeploy-storybook:\n stage: deployment\n script:\n - echo \"Enjoy the day. 🥳 Every job needs a script, but this job was just created to configure an environment.\"\n environment:\n name: storybook/$CI_COMMIT_REF_SLUG\n url: https://.gitlab.io//$CI_COMMIT_REF_SLUG/storybook/\n on_stop: remove-storybook\n only:\n - branches\n\nremove-storybook:\n stage: deployment\n cache:\n key: 'my-storybook'\n paths:\n - public\n script:\n - rm -rf \"public/$CI_COMMIT_REF_SLUG/storybook\"\n when: manual\n variables:\n GIT_STRATEGY: none # needed to prevent \"Couldn't find remote ref\" error\n environment:\n name: storybook/$CI_COMMIT_REF_SLUG\n action: stop\n\n# stage: pages (the stage name is custom, but the job NEEDS to be named pages)\n\npages:\n stage: pages\n cache:\n key: 'my-storybook'\n paths:\n - public\n script:\n - if [ \"$CI_COMMIT_REF_NAME\" = \"main\" ]; then\n mkdir -p public;\n touch public/index.html;\n echo \"window.location.href = 'https://.gitlab.io//main/storybook'\" > public/index.html;\n fi;\n - rm -rf \"public/$CI_COMMIT_REF_SLUG\"\n - mkdir -p \"public/$CI_COMMIT_REF_SLUG\";\n - mv storybook \"public/$CI_COMMIT_REF_SLUG\"\n artifacts:\n paths:\n - public\n```\n\nThis compiles as intended but has errors in console when viewed:\n\n```\niframe.html:1 Access to script at 'https://gitlab.com/oauth/authorize?client_id=&redirect_uri=https://projects.gitlab.io/auth&response_type=code&state=AFyDa1QTpsd9qXqSzdoy4w==&scope=api' (redirected from 'https://.gitlab.io/assets/iframe.8696a5de.js') from origin 'https://.gitlab.io' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.\n```\n\n```\niframe.html:374 GET https://gitlab.com/oauth/authorize?client_id=&redirect_uri=https://projects.gitlab.io/auth&response_type=code&state=AFyDa1QTpsd9qXqSzdoy4w==&scope=api net::ERR_FAILED 302\n```\n\nThe relevant section of `https://.gitlab.io///storybook/assets/iframe.html`:\n\n```\n\n ...\n \n\n \n \n\n \n ...\n\n```\n\n`.storybook/main.cjs`\n\n```\nconst { resolve } = require(\"path\");\nconst { typescript: preprocessTS } = require(\"svelte-preprocess\");\nconst { loadConfigFromFile, mergeConfig } = require(\"vite\");\n\nmodule.exports = {\n \"stories\": [\n \"../src/**/*.stories.mdx\",\n \"../src/**/*.stories.@(js|jsx|ts|tsx|svelte)\"\n ],\n \"addons\": [\n \"@storybook/addon-links\",\n \"@storybook/addon-essentials\",\n \"@storybook/addon-interactions\",\n \"@storybook/addon-svelte-csf\"\n ],\n \"framework\": \"@storybook/svelte\",\n \"core\": {\n \"builder\": \"@storybook/builder-vite\"\n },\n \"svelteOptions\": {\n \"preprocess\": import(\"../svelte.config.js\").preprocess\n },\n svelteOptions: {\n preprocess: [\n preprocessTS(),\n ],\n },\n async viteFinal(config, { configType }) {\n const { config: userConfig } = await loadConfigFromFile(\n resolve(__dirname, \"../vite.config.ts\")\n );\n\n return mergeConfig(config, {\n ...userConfig,\n // manually specify plugins to avoid conflict\n plugins: []\n });\n }\n}\n```\n\n### Question\n\nWhat can I do to fix this script import error? I think the generated url in the script tag is wrong, and should instead be something similar to `https://.gitlab.io///storybook/assets/iframe.8696a5de.js` (instead of the current `https://.gitlab.io/assets/iframe.8696a5de.js`). Is there any way I can edit the CI to edit the root URL?\n\nIf that would not work, why not, and what would work instead?\n\n========================================\n\nCode:\n```text\nimage: node:16\n\nstages:\n - setup\n - build-and-test\n - deployment\n - pages\n\n# stage: setup\n\nsetup:\n stage: setup\n cache:\n key: ${CI_COMMIT_REF_SLUG}\n paths:\n - node_modules/\n artifacts:\n paths:\n - node_modules/\n script:\n - yarn\n\n# stage: build-and-test (here I run linter, unit tests, and everything I want to build or test)\n\nbuild:\n stage: build-and-test\n artifacts:\n paths:\n - dist/\n script:\n - yarn build\n\nstorybook:\n stage: build-and-test\n artifacts:\n expire_in: 2 weeks\n when: always\n paths:\n - storybook/\n script:\n - yarn build-storybook --output-dir storybook\n\n# stage: deployment (here I deploy my app to specific stages or other artefacts like storybook)\n\ndeploy-storybook:\n stage: deployment\n script:\n - echo \"Enjoy the day. 🥳 Every job needs a script, but this job was just created to configure an environment.\"\n environment:\n name: storybook/$CI_COMMIT_REF_SLUG\n url: https://<my_username>.gitlab.io/<my_project>/$CI_COMMIT_REF_SLUG/storybook/\n on_stop: remove-storybook\n only:\n - branches\n\nremove-storybook:\n stage: deployment\n cache:\n key: 'my-storybook'\n paths:\n - public\n script:\n - rm -rf \"public/$CI_COMMIT_REF_SLUG/storybook\"\n when: manual\n variables:\n GIT_STRATEGY: none # needed to prevent \"Couldn't find remote ref\" error\n environment:\n name: storybook/$CI_COMMIT_REF_SLUG\n action: stop\n\n# stage: pages (the stage name is custom, but the job NEEDS to be named pages)\n\npages:\n stage: pages\n cache:\n key: 'my-storybook'\n paths:\n - public\n script:\n - if [ \"$CI_COMMIT_REF_NAME\" = \"main\" ]; then\n mkdir -p public;\n touch public/index.html;\n echo \"<!DOCTYPE HTML><script>window.location.href = 'https://<my_username>.gitlab.io/<my_project>/main/storybook'</script>\" > public/index.html;\n fi;\n - rm -rf \"public/$CI_COMMIT_REF_SLUG\"\n - mkdir -p \"public/$CI_COMMIT_REF_SLUG\";\n - mv storybook \"public/$CI_COMMIT_REF_SLUG\"\n artifacts:\n paths:\n - public\n```\n\n```text\niframe.html:1 Access to script at 'https://gitlab.com/oauth/authorize?client_id=<my_client_id>&redirect_uri=https://projects.gitlab.io/auth&response_type=code&state=AFyDa1QTpsd9qXqSzdoy4w==&scope=api' (redirected from 'https://<my_username>.gitlab.io/assets/iframe.8696a5de.js') from origin 'https://<my_username>.gitlab.io' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.\n```\n\n```text\niframe.html:374 GET https://gitlab.com/oauth/authorize?client_id=<my_client_id>&redirect_uri=https://projects.gitlab.io/auth&response_type=code&state=AFyDa1QTpsd9qXqSzdoy4w==&scope=api net::ERR_FAILED 302\n```\n\n```html\n<head>\n ...\n <script defer src=\"/node_modules/@fortawesome/fontawesome-free/js/all.min.js\"></script>\n\n <!-- iframe.html:374 -->\n <script type=\"module\" crossorigin src=\"/assets/iframe.8696a5de.js\"></script>\n\n <link rel=\"stylesheet\" href=\"/assets/iframe.0f83afa4.css\">\n ...\n</head>\n```\n\n```js\nconst { resolve } = require(\"path\");\nconst { typescript: preprocessTS } = require(\"svelte-preprocess\");\nconst { loadConfigFromFile, mergeConfig } = require(\"vite\");\n\nmodule.exports = {\n \"stories\": [\n \"../src/**/*.stories.mdx\",\n \"../src/**/*.stories.@(js|jsx|ts|tsx|svelte)\"\n ],\n \"addons\": [\n \"@storybook/addon-links\",\n \"@storybook/addon-essentials\",\n \"@storybook/addon-interactions\",\n \"@storybook/addon-svelte-csf\"\n ],\n \"framework\": \"@storybook/svelte\",\n \"core\": {\n \"builder\": \"@storybook/builder-vite\"\n },\n \"svelteOptions\": {\n \"preprocess\": import(\"../svelte.config.js\").preprocess\n },\n svelteOptions: {\n preprocess: [\n preprocessTS(),\n ],\n },\n async viteFinal(config, { configType }) {\n const { config: userConfig } = await loadConfigFromFile(\n resolve(__dirname, \"../vite.config.ts\")\n );\n\n return mergeConfig(config, {\n ...userConfig,\n // manually specify plugins to avoid conflict\n plugins: []\n });\n }\n}\n```\n\n```text\nhttps://<my_username>.gitlab.io/<project_name>/<branch>/storybook/assets/iframe.html\n```\n\n```text\n.storybook/main.cjs\n```\n\n```text\nhttps://<my_username>.gitlab.io/<project_name>/<branch>/storybook/assets/iframe.8696a5de.js\n```\n\n```text\nhttps://<my_username>.gitlab.io/assets/iframe.8696a5de.js\n```\n\n```text\n- sed -i -E \"s/((src|href)=\\\")\\/?/\\1.\\//g\" public/$CI_COMMIT_REF_SLUG/storybook/index.html\n- sed -i -E \"s/((src|href)=\\\")\\/?/\\1.\\//g\" public/$CI_COMMIT_REF_SLUG/storybook/iframe.html\n```\n\n```text\nsrc\n```\n\n```text\nhref\n```\n\n```text\nindex.html\n```\n\n```text\niframe.html\n```\n\n```text\n<user>.gitlab.io/<repo>/\n```\n\n```text\n<user>.gitlab.io/\n```\n\n```text\npath/name.ext\n```\n\n```text\n/path/name.ext\n```\n\n```text\n./path/name.ext\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":392,"estimatedTokens":2262}}562{"id":"stack-73116356","source":"stackoverflow","questionId":73116356,"title":"How to do type annotation in markup section","tags":["typescript","svelte"],"text":"Title: How to do type annotation in markup section\nTags: typescript, svelte\nSource: Stack Overflow\n\nQuestion:\nNot sure if it's duplicate of svelte typescript typing in markup, but since that one is not answered, and my question is slightly different, I might try.\n\nSvelte has `await` block that can await for a Promise and make the result available for the block. Suppose I fetch an object with type `T` from somewhere, then use `T`'s field `foo` inside the block. Since there is no way to annotate that object with type `T`, `npm check` always complains that `Error: Property 'foo' does not exist on type 'unknown'. (ts)`, though the code works perfectly.\n\nIf I write something like `{#await my_fetch() then my_object: T}`, the error becomes `Error: Expected } (svelte)`. It doesn't matter if `T` is correctly imported or not, because this is syntax error.\n\nI can't find a way to annotate type outside the `` block at the top of the svelte file, but the linter complains about type missing in markup section anyways. Am I missing something?\n\nIn the worst case, I can just ignore these false alarms and move on, but if there's way to clear these up please let me know.\n\n========================================\n\nCode:\n```text\nawait\n```\n\n```text\nT\n```\n\n```text\nT\n```\n\n```text\nfoo\n```\n\n```text\nT\n```\n\n```text\nnpm check\n```\n\n```text\nError: Property 'foo' does not exist on type 'unknown'. (ts)\n```\n\n```text\n{#await my_fetch() then my_object: T}\n```\n\n```text\nError: Expected } (svelte)\n```\n\n```text\nT\n```\n\n```text\n<script>\n```\n\n```text\nmy_fetch()\n```\n\n```text\n<script>\n```\n\n```text\nawait\n```\n\n========================================\n\nComments:\n- Yes! Wrapping `my_fetch()` in a annotated function (`const wrap_fetch = async (): Promise => { ... }`) solved the problem. `my_fetch()` didn't work because itself is a template function from a library.\n- And thanks for confirming the known limitation.\n- I just found the issue relating to this and have linked it in my answer.","metadata":{"transformedAt":"2026-08-18T18:33:40.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":80,"estimatedTokens":493}}563{"id":"stack-72336698","source":"stackoverflow","questionId":72336698,"title":"How to Compile a Svelte file to JavaScript from the Command line?","tags":["javascript","svelte"],"text":"Title: How to Compile a Svelte file to JavaScript from the Command line?\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm new to Svelte. Quick question:\n\n**Is there a CLI for the Svelte compiler, and how do I access it?**\n\nI understand Svelte has a preconfigured setup that uses rollup and what not\nfor building an app. That's all good, but I only need the CLI for transforming\na `svelte` file to pure `js` file. Something like:\n\n`svelte compile input.svelte --out=out.js`\n\n**Update**\nIt seems like there is no CLI for the Svelte compiler.\nHowever, a brief outline of the compilation process is available here. In particular,the following code snippet, which can be\nused to build CLI.\n\n```\nresult: {\n js,\n css,\n ast,\n warnings,\n vars,\n stats\n} = svelte.compile(source: string, options?: {...})\n```\n\n========================================\n\nCode:\n```js\nresult: {\n js,\n css,\n ast,\n warnings,\n vars,\n stats\n} = svelte.compile(source: string, options?: {...})\n```\n\n```text\nsvelte\n```\n\n```text\njs\n```\n\n```text\nsvelte compile input.svelte --out=out.js\n```\n\n```js\n#!/usr/bin/env node\nimport { compile } from \"svelte/compiler\";\nimport fs from \"node:fs\";\n\nconst filename = process.argv[2];\nconst source = fs.readFileSync(filename, 'utf-8');\nconst result = compile(source, { filename });\nprocess.stdout.write(result.js.code);\n```\n\n========================================\n\nComments:\n- Would this consider compile options from somewhere or could we pass compile options somehow. Use-case is to create a custom element from an otherwise existing component within a Sveltekit project.\n- 'compile()' will get compile options as second argument, I just checked. So we could expose some options as CLI tool arguments and pass them to the compiler.\n- compile's first argument is the source code string, not filename svelte.dev/docs#compile-time-svelte-compile\n- Oops, it created a component that just displays the filename 😅. I've updated the answer so it loads and uses the source from the filename.","metadata":{"transformedAt":"2026-08-18T18:33:40.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":75,"estimatedTokens":505}}564{"id":"stack-70965219","source":"stackoverflow","questionId":70965219,"title":"How to make my SvelteKit API work in production (Github Pages)?","tags":["github-pages","svelte","sveltekit"],"text":"Title: How to make my SvelteKit API work in production (Github Pages)?\nTags: github-pages, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\n### Background\n\nI have my project deployed to Github Pages here: https://zeddrix.github.io/jw-guitar-tabs, so I have this in my **svelte.config.js** file:\n\n```\nkit: {\n ...\n paths: {\n base: '/jw-guitar-tabs'\n },\n appDir: 'internal',\n ...\n}\n```\n\nI have this in my **__layout.svelte**:\n\n```\n\n import { base } from '$app/paths';\n ...\n const fetchFromDBAndStore = async (category: SongCategoriesType) => {\n const res = await fetch(`${base}/api/categories/original-songs`);\n const data = await res.json();\n console.log(data);\n\n ...other code...\n };\n\n ...I have my code here that uses this data...\n\n```\n\n**Side note:** I put it in this file so that this runs on any page, but I have a code to make sure that this doesn't run if I already have the data. *This is not the issue.*\n\nThis calls on the file: **src/routes/api/categories/original-songs.ts**:\n\n```\nimport fetchSongsDB from '$utils/fetchSongsDB';\n\nexport const get = async () => fetchSongsDB('originals');\n```\n\nAnd this `fetchSongsDB` function fetches the songs from my database.\n\nEverything is working fine in **development mode** when I run `npm run dev` and even in **preview mode** when I run `npm run preview` *after build*, of course, in `localhost:3000/jw-guitar-tabs`.\n\nhttps://i.sstatic.net/Wxdls.png\n\n### Issue\n\nHowever, on the static github page at https://zeddrix.github.io/jw-guitar-tabs, I get this:\n\nhttps://i.sstatic.net/RpPlR.png\n\nhttps://i.sstatic.net/curuQ.png\n\nIt serves the 404 Github Page as the response. I guess it's because it can't find the **src/routes/api/categories/original-songs.ts** file. But of course Github will not find this file because the deployed folder to gh-pages is the build folder so I don't have this original ***file*** route anymore.\n\nhttps://i.sstatic.net/yRkO5.png\n\nHow would I solve this?\n\n========================================\n\nCode:\n```text\nkit: {\n ...\n paths: {\n base: '/jw-guitar-tabs'\n },\n appDir: 'internal',\n ...\n}\n```\n\n```text\n<script lang=\"ts\">\n import { base } from '$app/paths';\n ...\n const fetchFromDBAndStore = async (category: SongCategoriesType) => {\n const res = await fetch(`${base}/api/categories/original-songs`);\n const data = await res.json();\n console.log(data);\n\n ...other code...\n };\n\n ...I have my code here that uses this data...\n</script>\n\n<Layout><slot /></Layout>\n```\n\n```text\nimport fetchSongsDB from '$utils/fetchSongsDB';\n\nexport const get = async () => fetchSongsDB('originals');\n```\n\n```text\nfetchSongsDB\n```\n\n```text\nnpm run dev\n```\n\n```text\nnpm run preview\n```\n\n```text\nlocalhost:3000/jw-guitar-tabs\n```\n\n```text\nfetch(`${base}/api/categories/original-songs`);\n```\n\n```text\nfetch(`${base}/api/categories/original-songs.json`);\n```\n\n```json\nkit: {\n prerender: {\n entries: [\n \"*\",\n \"/api/categories/original-songs.json\",\n```\n\n```text\noriginal-songs.ts\n```\n\n```text\noriginal-songs.json.ts\n```\n\n```text\n/favorites\n```\n\n```text\n/favorites/\n```\n\n```text\ntrailingSlash: \"never\",\n```\n\n```text\nfavorites.html\n```\n\n```text\nfavorites/index.html\n```\n\n```text\n/favorites\n```\n\n========================================\n\nComments:\n- I am: `\"@sveltejs/adapter-static\": \"^1.0.0-next.26\"`. That's why I was able to deploy my project to github. Is the issue related with this?\n- Unsure, I asked because I was thinking it would cause issues if it were absent — you're right though, without it you wouldn't have made it onto Github Pages in the first place.\n- I'm pretty sure that GitHub Pages only can serves static file, so you can't run any server-side code (in this case, your API endpoint). If you need to run a Node.js app (so that you can execute server-side code), you need something like a VPS provided by DigitalOcean, Linode, or other provider, or you can use free alternative like Deta.sh to host your Node.js app as a serverless app.\n- You can try deploying the same site on Vercel or Cloudflare Pages (they are both free up to a certain point). Most probably the issue is the same as @Owl described: Github Pages cannot run server functions. Or you are trying to access the database that is not reachable from the deployed backend.\n- @Owl—this site is deployed to GitHub Pages and calls a SvelteKit endpoint. I don't know whether he can connect to MongoDB after hitting the endpoint, but I feel at least he should not be getting a 404.\n- @kenset it calls a `.json` \"endpoint\", which is a static file just like HTML (svelteland.github.io/svelte-kit-blog-demo/create-your-blog.‌​json), which is stored here\n- The static files you reference would correspond to @Zedd's Mongo query — but @Zedd should at least be able to hit the endpoint just as svelteland.github.io can hit the `[slug].json.js` endpoint.\n- Seems like the `[slug].json.js` is only used for dev server or when building. I just tested on one of my Svelte Kit app, using adapter static strips out all endpoint routes (most likely because the adapter is only used to generate static file). If you do a network inspection on svelteland, it doesn't seem to hit `[slug].json.js`, rather than accessing a static `.json` file. I tried to clone and build the `svelte-kit-blog-demo` app, and it seems to bundle `create-your-blog.json`, `decoration.json`, `deploy-to-github.json` on the root build directory rather than using \"endpoint\" to fetch it.\n- Thanks a lot for the answer! So this means that everytime I modified the data in my db, I'll need to always build and deploy, since it's prerendered, right?\n- What about directly getting the data from the db, will that be possible in a static website, to avoid the hustle of building & deploying again and again? And even if that were possible, I still need to wait for the standalone endpoints feature (kit.svelte.dev/docs/routing#standalone-endpoints) to get this done, coz there's no other way to get this done, am I right?\n- That the limitation of static hosting. A method would be to create a CSR/SPA and use a database providers that has an api that is accessible from the client (like Firebase's \"Cloud Firestore\" for example). but not sure if thats good fit for a sveltekit site.","metadata":{"transformedAt":"2026-08-18T18:33:40.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":184,"estimatedTokens":1566}}565{"id":"stack-65711858","source":"stackoverflow","questionId":65711858,"title":"Svelte - how to make data not reactive?","tags":["javascript","svelte"],"text":"Title: Svelte - how to make data not reactive?\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI have some HTML elements that have a property `color`.\n\n```\n{name}\n```\n\nThe value of `color` will change over time. And I will add more of these `label` elements in future, but I wish **only new elements inherit the new value** - effectively, I wish to disable reactivity for this variable.\n\nIs this possible in Svelte?\n\n========================================\n\nCode:\n```text\n<label name={name} style=\"color: {color}\"); \">{name}</label>\n```\n\n```text\ncolor\n```\n\n```text\ncolor\n```\n\n```text\nlabel\n```\n\n========================================\n\nComments:\n- How are you setting the `color` variable?\n- So you are saying that you will have multiple labels, each with a name acting as their unique key? You could save the current color to a dictionary indexed by name at the time of the label creation. Then access the required color with: `{name}`\n- Makes sense, pass via value.","metadata":{"transformedAt":"2026-08-18T18:33:40.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":40,"estimatedTokens":245}}566{"id":"stack-76698925","source":"stackoverflow","questionId":76698925,"title":"Svelte #each block update condition","tags":["javascript","svelte"],"text":"Title: Svelte #each block update condition\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nWhen having an #each block in svelte (like https://learn.svelte.dev/tutorial/keyed-each-blocks), the entry is only updated if the content changed. This works perfectly in the tutorials example, where a string is given as property to a nested component:\n\n```\n{#each things as thing (thing.id)}\n \n{/each}\n```\n\nBut if I give the whole object (`thing`) and adjust Thing accordingly, it always updates all list entries. Hence I wonder what the condition is Svelte decides on, whether to update the component or not. Is it the property, which is incase of the whole object a reference and therefore always changes? Or is the whole Nested component generated to be compared against the DOM? Is it bad practice to give an Object to a component?\n\nApp.svelte\n\n```\n\n import Thing from './Thing.svelte';\n\n let things = [\n { id: 1, name: 'apple' },\n { id: 2, name: 'banana' },\n { id: 3, name: 'carrot' },\n { id: 4, name: 'doughnut' },\n { id: 5, name: 'egg' }\n ];\n\n function handleClick() {\n things = things.slice(1);\n }\n\n Remove first thing\n\n{#each things as thing (thing.id)}\n \n{/each}\n```\n\nThing.svelte\n\n```\n\n import {\n beforeUpdate,\n afterUpdate\n } from 'svelte';\n \n const emojis = {\n apple: '🍎',\n banana: '🍌',\n carrot: '🥕',\n doughnut: '🍩',\n egg: '🥚'\n };\n\n export let name;\n const emoji = emojis[name.name];\n\n beforeUpdate(() => {\n console.log('before updating ' + name.id)\n });\n \n afterUpdate(() => {\n console.log('after updating ' + name.id)\n });\n\n{emoji} = {name.name}\n\n```\n\nThe update lifecycle functions are called everytime, even if the content didn't change.\n\nEdit:\nWith the REPL there is this JS output tab which I searched a little. There are many of these p() {...} like:\n\n```\np(ctx, [dirty]) {\n if (dirty & /*name*/ 1 && t2_value !== (t2_value = /*name*/ ctx[0].name + \"\")) set_data(t2, t2_value);\n },\n```\n\nwhich seem to do the job. The one above is the one from the `Thing` `create_fragment` return. To me, the comparison seems good, but still an update is done.\n\n========================================\n\nTop Answer:\nYou have a couple of questions in your post, so to best help, I'll break them down into separate parts. I hope this clears things up at least a little bit.\n\n### Part 1: Why does the component update when I pass in the whole object?\n\nIs it the property, which is incase of the whole object a reference and therefore always changes? Or is the whole Nested component generated to be compared against the DOM?\n\nIt sounds like you are on the right track. This is how Svelte's reactive behavior works. It will trigger an update when the props are determined as changed; however, it does not do a deep equality check. So in your example, you are passing in a whole object, so the reference to the object will be used to determine if the prop has changed.\n\nIn the `{#each}` block, you have set `{thing.id}` as the key. This means that Svelte will these rules (for the most part) to determine whether it should rerender the component:\n\n- The object is new (it was not on the list before).\n\n- The object with the same key (thing.id) has been removed from the list.\n\n- The key `thing.id` changes.\n\nSo here comes the tricky part. Even though you are only slicing out part of the array in `handleClick()` Svelte will still update the component since it sees that the reference has changed.\n\n***Note:** Creating a new array with new references is the behavior of `slice`.*\n\nTo get around this, you could pass the component a specific property of the object rather than the entire thing:\n\n```\n{#each things as thing (thing.id)}\n \n{/each}\n```\n\n### Part 2: Is giving an object to a component bad practice?\n\nIs it bad practice to give an Object to a component?\n\nThis is a bit subjective, but in my opinion, passing an object is not necessarily a bad practice, but you should be aware of the implications. A couple of high-level points off the top of my head might be:\n\n- If the object is large or changes often, this could lead to many unnecessary updates and performance problems.\n\n- If only specific properties of the object are used by the component, passing only those properties could improve performance and make the code more transparent.\n\nBut like I said, this is only my opinion.\n\n### Part 3: `p(ctx, [dirty])` and what is going on here\n\nThe update lifecycle functions are called every time, even if the content didn't change.\n\nAs I'm sure you know, this is a part of Svelte's compiled code. This checks if the `name` prop in the `ctx` object (current context of the component) has changed, and if so, it will update the text content of the corresponding DOM element. In your case, the `name` prop is an object, and every time you slice the array, that object's reference changes, so this function will always consider it as \"changed\".\n\n========================================\n\nCode:\n```text\n{#each things as thing (thing.id)}\n <Thing name={thing.name}/>\n{/each}\n```\n\n```text\n<script>\n import Thing from './Thing.svelte';\n\n let things = [\n { id: 1, name: 'apple' },\n { id: 2, name: 'banana' },\n { id: 3, name: 'carrot' },\n { id: 4, name: 'doughnut' },\n { id: 5, name: 'egg' }\n ];\n\n function handleClick() {\n things = things.slice(1);\n }\n</script>\n\n<button on:click={handleClick}>\n Remove first thing\n</button>\n\n{#each things as thing (thing.id)}\n <Thing name={thing} />\n{/each}\n```\n\n```text\n<script>\n import {\n beforeUpdate,\n afterUpdate\n } from 'svelte';\n \n const emojis = {\n apple: '🍎',\n banana: '🍌',\n carrot: '🥕',\n doughnut: '🍩',\n egg: '🥚'\n };\n\n export let name;\n const emoji = emojis[name.name];\n\n beforeUpdate(() => {\n console.log('before updating ' + name.id)\n });\n \n afterUpdate(() => {\n console.log('after updating ' + name.id)\n });\n</script>\n\n<p>{emoji} = {name.name}</p>\n```\n\n```text\np(ctx, [dirty]) {\n if (dirty & /*name*/ 1 && t2_value !== (t2_value = /*name*/ ctx[0].name + \"\")) set_data(t2, t2_value);\n },\n```\n\n```text\nthing\n```\n\n```text\nThing\n```\n\n```text\ncreate_fragment\n```\n\n```text\nthings[0].name = 'banana'\n```\n\n```text\nbeforeUpdate\n```\n\n```text\nafterUpdate\n```\n\n```text\n<svelte:options immutable />\n```\n\n```text\nThing\n```\n\n```js\n{#each things as thing (thing.id)}\n <Thing name={thing.name}/>\n{/each}\n```\n\n```text\n{#each}\n```\n\n```text\n{thing.id}\n```\n\n```text\nthing.id\n```\n\n```text\nhandleClick()\n```\n\n```text\nslice\n```\n\n```text\np(ctx, [dirty])\n```\n\n```text\nname\n```\n\n```text\nctx\n```\n\n```text\nname\n```\n\n========================================\n\nComments:\n- What do you even mean by \"updates all list entries\"? Also, show your code.\n- For objects (i.e. not primitives), Svelte will consider them changed even if the reference did *not* change unless the `immutable` option is set. Otherwise changes to properties of objects would get lost.\n- Thank you very much for the detailed explanation. Part 1 makes sense to me. Part 2 aswell, I was just sometimes a bit lazy and forwarded what I fetched, guess I will change it where appropriate. Part 3 still confuses me a bit, because I think there are multiple `p()` calls and this is probaly the last one. The previous likely compare the reference, but this one has `ctx[0].name`, where `ctx[0]` is the object, if I'm not wrong.\n- Thanks a lot for the reply and the REPL. This invalidation explains it. You mentioned that: ` this is not very expensive as just the used properties are checked and the UI is only touched if something actually changed.` Does that mean that the actual comparison `t2_value !== (t2_value = /*name*/ ctx[0].name + \"\"` evals true even if the object contains the same `name` content?\n- No, that will be `false` since this does a string comparison. If the `name` did effectively not change, nothing happens. If it did change, `t2`, the text node showing the name, will be updated using `set_data`. The check is performed even if the `thing` is the same, the UI is only updated if `thing.name` actually changed.\n- That makes sense. Hence a UI update is avoided even if an object is used, just at the very last comparison call (`p()`, maybe I got the wrong idea?). But If it evals to `false`, why do the lifecycle functions run? Aren't they supposed to run on a UI update (`schedules work to happen immediately before the DOM is updated`)?\n- The callbacks run whenever the update loop runs, regardless of whether anything happens within. For the before-case it would be impossible to know anyway.\n- This explains the inner working perfectly, I would love to take it as accepted answer. Basically, somewhere `dirty_components` is filled and on `flush` all `$$.before_update` and `p()` are called. Independent of whether `p()` evals true, `$$.after_update.forEach(add_render_callback);` is done, adding the `afterUpdate` to a list for later callback (the `foreEach` is a bit strange, are there multiple `afterUpdate` per fragment?). My conclusion is that objects are not bad, it just gets a little bit more `dirty` but no UI redrawings are triggered if not needed.\n- `before_update` and `after_update` are both lists, as the functions `beforeUpdate`/`afterUpdate` can be called arbitrarily often. All of that is just implementation detail though, so I do not think there is much merit in going as deeply into that. I added one sentence on the callbacks always being executed.\n- Perfect, thanks for your patience (with the many questions) and your time.","metadata":{"transformedAt":"2026-08-18T18:33:40.701Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":292,"estimatedTokens":2387}}567{"id":"stack-59683025","source":"stackoverflow","questionId":59683025,"title":"Access iframe content with Svelte","tags":["iframe","styling","head","svelte"],"text":"Title: Access iframe content with Svelte\nTags: iframe, styling, head, svelte\nSource: Stack Overflow\n\nQuestion:\nI am trying to access the head element within an iframe to change the styling. But everything that I can think of is not working.\n\nThis is my current code:\n\n```\n\n let frame;\n onMount(() => {\n frame.addEventListener('load', onLoad());\n })\n function onLoad() {\n let head = frame.contentDocument.head || frame.contentWindow.document.head;\n console.log(head);\n }\n\n```\n\nThis will successfully log the iframe but the `innerHTML` is blank.\n\n========================================\n\nCode:\n```js\n<script>\n let frame;\n onMount(() => {\n frame.addEventListener('load', onLoad());\n })\n function onLoad() {\n let head = frame.contentDocument.head || frame.contentWindow.document.head;\n console.log(head);\n }\n</script>\n\n<iframe bind:this={frame} src=\"src_here\" title=\"preview\" />\n```\n\n```text\ninnerHTML\n```\n\n```text\nfunction onLoad() {\n const head = frame.contentDocument.querySelector('head');\n console.log(head);\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":52,"estimatedTokens":259}}568{"id":"stack-63334701","source":"stackoverflow","questionId":63334701,"title":"Is there way to use Nest JS with Sapper (Svelte)?","tags":["javascript","node.js","nestjs","svelte","sapper"],"text":"Title: Is there way to use Nest JS with Sapper (Svelte)?\nTags: javascript, node.js, nestjs, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI've been looking for the past few days, but I haven't found a single sample code or article that discusses how to combine (*not separate them as API Service & Frontend Service*) Nest JS with Sapper (*Svelte*). Does anyone have any references in this regard?\n\n========================================\n\nComments:\n- How do you want to integrate them? You can build and deploy a NestJS API, and consume it from a separate Sapper app. Is that close to what you want?\n- Not. I want to combine the two things in one application or instance.\n- Marcio Koji Carvalho posted an Answer saying \"Nest.js Sapper working example Dirty but working example\"","metadata":{"transformedAt":"2026-08-18T18:33:40.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":13,"estimatedTokens":196}}569{"id":"stack-69173766","source":"stackoverflow","questionId":69173766,"title":"Svelte transition defined per transition and not per component","tags":["javascript","svelte","svelte-3","svelte-transition"],"text":"Title: Svelte transition defined per transition and not per component\nTags: javascript, svelte, svelte-3, svelte-transition\nSource: Stack Overflow\n\nQuestion:\nI'm developing a Svelte UI with full page navigation using svelte-spa-router.\nI'm facing the case where the UX designer defined the transition between page \"per transition\" and not per page has it's meant to be in Svelte (AFAIK).\n\nhttps://i.sstatic.net/4Wn5i.png\n\nE.g. in this UX page B1 out transition would :\n\n- disappeared instantly when going back to the home page A ;\n\n- slide left when going to C1 ;\n\n- dissolve when going to B2.\n\nThe UX actually makes sense because B1/B2, C1/C2 are similar but treats the same subject from a different point of view.\n\nSvelte transition are working great but are defined per component, with a `in` transition and an `out` transition.\n\nI tried leveraging the fact that transition property could be object and reactive.\n\n```\n\n import { fade } from \"svelte/transition\";\n let page = \"A\";\n let duration = 0;\n function goto(dest) {\n if(dest == \"A\" || page == \"A\") {\n duration = 0;\n } else {\n duration = 400;\n }\n page = dest;\n }\n\n{#if page == \"A\"}\n \n \n\n### Page A\n\n goto(\"B1\")}>Goto B1\n goto(\"B2\")}>Goto B2\n \n{:else if page == \"B1\"} \n \n \n\n### Page B1\n\n goto(\"A\")}>Goto Back\n goto(\"B2\")}>Goto B2\n \n{:else if page == \"B2\"}\n \n \n\n### Page B2\n\n goto(\"A\")}>Goto Back\n goto(\"B1\")}>Goto B1\n \n{/if}\n\n section {\n position: absolute;\n width: 500px;\n height: 500px;\n }\n section.A {\n background: pink;\n }\n section.B1 {\n background: blue;\n }\n section.B2 {\n background: yellow;\n }\n\n```\n\nBut I cannot figure out how to change the transition effect (maybe a custom transition function ?).\nMoreover, this solution seems very complicated, time consuming and could really turn to a ball of spaghetti in a more complex UX.\n\nIn addition, in svelte-spa-router I did not found a way to know where I'm coming from (i.e. the prevision `location`) to manage the transition accordingly.\n\nAny thoughts ?\n\n========================================\n\nCode:\n```text\n<script>\n import { fade } from \"svelte/transition\";\n let page = \"A\";\n let duration = 0;\n function goto(dest) {\n if(dest == \"A\" || page == \"A\") {\n duration = 0;\n } else {\n duration = 400;\n }\n page = dest;\n }\n</script>\n\n{#if page == \"A\"}\n <section class=\"A\" transition:fade={{duration: duration}}>\n <h1>Page A</h1>\n <nav on:click={e => goto(\"B1\")}>Goto B1</nav>\n <nav on:click={e => goto(\"B2\")}>Goto B2</nav>\n </section>\n{:else if page == \"B1\"} \n <section class=\"B1\" transition:fade={{duration: duration}}>\n <h1>Page B1</h1>\n <nav on:click={e => goto(\"A\")}>Goto Back</nav>\n <nav on:click={e => goto(\"B2\")}>Goto B2</nav>\n </section>\n{:else if page == \"B2\"}\n <section class=\"B2\" transition:fade={{duration: duration}}>\n <h1>Page B2</h1>\n <nav on:click={e => goto(\"A\")}>Goto Back</nav>\n <nav on:click={e => goto(\"B1\")}>Goto B1</nav>\n </section>\n{/if}\n\n<style>\n section {\n position: absolute;\n width: 500px;\n height: 500px;\n }\n section.A {\n background: pink;\n }\n section.B1 {\n background: blue;\n }\n section.B2 {\n background: yellow;\n }\n</style>\n```\n\n```text\nin\n```\n\n```text\nout\n```\n\n```text\nlocation\n```\n\n```js\n// pageTransion.js\nfunction slidePage(el) {\n return fly(el, { x: 200, duration: 300 });\n}\nfunction disolvePage(el) {\n return fade(el, { duration: 300 });\n}\nlet previous = \"\";\nlet current = \"\";\nexport function setNextPage(next) {\n previous = current;\n current = next;\n}\n\nexport function pageTransition(el) {\n const transitions = {\n \"b1-b2\": disolvePage,\n \"b1-c1\": slidePage,\n // etc\n };\n return transitions[previous + \"-\" + current];\n}\n\n\n// b1.svelte\n<div transition:pageTransition>\n```\n\n```text\nin:\n```\n\n```text\nfade\n```\n\n```text\nsetNextPage\n```\n\n========================================\n\nComments:\n- Thank you for your answer, I didn't know `transition` could be a function, that's great. I will check it out.","metadata":{"transformedAt":"2026-08-18T18:33:40.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":204,"estimatedTokens":1017}}570{"id":"stack-67937537","source":"stackoverflow","questionId":67937537,"title":"Sveltejs SSR - Property 'render' does not exist on type 'typeof SvelteComponentDev'","tags":["typescript","server-side-rendering","svelte","rollupjs"],"text":"Title: Sveltejs SSR - Property 'render' does not exist on type 'typeof SvelteComponentDev'\nTags: typescript, server-side-rendering, svelte, rollupjs\nSource: Stack Overflow\n\nQuestion:\nIm trying to server side rendering a svelte component with typescript and rollup.\n\n```\n// renderer.ts\nimport type { SvelteComponentDev } from 'svelte/internal';\nimport App from '../../../routes/index.svelte';\n\nexport default (): SvelteComponentDev => {\n const { html } = App.render();\n return html;\n};\n```\n\nIt returns the following errors\n\n```\nPlugin typescript: @rollup/plugin-typescript TS2339: Property 'render' does not exist on type 'typeof SvelteComponentDev'.\n```\n\nFrom my research, I came up with the following workaround but I'm not a big fan of it.\nDo you guys have a better way to ssr svelte component in typescript?\nThks\n\n```\n// renderer.ts\nimport type { SvelteComponentDev } from 'svelte/internal';\n\nlet App;\nimport('../../../routes/index.svelte').then(module => {\n App = module.default;\n});\n\nexport default (): SvelteComponentDev => {\n const { html } = App.render();\n return html;\n};\n```\n\n========================================\n\nCode:\n```text\n// renderer.ts\nimport type { SvelteComponentDev } from 'svelte/internal';\nimport App from '../../../routes/index.svelte';\n\nexport default (): SvelteComponentDev => {\n const { html } = App.render();\n return html;\n};\n```\n\n```text\nPlugin typescript: @rollup/plugin-typescript TS2339: Property 'render' does not exist on type 'typeof SvelteComponentDev'.\n```\n\n```text\n// renderer.ts\nimport type { SvelteComponentDev } from 'svelte/internal';\n\nlet App;\nimport('../../../routes/index.svelte').then(module => {\n App = module.default;\n});\n\nexport default (): SvelteComponentDev => {\n const { html } = App.render();\n return html;\n};\n```\n\n```js\n// renderer.ts\nimport type { SvelteComponentDev } from 'svelte/internal';\nimport App from '../../../routes/index.svelte';\n\nexport default (): SvelteComponentDev => {\n const { html } = (App as any).render();\n return html;\n};\n```\n\n```js\n// renderer.ts\nimport type { SvelteComponentDev } from 'svelte/internal';\nimport App from '../../../routes/index.svelte';\n\nexport default (): string => {\n const { html } = (App as any).render();\n return html;\n};\n```\n\n```text\nany\n```\n\n```text\nhtml\n```\n\n```text\nstring\n```\n\n========================================\n\nComments:\n- Indeed type casting to any works! Thank you","metadata":{"transformedAt":"2026-08-18T18:33:40.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":114,"estimatedTokens":602}}571{"id":"stack-60647542","source":"stackoverflow","questionId":60647542,"title":"Svelte application not working on android version 6.0.1 or Later","tags":["cordova","webpack","babeljs","html-framework-7","svelte"],"text":"Title: Svelte application not working on android version 6.0.1 or Later\nTags: cordova, webpack, babeljs, html-framework-7, svelte\nSource: Stack Overflow\n\nQuestion:\nI have created Cordova application demo in Svelte but when I run the application on android 6.0.1 or later application is stuck at splace screen.\n\nYou can find inspect screen, screenshot from below link. I have tried many babel hacks to convert ... which is js many spread operator to convert but no solution will work.\n\nThere is many js issues arise, from there two most important issue is below.\n\nUncaught Syntax error: Unexpected token ...\n\nUncaught Syntax error: Undefined token *\n\nhttps://forum.framework7.io/uploads/default/optimized/2X/5/511119ee16112390bb2bc6ecc4026b3028203e72_2_1380x786.png\n\nI am using Framwork7-CLI to create a Cordova android application, Framework7 version is 5.5.0 and latest Framwork7 CLI version.\n\nCurrently, I have selected Cordova and PWA application with Tabbed view F7 template.\n\nMy pacakage.json, babel.config.js and webpack.config.js file are below.\n\n**pacakage.json**\n\n```\n{\n \"name\": \"test-app\",\n \"private\": true,\n \"version\": \"1.0.0\",\n \"description\": \"Test App\",\n \"repository\": \"\",\n \"license\": \"UNLICENSED\",\n \"framework7\": {\n \"cwd\": \"/Users/hirenraiyani/demo_apps\",\n \"type\": [\n \"pwa\",\n \"cordova\"\n ],\n \"name\": \"Test App\",\n \"framework\": \"svelte\",\n \"template\": \"tabs\",\n \"bundler\": \"webpack\",\n \"cssPreProcessor\": \"less\",\n \"theming\": {\n \"customColor\": false,\n \"color\": \"#007aff\",\n \"darkTheme\": false,\n \"iconFonts\": true,\n \"fillBars\": false\n },\n \"customBuild\": false,\n \"webpack\": {\n \"developmentSourceMap\": true,\n \"productionSourceMap\": true,\n \"hashAssets\": false,\n \"preserveAssetsPaths\": false,\n \"inlineAssets\": true\n },\n \"pkg\": \"io.framework7.myapp\",\n \"cordova\": {\n \"folder\": \"cordova\",\n \"platforms\": [\n \"android\"\n ],\n \"plugins\": [\n \"cordova-plugin-statusbar\",\n \"cordova-plugin-keyboard\",\n \"cordova-plugin-splashscreen\",\n \"cordova-plugin-wkwebview-engine\",\n \"cordova-plugin-device\",\n \"cordova-plugin-inappbrowser\",\n \"cordova-plugin-file\",\n \"cordova-plugin-media\"\n ]\n }\n },\n \"scripts\": {\n \"start\": \"npm run dev\",\n \"dev\": \"cross-env NODE_ENV=development webpack-dev-server --config ./build/webpack.config.js\",\n \"build-dev\": \"cross-env NODE_ENV=development node ./build/build.js\",\n \"build-prod\": \"cross-env NODE_ENV=production node ./build/build.js\",\n \"build-dev-cordova\": \"cross-env TARGET=cordova cross-env NODE_ENV=development node ./build/build.js && cd cordova && cordova build\",\n \"build-prod-cordova\": \"cross-env TARGET=cordova cross-env NODE_ENV=production node ./build/build.js && cd cordova && cordova build\",\n \"android-prod\": \"cross-env TARGET=cordova cross-env NODE_ENV=production node ./build/build.js && cd cordova && cordova run android\",\n \"postinstall\": \"cpy ./node_modules/framework7-icons/fonts/*.* ./src/fonts/\"\n },\n \"browserslist\": [\n \"Android >= 5\",\n \"IOS >= 11\",\n \"Safari >= 11\",\n \"Chrome >= 49\",\n \"Firefox >= 31\",\n \"Samsung >= 5\"\n ],\n \"dependencies\": {\n \"dom7\": \"^2.1.3\",\n \"framework7\": \"^5.5.0\",\n \"framework7-icons\": \"^3.0.0\",\n \"framework7-svelte\": \"^5.5.0\",\n \"svelte\": \"^3.19.2\",\n \"template7\": \"^1.4.2\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.8.7\",\n \"@babel/plugin-syntax-dynamic-import\": \"^7.8.3\",\n \"@babel/plugin-transform-runtime\": \"^7.8.3\",\n \"@babel/preset-env\": \"^7.8.7\",\n \"@babel/runtime\": \"^7.8.7\",\n \"babel-loader\": \"^8.0.6\",\n \"chalk\": \"^3.0.0\",\n \"copy-webpack-plugin\": \"^5.1.1\",\n \"cpy-cli\": \"^3.1.0\",\n \"cross-env\": \"^7.0.2\",\n \"css-loader\": \"^3.4.2\",\n \"file-loader\": \"^5.1.0\",\n \"html-webpack-plugin\": \"^3.2.0\",\n \"less\": \"^3.11.1\",\n \"less-loader\": \"^5.0.0\",\n \"mini-css-extract-plugin\": \"^0.9.0\",\n \"optimize-css-assets-webpack-plugin\": \"^5.0.3\",\n \"ora\": \"^4.0.3\",\n \"postcss-loader\": \"^3.0.0\",\n \"postcss-preset-env\": \"^6.7.0\",\n \"rimraf\": \"^3.0.2\",\n \"style-loader\": \"^1.1.3\",\n \"svelte-loader\": \"^2.13.6\",\n \"terser-webpack-plugin\": \"^2.3.5\",\n \"url-loader\": \"^3.0.0\",\n \"webpack\": \"^4.42.0\",\n \"webpack-cli\": \"^3.3.11\",\n \"webpack-dev-server\": \"^3.10.3\",\n \"workbox-webpack-plugin\": \"^5.0.0\"\n }\n}\n```\n\n**babel.config.js**\n\n```\nmodule.exports = {\n presets: [\n ['@babel/preset-env', {\n modules: false,\n }],\n ],\n plugins: [\n '@babel/plugin-transform-runtime',\n '@babel/plugin-syntax-dynamic-import',\n ],\n};\n```\n\n**webpack.config.js**\n\n```\nconst webpack = require('webpack');\nconst CopyWebpackPlugin = require('copy-webpack-plugin');\nconst HtmlWebpackPlugin = require('html-webpack-plugin');\n\nconst MiniCssExtractPlugin = require('mini-css-extract-plugin');\nconst OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin');\nconst TerserPlugin = require('terser-webpack-plugin');\nconst WorkboxPlugin = require('workbox-webpack-plugin');\n\nconst path = require('path');\n\nfunction resolvePath(dir) {\n return path.join(__dirname, '..', dir);\n}\n\nconst env = process.env.NODE_ENV || 'development';\nconst target = process.env.TARGET || 'web';\nconst isCordova = target === 'cordova';\n\nmodule.exports = {\n mode: env,\n entry: {\n app: './src/js/app.js',\n },\n output: {\n path: resolvePath(isCordova ? 'cordova/www' : 'www'),\n filename: 'js/[name].js',\n chunkFilename: 'js/[name].js',\n publicPath: '',\n hotUpdateChunkFilename: 'hot/hot-update.js',\n hotUpdateMainFilename: 'hot/hot-update.json',\n },\n resolve: {\n extensions: ['.mjs', '.js', '.svelte', '.json'],\n alias: {\n\n '@': resolvePath('src'),\n },\n mainFields: ['svelte', 'browser', 'module', 'main']\n },\n devtool: env === 'production' ? 'source-map' : 'eval',\n devServer: {\n hot: true,\n open: true,\n compress: true,\n contentBase: '/www/',\n disableHostCheck: true,\n historyApiFallback: true,\n watchOptions: {\n poll: 1000,\n },\n },\n optimization: {\n minimizer: [new TerserPlugin({\n sourceMap: true,\n })],\n },\n module: {\n rules: [\n {\n test: /\\.(mjs|js|jsx)$/,\n use: 'babel-loader',\n include: [\n resolvePath('src'),\n resolvePath('node_modules/framework7'),\n\n resolvePath('node_modules/framework7-svelte'),\n resolvePath('node_modules/svelte'),\n resolvePath('node_modules/template7'),\n resolvePath('node_modules/dom7'),\n resolvePath('node_modules/ssr-window'),\n ],\n },\n\n {\n test: /\\.svelte$/,\n use: {\n loader: 'svelte-loader',\n options: {\n emitCss: true,\n },\n },\n },\n\n {\n test: /\\.css$/,\n use: [\n (env === 'development' ? 'style-loader' : {\n loader: MiniCssExtractPlugin.loader,\n options: {\n publicPath: '../'\n }\n }),\n 'css-loader',\n 'postcss-loader',\n ],\n },\n {\n test: /\\.styl(us)?$/,\n use: [\n (env === 'development' ? 'style-loader' : {\n loader: MiniCssExtractPlugin.loader,\n options: {\n publicPath: '../'\n }\n }),\n 'css-loader',\n 'postcss-loader',\n 'stylus-loader',\n ],\n },\n {\n test: /\\.less$/,\n use: [\n (env === 'development' ? 'style-loader' : {\n loader: MiniCssExtractPlugin.loader,\n options: {\n publicPath: '../'\n }\n }),\n 'css-loader',\n 'postcss-loader',\n 'less-loader',\n ],\n },\n {\n test: /\\.(sa|sc)ss$/,\n use: [\n (env === 'development' ? 'style-loader' : {\n loader: MiniCssExtractPlugin.loader,\n options: {\n publicPath: '../'\n }\n }),\n 'css-loader',\n 'postcss-loader',\n 'sass-loader',\n ],\n },\n {\n test: /\\.(png|jpe?g|gif|svg)(\\?.*)?$/,\n loader: 'url-loader',\n options: {\n limit: 10000,\n name: 'images/[name].[ext]',\n\n },\n },\n {\n test: /\\.(mp4|webm|ogg|mp3|wav|flac|aac|m4a)(\\?.*)?$/,\n loader: 'url-loader',\n options: {\n limit: 10000,\n name: 'media/[name].[ext]',\n\n },\n },\n {\n test: /\\.(woff2?|eot|ttf|otf)(\\?.*)?$/,\n loader: 'url-loader',\n options: {\n limit: 10000,\n name: 'fonts/[name].[ext]',\n\n },\n },\n ],\n },\n plugins: [\n new webpack.DefinePlugin({\n 'process.env.NODE_ENV': JSON.stringify(env),\n 'process.env.TARGET': JSON.stringify(target),\n }),\n\n ...(env === 'production' ? [\n new OptimizeCSSPlugin({\n cssProcessorOptions: {\n safe: true,\n map: { inline: false },\n },\n }),\n new webpack.optimize.ModuleConcatenationPlugin(),\n ] : [\n // Development only plugins\n new webpack.HotModuleReplacementPlugin(),\n new webpack.NamedModulesPlugin(),\n ]),\n new HtmlWebpackPlugin({\n filename: './index.html',\n template: './src/index.html',\n inject: true,\n minify: env === 'production' ? {\n collapseWhitespace: true,\n removeComments: true,\n removeRedundantAttributes: true,\n removeScriptTypeAttributes: true,\n removeStyleLinkTypeAttributes: true,\n useShortDoctype: true\n } : false,\n }),\n new MiniCssExtractPlugin({\n filename: 'css/[name].css',\n }),\n new CopyWebpackPlugin([\n {\n from: resolvePath('src/static'),\n to: resolvePath(isCordova ? 'cordova/www/static' : 'www/static'),\n },\n {\n from: resolvePath('src/manifest.json'),\n to: resolvePath('www/manifest.json'),\n },\n ]),\n ...(!isCordova ? [\n new WorkboxPlugin.InjectManifest({\n swSrc: resolvePath('src/service-worker.js'),\n })\n ] : []),\n\n ],\n};\n```\n\n========================================\n\nCode:\n```text\n{\n \"name\": \"test-app\",\n \"private\": true,\n \"version\": \"1.0.0\",\n \"description\": \"Test App\",\n \"repository\": \"\",\n \"license\": \"UNLICENSED\",\n \"framework7\": {\n \"cwd\": \"/Users/hirenraiyani/demo_apps\",\n \"type\": [\n \"pwa\",\n \"cordova\"\n ],\n \"name\": \"Test App\",\n \"framework\": \"svelte\",\n \"template\": \"tabs\",\n \"bundler\": \"webpack\",\n \"cssPreProcessor\": \"less\",\n \"theming\": {\n \"customColor\": false,\n \"color\": \"#007aff\",\n \"darkTheme\": false,\n \"iconFonts\": true,\n \"fillBars\": false\n },\n \"customBuild\": false,\n \"webpack\": {\n \"developmentSourceMap\": true,\n \"productionSourceMap\": true,\n \"hashAssets\": false,\n \"preserveAssetsPaths\": false,\n \"inlineAssets\": true\n },\n \"pkg\": \"io.framework7.myapp\",\n \"cordova\": {\n \"folder\": \"cordova\",\n \"platforms\": [\n \"android\"\n ],\n \"plugins\": [\n \"cordova-plugin-statusbar\",\n \"cordova-plugin-keyboard\",\n \"cordova-plugin-splashscreen\",\n \"cordova-plugin-wkwebview-engine\",\n \"cordova-plugin-device\",\n \"cordova-plugin-inappbrowser\",\n \"cordova-plugin-file\",\n \"cordova-plugin-media\"\n ]\n }\n },\n \"scripts\": {\n \"start\": \"npm run dev\",\n \"dev\": \"cross-env NODE_ENV=development webpack-dev-server --config ./build/webpack.config.js\",\n \"build-dev\": \"cross-env NODE_ENV=development node ./build/build.js\",\n \"build-prod\": \"cross-env NODE_ENV=production node ./build/build.js\",\n \"build-dev-cordova\": \"cross-env TARGET=cordova cross-env NODE_ENV=development node ./build/build.js && cd cordova && cordova build\",\n \"build-prod-cordova\": \"cross-env TARGET=cordova cross-env NODE_ENV=production node ./build/build.js && cd cordova && cordova build\",\n \"android-prod\": \"cross-env TARGET=cordova cross-env NODE_ENV=production node ./build/build.js && cd cordova && cordova run android\",\n \"postinstall\": \"cpy ./node_modules/framework7-icons/fonts/*.* ./src/fonts/\"\n },\n \"browserslist\": [\n \"Android >= 5\",\n \"IOS >= 11\",\n \"Safari >= 11\",\n \"Chrome >= 49\",\n \"Firefox >= 31\",\n \"Samsung >= 5\"\n ],\n \"dependencies\": {\n \"dom7\": \"^2.1.3\",\n \"framework7\": \"^5.5.0\",\n \"framework7-icons\": \"^3.0.0\",\n \"framework7-svelte\": \"^5.5.0\",\n \"svelte\": \"^3.19.2\",\n \"template7\": \"^1.4.2\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.8.7\",\n \"@babel/plugin-syntax-dynamic-import\": \"^7.8.3\",\n \"@babel/plugin-transform-runtime\": \"^7.8.3\",\n \"@babel/preset-env\": \"^7.8.7\",\n \"@babel/runtime\": \"^7.8.7\",\n \"babel-loader\": \"^8.0.6\",\n \"chalk\": \"^3.0.0\",\n \"copy-webpack-plugin\": \"^5.1.1\",\n \"cpy-cli\": \"^3.1.0\",\n \"cross-env\": \"^7.0.2\",\n \"css-loader\": \"^3.4.2\",\n \"file-loader\": \"^5.1.0\",\n \"html-webpack-plugin\": \"^3.2.0\",\n \"less\": \"^3.11.1\",\n \"less-loader\": \"^5.0.0\",\n \"mini-css-extract-plugin\": \"^0.9.0\",\n \"optimize-css-assets-webpack-plugin\": \"^5.0.3\",\n \"ora\": \"^4.0.3\",\n \"postcss-loader\": \"^3.0.0\",\n \"postcss-preset-env\": \"^6.7.0\",\n \"rimraf\": \"^3.0.2\",\n \"style-loader\": \"^1.1.3\",\n \"svelte-loader\": \"^2.13.6\",\n \"terser-webpack-plugin\": \"^2.3.5\",\n \"url-loader\": \"^3.0.0\",\n \"webpack\": \"^4.42.0\",\n \"webpack-cli\": \"^3.3.11\",\n \"webpack-dev-server\": \"^3.10.3\",\n \"workbox-webpack-plugin\": \"^5.0.0\"\n }\n}\n```\n\n```text\nmodule.exports = {\n presets: [\n ['@babel/preset-env', {\n modules: false,\n }],\n ],\n plugins: [\n '@babel/plugin-transform-runtime',\n '@babel/plugin-syntax-dynamic-import',\n ],\n};\n```\n\n```text\nconst webpack = require('webpack');\nconst CopyWebpackPlugin = require('copy-webpack-plugin');\nconst HtmlWebpackPlugin = require('html-webpack-plugin');\n\nconst MiniCssExtractPlugin = require('mini-css-extract-plugin');\nconst OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin');\nconst TerserPlugin = require('terser-webpack-plugin');\nconst WorkboxPlugin = require('workbox-webpack-plugin');\n\nconst path = require('path');\n\nfunction resolvePath(dir) {\n return path.join(__dirname, '..', dir);\n}\n\nconst env = process.env.NODE_ENV || 'development';\nconst target = process.env.TARGET || 'web';\nconst isCordova = target === 'cordova';\n\n\nmodule.exports = {\n mode: env,\n entry: {\n app: './src/js/app.js',\n },\n output: {\n path: resolvePath(isCordova ? 'cordova/www' : 'www'),\n filename: 'js/[name].js',\n chunkFilename: 'js/[name].js',\n publicPath: '',\n hotUpdateChunkFilename: 'hot/hot-update.js',\n hotUpdateMainFilename: 'hot/hot-update.json',\n },\n resolve: {\n extensions: ['.mjs', '.js', '.svelte', '.json'],\n alias: {\n\n '@': resolvePath('src'),\n },\n mainFields: ['svelte', 'browser', 'module', 'main']\n },\n devtool: env === 'production' ? 'source-map' : 'eval',\n devServer: {\n hot: true,\n open: true,\n compress: true,\n contentBase: '/www/',\n disableHostCheck: true,\n historyApiFallback: true,\n watchOptions: {\n poll: 1000,\n },\n },\n optimization: {\n minimizer: [new TerserPlugin({\n sourceMap: true,\n })],\n },\n module: {\n rules: [\n {\n test: /\\.(mjs|js|jsx)$/,\n use: 'babel-loader',\n include: [\n resolvePath('src'),\n resolvePath('node_modules/framework7'),\n\n\n resolvePath('node_modules/framework7-svelte'),\n resolvePath('node_modules/svelte'),\n resolvePath('node_modules/template7'),\n resolvePath('node_modules/dom7'),\n resolvePath('node_modules/ssr-window'),\n ],\n },\n\n {\n test: /\\.svelte$/,\n use: {\n loader: 'svelte-loader',\n options: {\n emitCss: true,\n },\n },\n },\n\n {\n test: /\\.css$/,\n use: [\n (env === 'development' ? 'style-loader' : {\n loader: MiniCssExtractPlugin.loader,\n options: {\n publicPath: '../'\n }\n }),\n 'css-loader',\n 'postcss-loader',\n ],\n },\n {\n test: /\\.styl(us)?$/,\n use: [\n (env === 'development' ? 'style-loader' : {\n loader: MiniCssExtractPlugin.loader,\n options: {\n publicPath: '../'\n }\n }),\n 'css-loader',\n 'postcss-loader',\n 'stylus-loader',\n ],\n },\n {\n test: /\\.less$/,\n use: [\n (env === 'development' ? 'style-loader' : {\n loader: MiniCssExtractPlugin.loader,\n options: {\n publicPath: '../'\n }\n }),\n 'css-loader',\n 'postcss-loader',\n 'less-loader',\n ],\n },\n {\n test: /\\.(sa|sc)ss$/,\n use: [\n (env === 'development' ? 'style-loader' : {\n loader: MiniCssExtractPlugin.loader,\n options: {\n publicPath: '../'\n }\n }),\n 'css-loader',\n 'postcss-loader',\n 'sass-loader',\n ],\n },\n {\n test: /\\.(png|jpe?g|gif|svg)(\\?.*)?$/,\n loader: 'url-loader',\n options: {\n limit: 10000,\n name: 'images/[name].[ext]',\n\n },\n },\n {\n test: /\\.(mp4|webm|ogg|mp3|wav|flac|aac|m4a)(\\?.*)?$/,\n loader: 'url-loader',\n options: {\n limit: 10000,\n name: 'media/[name].[ext]',\n\n },\n },\n {\n test: /\\.(woff2?|eot|ttf|otf)(\\?.*)?$/,\n loader: 'url-loader',\n options: {\n limit: 10000,\n name: 'fonts/[name].[ext]',\n\n },\n },\n ],\n },\n plugins: [\n new webpack.DefinePlugin({\n 'process.env.NODE_ENV': JSON.stringify(env),\n 'process.env.TARGET': JSON.stringify(target),\n }),\n\n ...(env === 'production' ? [\n new OptimizeCSSPlugin({\n cssProcessorOptions: {\n safe: true,\n map: { inline: false },\n },\n }),\n new webpack.optimize.ModuleConcatenationPlugin(),\n ] : [\n // Development only plugins\n new webpack.HotModuleReplacementPlugin(),\n new webpack.NamedModulesPlugin(),\n ]),\n new HtmlWebpackPlugin({\n filename: './index.html',\n template: './src/index.html',\n inject: true,\n minify: env === 'production' ? {\n collapseWhitespace: true,\n removeComments: true,\n removeRedundantAttributes: true,\n removeScriptTypeAttributes: true,\n removeStyleLinkTypeAttributes: true,\n useShortDoctype: true\n } : false,\n }),\n new MiniCssExtractPlugin({\n filename: 'css/[name].css',\n }),\n new CopyWebpackPlugin([\n {\n from: resolvePath('src/static'),\n to: resolvePath(isCordova ? 'cordova/www/static' : 'www/static'),\n },\n {\n from: resolvePath('src/manifest.json'),\n to: resolvePath('www/manifest.json'),\n },\n ]),\n ...(!isCordova ? [\n new WorkboxPlugin.InjectManifest({\n swSrc: resolvePath('src/service-worker.js'),\n })\n ] : []),\n\n ],\n};\n```\n\n```text\n\"browserslist\": [\n \"Android >= 5\",\n \"IOS >= 11\",\n \"Safari >= 11\",\n \"Chrome >= 49\",\n \"Firefox >= 31\",\n \"Samsung >= 5\"\n ],\n```\n\n```text\n\"dependencies\": {\n \"core-js\": \"^3.6.4\",\n ....\n}\n\ncheck **devdependencies**,\n\"devDependencies\": {\n \"@babel/core\": \"^7.8.7\",\n \"@babel/plugin-syntax-dynamic-import\": \"^7.8.3\",\n \"@babel/plugin-transform-runtime\": \"^7.8.3\",\n \"@babel/preset-env\": \"^7.8.7\",\n \"@babel/runtime\": \"^7.8.7\",\n \"babel-loader\": \"^8.0.6\",\n ...\n}\n```\n\n```text\nmodule.exports = {\n presets: [\n ['@babel/preset-env', {\n \"modules\": false,\n \"corejs\": 3,\n \"useBuiltIns\": \"usage\",\n \"targets\": {\n \"browsers\": [\n \"> 0.5%\",\n \"last 2 major versions\",\n \"safari >= 9\",\n \"not ie <= 11\",\n \"not dead\"\n ]\n }\n }],\n ],\n plugins: [\n '@babel/plugin-transform-runtime',\n '@babel/plugin-syntax-dynamic-import',\n ],\n};\n```\n\n```text\nmodule: {\n rules: [\n ....\n {\n test: /\\.svelte$/,\n use: [\n 'babel-loader',\n {\n loader: 'svelte-loader',\n options: {\n hotReload: false,\n emitCss: true,\n },\n },\n ],\n },\n ....\n```\n\n========================================\n\nComments:\n- I have similar issue, if any one have solution please let me know","metadata":{"transformedAt":"2026-08-18T18:33:40.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":812,"estimatedTokens":4749}}572{"id":"stack-62096839","source":"stackoverflow","questionId":62096839,"title":"Webpack devServer proxy not working with Sapper","tags":["webpack","svelte","sapper"],"text":"Title: Webpack devServer proxy not working with Sapper\nTags: webpack, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI have a **node** dev server running **Sapper** on `http://localhost:3000`, and I want all `/api/` requests proxy another local dev server written on python `http://localhost:8000/api/`\n\nThis worked perfectly for pure **Svelte**:\n\n```\n// webpack.config.js\n\nmodule.exports.devServer = {\n historyApiFallback: true,\n proxy: {\n '/api/': {\n target: 'http://localhost:8000',\n secure: false,\n changeOrigin: true\n }\n },\n};\n```\n\nBut does absolutely nothing with **Sapper** - just get default Sapper's 404 error\n\nI guess it is somehow related with **Sapper**'s routing mechanism, but can not find how to deal with it\n\n========================================\n\nCode:\n```text\n// webpack.config.js\n\nmodule.exports.devServer = {\n historyApiFallback: true,\n proxy: {\n '/api/': {\n target: 'http://localhost:8000',\n secure: false,\n changeOrigin: true\n }\n },\n};\n```\n\n```text\nhttp://localhost:3000\n```\n\n```text\n/api/\n```\n\n```text\nhttp://localhost:8000/api/\n```\n\n```text\nconst { createProxyMiddleware } = require('http-proxy-middleware');\n\npolka()\n .use('/api', createProxyMiddleware({ target: 'http://localhost:8000' }))\n // other .use, .listen rules\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":65,"estimatedTokens":329}}573{"id":"stack-58790619","source":"stackoverflow","questionId":58790619,"title":"Sapper keep getting warning from client about 'this' keyword?","tags":["javascript","frontend","rollupjs","svelte","sapper"],"text":"Title: Sapper keep getting warning from client about 'this' keyword?\nTags: javascript, frontend, rollupjs, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nKeep getting this warning from the client, but not entirely sure what could be causing it. Any guidance in the right direction would be very helpful!\n\n```\n• client\nThe 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten\n1: var __extends = (this && this.__extends) || (function () {\n ^\n2: var extendStatics = function (d, b) {\n3: extendStatics = Object.setPrototypeOf ||\nThe 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten\n1: var __extends = (this && this.__extends) || (function () {\n ^\n2: var extendStatics = function (d, b) {\n3: extendStatics = Object.setPrototypeOf ||\nThe 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten\n1: var __assign = (this && this.__assign) || function () {\n ^\n2: __assign = Object.assign || function(t) {\n3: for (var s, i = 1, n = arguments.length; i < n; i++) {\nThe 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten\n1: var __assign = (this && this.__assign) || function () {\n ^\n2: __assign = Object.assign || function(t) {\n3: for (var s, i = 1, n = arguments.length; i < n; i++) {\n```\n\n========================================\n\nCode:\n```text\n• client\nThe 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten\n1: var __extends = (this && this.__extends) || (function () {\n ^\n2: var extendStatics = function (d, b) {\n3: extendStatics = Object.setPrototypeOf ||\nThe 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten\n1: var __extends = (this && this.__extends) || (function () {\n ^\n2: var extendStatics = function (d, b) {\n3: extendStatics = Object.setPrototypeOf ||\nThe 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten\n1: var __assign = (this && this.__assign) || function () {\n ^\n2: __assign = Object.assign || function(t) {\n3: for (var s, i = 1, n = arguments.length; i < n; i++) {\nThe 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten\n1: var __assign = (this && this.__assign) || function () {\n ^\n2: __assign = Object.assign || function(t) {\n3: for (var s, i = 1, n = arguments.length; i < n; i++) {\n```\n\n```text\ncontext: \"window\"\n```\n\n========================================\n\nComments:\n- It looks like they are scanning a transpiled bundle, not an ES module.","metadata":{"transformedAt":"2026-08-18T18:33:40.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":66,"estimatedTokens":697}}574{"id":"stack-61653322","source":"stackoverflow","questionId":61653322,"title":"Benign cyclical dependencies","tags":["svelte","svelte-3","svelte-component"],"text":"Title: Benign cyclical dependencies\nTags: svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nTrying svelte for a new project I wrote a component to edit a compound object which delegates editing of individual parts to subcomponent and recreates the compound object whenever a part was changed. Of course, when the compound object is externally changed the subcomponents should be updated to the new values.\n\nI ended up with the following:\n\n```\n \n let item = \"content\";\n export let holder = { item };\n\n $: {\n console.log(\"setting item to \"+holder.item);\n item = holder.item;\n }\n\n $: setHolder(item);\n\n function setHolder(i) {\n console.log(\"setting holder for \"+i);\n holder = { item: i }\n }\n\n```\n\nThe above compiles but the content cannot be edited as somehow when `item` is edited the first reactive block is executed setting the variable back to `holder.item`. \n\nI don't understand the following:\n\n- Why is the first reactive block executed? As `item` only appears on the left-hand-side of an assignment it is not a value it depends on.\n\n- Why has the cyclical dependency be \"hidden\" from the compiler, why doesn't the following work?\n\n```\n$: {\n console.log(\"setting item to \"+holder.item);\n item = holder.item;\n }\n\n $: {\n console.log(\"setting holder for \"+item);\n holder = { item }\n }\n```\n\n- And why does everything work when wrapping both reactive blocks into functions?\n\n```\n$: setItem(holder)\n function setItem(h) {\n console.log(\"setting item to \"+h.item);\n item = h.item;\n }\n\n $: setHolder(item);\n function setHolder(i) {\n console.log(\"setting holder for \"+i);\n holder = { item: i }\n }\n```\n\nIt seems odd to relying on the compiler somehow not seeing what the code is doing so I'm wondering if I'm having a completly wrong approach.\n\n========================================\n\nCode:\n```html\n<script> \n let item = \"content\";\n export let holder = { item };\n\n $: {\n console.log(\"setting item to \"+holder.item);\n item = holder.item;\n }\n\n $: setHolder(item);\n\n function setHolder(i) {\n console.log(\"setting holder for \"+i);\n holder = { item: i }\n }\n</script>\n\n<input type=\"text\" bind:value={item} />\n```\n\n```js\n$: {\n console.log(\"setting item to \"+holder.item);\n item = holder.item;\n }\n\n $: {\n console.log(\"setting holder for \"+item);\n holder = { item }\n }\n```\n\n```js\n$: setItem(holder)\n function setItem(h) {\n console.log(\"setting item to \"+h.item);\n item = h.item;\n }\n\n $: setHolder(item);\n function setHolder(i) {\n console.log(\"setting holder for \"+i);\n holder = { item: i }\n }\n```\n\n```text\nitem\n```\n\n```text\nholder.item\n```\n\n```text\nitem\n```\n\n```text\nholder\n```\n\n```text\nitem\n```\n\n========================================\n\nComments:\n- While I agree with your assessment, I'm still having trouble to understand why `setItem` isn't triggered after `setHolder` updates `holder` (and it should since `holder` has been assigned an entirely new object?) Even in the function form, we should have an illegal cyclical dependency here, or am I missing something?\n- Still looking for an answer to this -up :(\n- @sleighty I have to say, I am not 100% sure, but it must be something with how Svelte optimizes comparing objects and primitives. Note that if you do `bind:value?={holder.item}` it does trigger both functions.\n- Interesting. What does the `?` do? I've never used that syntax in Svelte haha. In my case I'm using this pattern to enhance this Tabs component so that it can be used like `` so I'm not running into that inner `input bind:...` bit, thankfully. (If I remember right, Rich Harris posted a link to this Tabs implementation in another SO question: svelte.dev/repl/8e68120858e5322272dc9136c4bb79cc?version=3.7‌​.0)\n- the `?=` is a typo, lol :D","metadata":{"transformedAt":"2026-08-18T18:33:40.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":144,"estimatedTokens":953}}575{"id":"stack-56755721","source":"stackoverflow","questionId":56755721,"title":"Using relative sizes with rem units in Sapper","tags":["css","svelte","sapper"],"text":"Title: Using relative sizes with rem units in Sapper\nTags: css, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI am using Sapper to create a web app and want to use relative font sizes.\n\nI have set fixed font sizes for different media queries on the `body` element. Then I want to use `rem` units for the `font-size` in subsequent text elements of Svelte components to adjust the font-size to the viewport.\n\nHTML (Svelte component)\n\n```\n\n### Title\n\n```\n\nCSS (of the Svelte component)\n\n```\nh1 {\n font-size: 2rem;\n}\n```\n\nGlobal CSS of Sapper\n\n```\nbody {\n font-size: 12 px;\n}\n\n@media (min-width: 600px ) {\n body {\n font-size: 15px;\n }\n}\n```\n\nI would expect that the local component CSS is able to read the font-size on the global `body` element and therefore adjust the font-size in `h1` to the viewport size. However, no action is seen. In contrast, using `em` units works fine.\n\n========================================\n\nCode:\n```html\n<h1>Title</h1>\n```\n\n```text\nh1 {\n font-size: 2rem;\n}\n```\n\n```text\nbody {\n font-size: 12 px;\n}\n\n@media (min-width: 600px ) {\n body {\n font-size: 15px;\n }\n}\n```\n\n```text\nbody\n```\n\n```text\nrem\n```\n\n```text\nfont-size\n```\n\n```text\nbody\n```\n\n```text\nh1\n```\n\n```text\nem\n```\n\n```html\n<h1>Hello!</h1>\n\n<style>\n :global(html) {\n font-size: 12px;\n }\n\n @media (min-width: 600px) {\n :global(html) {\n font-size: 15px;\n }\n }\n\n h1 {\n font-size: 2rem;\n }\n</style>\n```\n\n```text\n:global\n```\n\n```text\nrem\n```\n\n```text\nhtml\n```\n\n```text\nbody\n```\n\n========================================\n\nComments:\n- Great, it's the `html` I have to style not the `body`, that was the bug. It actually works without the `:global`, when I include it in the `global.css` of Sapper. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:40.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":130,"estimatedTokens":429}}576{"id":"stack-65724373","source":"stackoverflow","questionId":65724373,"title":"Svelte: Unable to get imported unused CSS purged","tags":["svelte","rollup-plugin-postcss"],"text":"Title: Svelte: Unable to get imported unused CSS purged\nTags: svelte, rollup-plugin-postcss\nSource: Stack Overflow\n\nQuestion:\nI unsuccessfully tried to remove unused css imported from an external css file.\n\nI have tried a lot of combinaisons in vain, every time I run the build script I end up with a huge *bundle.css*.\n\nHere is the list of everything I tried so far:\n\n- Importing the file from App.svelte ``\n\n- Importing the file from App.svelte `` (using postcss-import)\n\n- Importing the file directly from main.js\n\n- Using postcss-purgecss along with rollup-plugin-postcss instead of passing by svelte-preprocess\n\nI am pretty sure there is something I am doing wrong but I honestly cannot figure out what.\n\nIf anyone have a clue on how to resolve this I would love to hear some feedback.\n\nSimple repo example: https://github.com/mgrisole/svelte-playground\n\n========================================\n\nCode:\n```text\n<script>\n```\n\n```text\n<style>\n```\n\n```text\nimport postcss from 'rollup-plugin-postcss';\n```\n\n```text\nsvelte({\n preprocess: sveltePreprocess({ postcss: true }),\n compilerOptions: {\n dev: !production,\n css: css => { css.write('bundle.css') },\n },\n ...(production && { emitCss: false }),\n}),\nproduction\n ? postcss({ extract: true, minimize: true })\n : css({ output: 'bundle.css' }),\n```\n\n```text\nconst purgecss = require('@fullhuman/postcss-purgecss')({\n content: ['./**/**/*.html', './**/**/*.svelte'],\n whitelistPatterns: [/svelte-/],\n defaultExtractor: content => content.match(/[\\w-/:]+(?<!:)/g) || []\n});\n\nconst isProduction = !process.env.ROLLUP_WATCH && !process.env.LIVERELOAD\n\nmodule.exports = {\n plugins: [\n ...(isProduction ? [purgecss] : [])\n ]\n};\n```\n\n```text\nrollup-plugin-postcss\n```\n\n```text\nrollup.config.js\n```\n\n```text\nrollup.config.js\n```\n\n```text\npostcss.config.js\n```\n\n========================================\n\nComments:\n- Thank you very much for your quick reply, unfortunately I end up with a nearly empty bundle.css after executing the build script. I created a branch following your suggestions, do you know if I omitted something: github.com/mgrisole/svelte-playground/tree/alternative-conf\n- You should remove or comment out `css({ output: 'bundle.css' })` (line 56). This is handled now in line 52, which runs only on dev mode.\n- Indeed, that was so obvious, thank so much mutil for your precious help!\n- I think we should change whitelistPatterns to safelist it seems like it has been changed since v3 github.com/FullHuman/purgecss/releases/tag/v3.0.0 It seems however that it is not needed, if I remove the exception svelte's selectors are not being removed. It surely need more investigation on my side though.","metadata":{"transformedAt":"2026-08-18T18:33:40.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":93,"estimatedTokens":669}}577{"id":"stack-73894568","source":"stackoverflow","questionId":73894568,"title":"Svelte importing svg as compoment works weird","tags":["html","css","svelte","sveltekit","svelte-component"],"text":"Title: Svelte importing svg as compoment works weird\nTags: html, css, svelte, sveltekit, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI've created this repl to demonstrate this issue. One SVG is just added inline and works ok, the other is imported as a component and doesn't work as intended. What's the difference? How do I get this scenario to work?\n\n========================================\n\nTop Answer:\nBasically yes, you missed the styling approach.\nYour both SVG is working fine except,\n\nI found that both are using same `id` that's why background overlapping, you can try with changing that.\n\n========================================\n\nCode:\n```css\n.my-stuff-svg-container :global(svg) {\n color: white;\n height: 1rem;\n width: 1rem;\n transition: 0.25s ease;\n }\n```\n\n```text\n:global\n```\n\n```text\nid\n```\n\n========================================\n\nComments:\n- Questions should be self contained; please include all relevant code *in* the question, not just in an off-site link.\n- Hah! thx! That was a fast answer","metadata":{"transformedAt":"2026-08-18T18:33:40.702Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":40,"estimatedTokens":259}}578{"id":"stack-68042095","source":"stackoverflow","questionId":68042095,"title":"How to keep a readable store in SvelteKit from being unsubscribed when changing pages/routes","tags":["svelte","sveltekit","svelte-store"],"text":"Title: How to keep a readable store in SvelteKit from being unsubscribed when changing pages/routes\nTags: svelte, sveltekit, svelte-store\nSource: Stack Overflow\n\nQuestion:\nIn SvelteKit, I get \"Subscribed\" and \"Unsubscribed\" logged to the console each time I navigate between the /first and /second routes. I want to have the readable's start function run *only once* for each user who visits the website - allowing me to store fetched data that doesn't change often.\n\n```\n// stores.ts\nimport { readable } from 'svelte/store'\nconst { VITE_WEB_URL } = import.meta.env\n\nexport const message = readable('', set => {\n console.log('Subscribed')\n const fetchMessage = async () => {\n const url = `${VITE_WEB_URL}/api/message`\n const response: Response = await fetch(url)\n return await response.text()\n }\n fetchMessage()\n .then(set)\n .catch(err => console.error('Failed to get message', err))\n return () => {\n console.log('Unsubscribed')\n }\n})\n```\n\n```\n\n import { message } from '../stores'\n\n### First: {$message}\n\nSecond\n```\n\n```\n\n import { message } from '../stores'\n\n### Second: {$message}\n\nFirst\n```\n\nAs I navigate between pages/routes in SvelteKit, unsubscribe is called so the next page/route invokes the start function as the \"first\" subscriber.\n\nHow can readable stores be shared across multiple pages/routes without re-running the start function? I've heard suggestions about using the template but have never seen an example.\n\nWould the template get the store value and pass it as props to components or simply prevent the store from having a \"last subscriber\" (effectively keep the door open)?\n\n========================================\n\nTop Answer:\nIt says that it is called when the first subscriber subscribes and then the delete function is called when the last subscriber unsubscribes. When you change routes it unsubscribes all subscribers and then runs the delete function, then when you get to the next route it reruns the initial function.\n\n========================================\n\nCode:\n```js\n// stores.ts\nimport { readable } from 'svelte/store'\nconst { VITE_WEB_URL } = import.meta.env\n\nexport const message = readable('', set => {\n console.log('Subscribed')\n const fetchMessage = async () => {\n const url = `${VITE_WEB_URL}/api/message`\n const response: Response = await fetch(url)\n return await response.text()\n }\n fetchMessage()\n .then(set)\n .catch(err => console.error('Failed to get message', err))\n return () => {\n console.log('Unsubscribed')\n }\n})\n```\n\n```svelte\n<!-- /routes/first.svelte -->\n<script>\n import { message } from '../stores'\n</script>\n\n<h1>First: {$message}</h1>\n\n<a href=\"/second\">Second</a>\n```\n\n```svelte\n<!-- /routes/second.svelte -->\n<script>\n import { message } from '../stores'\n</script>\n\n<h1>Second: {$message}</h1>\n\n<a href=\"/first\">First</a>\n```\n\n```svelte\n<!-- /lib/ComponentUsingMessage.svelte-->\n<script>\n import { message } from '../stores'\n</script>\n\n<p>{$message}</p>\n```\n\n```svelte\n<!-- /routes/__layout.svelte-->\n<script>\n import { message } from '../stores'\n // Or include a component in the template that loads $message...\n import ComponentUsingMessage from '$lib/ComponentUsingMessage.svelte'\n</script>\n\n<main>\n Both subscribe but do not unsubscribe while template is loaded:\n {$message}\n <ComponentUsingMessage/>\n\n <slot></slot>\n</main>\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.702Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":128,"estimatedTokens":834}}579{"id":"stack-45104864","source":"stackoverflow","questionId":45104864,"title":"Does Svelte support checkbox binding?","tags":["svelte"],"text":"Title: Does Svelte support checkbox binding?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nDoes Svelte support bindings for checkboxes?\n\nI am aware that the documentation says the following, so it is possible that it has yet to be implemented.\n\n Two-way binding is not yet fully implemented. Check back soon for the full list of available bindings!\n\nI imagine that the implementation would look something like this.\n\n```\n\n```\n\nHowever, when I try this at the moment, it does not seem to work.\n\n**Update**\n\nUpon further investigation, it seems that the binding is working in some way, with the bound value changing in the component data. However, for some reason, changes are not being reflected in the DOM. They can be reflected by simply setting the data to be itself (`component.set({checked: component.get('checked')})`), forcing a DOM update, but they are not being reflected automatically, as they should with binding.\n\n**Update 2**\n\nI have created a REPL to demonstrate this problem.\n\n========================================\n\nTop Answer:\nThis can be done with\n\n```\n\n let checked = false;\n\n```\n\nNow the variable `checked` is bound to the value of checkbox.\n\nYou can try this in this neat little example\n\n========================================\n\nCode:\n```text\n<input type=\"checkbox\" bind:checked=\"checked\">\n```\n\n```text\ncomponent.set({checked: component.get('checked')})\n```\n\n```html\n<Component bind:checked=\"checked\"></Component>\n```\n\n```text\n<input>\n```\n\n```text\n<script>\n let checked = false;\n</script>\n\n\n<input type=checkbox bind:checked={checked}>\n```\n\n```text\nchecked\n```\n\n========================================\n\nComments:\n- Great, thanks for the help. This did not cross my mind, as I was under the impression that data properties were already bound together once they had been passed from a parent component to a child component. Is it that there is a one-way binding from the parent component to the child component in this case, and that `:bind` declares a two-way binding between the parent and the child?\n- That's exactly right, yes — it's designed that way so that unidirectional data flow is the default, and two-way binding is opt-in (since it can cause nasty mutation bugs if done blindly)\n- I tried the linked example but it says \"Could not load ./App.html: O is not a function\"\n- @poshaughnessy try the updated link (it was using an older version of Svelte, with an out of date syntax)","metadata":{"transformedAt":"2026-08-18T18:33:40.702Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":81,"estimatedTokens":604}}580{"id":"stack-74336237","source":"stackoverflow","questionId":74336237,"title":"How to test the reaction to a component event in Svelte?","tags":["javascript","tdd","svelte","svelte-testing-library"],"text":"Title: How to test the reaction to a component event in Svelte?\nTags: javascript, tdd, svelte, svelte-testing-library\nSource: Stack Overflow\n\nQuestion:\nIn Svelte, I have a parent component which listens to a component event dispatched by a child component.\n\nI know how to use `component.$on` to check that the dispatched event does the right thing *within the component which is dispatching*, like so.\n\nBut **I can't figure out how to check that the component which receives the dispatch does the right thing in response.**\n\nHere's a basic example:\n\n**Child.svelte**\n\n```\n\n import { createEventDispatcher } from 'svelte'\n\n const dispatch = createEventDispatcher()\n \n function handleSubmit(event) {\n dispatch('results', 'some results')\n }\n\n Submit\n\n```\n\n**Parent.svelte**\n\n```\n\n import Child from './Child.svelte'\n\n let showResults = false\n\n function handleResults(event) {\n showResults = true\n }\n\n{ #if showResults }\n Some results.\n\n{ /if }\n```\n\nThe idea is to eventually write a test using `@testing-library/svelte` like:\n\n```\nimport { render } from '@testing-library/svelte'\nimport Parent from './Parent.svelte'\n\ntest('shows results when it receives them', () => {\n const rendered = render(Parent)\n \n // ***\n // Simulate the `results` event from the child component?\n // ***\n\n // Check that the results appear.\n})\n```\n\nIf the parent were reacting to a DOM event, I would use `fireEvent`.\n\nBut I don't know how I would get a hold of the `` component in this case, and even if I could I'm guessing that Svelte is using a different mechanism for component events.\n\n(Just to test it out, I used `createEvent` to fire a custom `results` event on one of the DOM elements rendered by `` but it didn't seem to do anything.)\n\nAnyone have any ideas? Thanks!\n\n========================================\n\nCode:\n```text\n<script>\n import { createEventDispatcher } from 'svelte'\n\n const dispatch = createEventDispatcher()\n \n function handleSubmit(event) {\n dispatch('results', 'some results')\n }\n</script>\n\n<form on:submit|preventDefault={ handleSubmit }>\n <button type='submit'>Submit</button>\n</form>\n```\n\n```text\n<script>\n import Child from './Child.svelte'\n\n let showResults = false\n\n function handleResults(event) {\n showResults = true\n }\n</script>\n\n<Child on:results={ handleResults } />\n\n{ #if showResults }\n <p id='results'>Some results.</p>\n{ /if }\n```\n\n```text\nimport { render } from '@testing-library/svelte'\nimport Parent from './Parent.svelte'\n\ntest('shows results when it receives them', () => {\n const rendered = render(Parent)\n \n // ***\n // Simulate the `results` event from the child component?\n // ***\n\n // Check that the results appear.\n})\n```\n\n```text\ncomponent.$on\n```\n\n```text\n@testing-library/svelte\n```\n\n```text\nfireEvent\n```\n\n```text\n<Child>\n```\n\n```text\ncreateEvent\n```\n\n```text\nresults\n```\n\n```text\n<Child>\n```\n\n```text\ntest('shows results when it receives them', async () => {\n // Arrange\n const rendered = render(Parent)\n\n const submitButton = rendered.getByRole('button', {\n name: /submit/i\n });\n\n const user = userEvent.setup();\n\n // Act\n await user.click(submitButton);\n\n // Assert\n const results = rendered.queryByText(/some results\\./i);\n\n expect(results).not.toBe(null);\n});\n```\n\n```text\n<script>\n import { createEventDispatcher } from \"svelte\";\n\n const dispatch = createEventDispatcher();\n\n function handleSubmit(event) {\n dispatch(\"results\", \"some results\");\n }\n</script>\n\n<form on:submit|preventDefault={handleSubmit}>\n <button type=\"submit\">Test</button>\n</form>\n```\n\n```text\n@testing-library/svelte\n```\n\n```text\nChild\n```\n\n```text\nresults\n```\n\n```text\nfireEvent\n```\n\n```text\nSubmitEvent\n```\n\n```text\n<form>\n```\n\n```text\n@testing-library/user-event\n```\n\n```text\ndispatchEvent\n```\n\n```text\nresults\n```\n\n```text\nParent\n```\n\n```text\nChild.svelte\n```\n\n```text\n__mocks__/Child.svelte\n```\n\n```text\nresults\n```\n\n```text\njest.mock(\"./Child.svelte\");\n```\n\n```text\ngetByRole\n```\n\n```text\n<p>\n```\n\n========================================\n\nComments:\n- Thanks @Desjardins! This makes sense and it does answer the question. With this approach, the Parent test has to know a lot about the Child component. I'm wondering if there's a way to mock out the Child component and/or simulate the dispatched event. Otherwise every time the Child component changes, this test would have to change too.\n- @jrh, that's true, you don't really get much of a traditional \"unit\" test with this approach. The idea behind this Testing Library is that, for UIs, it's testing that a user's interaction behaves as expected, which is why its primary functions are about grabbing things by their accessibility roles and performing user actions on them, without really caring about the name or details of the event. However, it should be possible to make a fake Child component that you can use to trigger the `results` event.","metadata":{"transformedAt":"2026-08-18T18:33:40.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":28,"totalLines":258,"estimatedTokens":1214}}581{"id":"stack-67639447","source":"stackoverflow","questionId":67639447,"title":"SvelteKit endpoint: converting from Node/Express","tags":["node.js","express","svelte","node-postgres","sveltekit"],"text":"Title: SvelteKit endpoint: converting from Node/Express\nTags: node.js, express, svelte, node-postgres, sveltekit\nSource: Stack Overflow\n\nQuestion:\nNew to SvelteKit and working to adapt an endpoint from a Node/Express server to make it more generic so as to be able to take advantage of SvelteKit adapters. The endpoint downloads files stored in a database via node-postgresql.\n\nMy functional endpoint in Node/Express looks like this:\n\n```\nimport stream from 'stream'\nimport db from '../utils/db'\n\nexport async function download(req, res) {\n const _id = req.params.id\n const sql = \"SELECT _id, name, type, data FROM files WHERE _id = $1;\"\n const { rows } = await db.query(sql, [_id])\n const file = rows[0]\n const fileContents = Buffer.from(file.data, 'base64')\n const readStream = new stream.PassThrough()\n readStream.end(fileContents)\n res.set('Content-disposition', `attachment; filename=${file.name}`)\n res.set('Content-Type', file.type)\n readStream.pipe(res)\n}\n```\n\nHere's what I have for [filenum].json.ts in SvelteKit so far...\n\n```\nimport stream from 'stream'\nimport db from '$lib/db'\n\nexport async function get({ params }): Promise {\n const { filenum } = params\n const { rows } = await db.query('SELECT _id, name, type, data FROM files WHERE _id = $1;', [filenum])\n \n if (rows) {\n const file = rows[0]\n const fileContents = Buffer.from(file.data, 'base64')\n const readStream = new stream.PassThrough()\n readStream.end(fileContents)\n let body\n readStream.pipe(body)\n\n return {\n headers: {\n 'Content-disposition': `attachment; filename=${file.name}`,\n 'Content-type': file.type\n },\n body\n }\n }\n}\n```\n\nWhat is the correct way to do this with SvelteKit without creating a dependency on Node? Per SvelteKit's Endpoint docs,\n\nWe don't interact with the req/res objects you might be familiar with from Node's http module or frameworks like Express, because they're only available on certain platforms. Instead, SvelteKit translates the returned object into whatever's required by the platform you're deploying your app to.\n\n========================================\n\nCode:\n```js\nimport stream from 'stream'\nimport db from '../utils/db'\n\nexport async function download(req, res) {\n const _id = req.params.id\n const sql = \"SELECT _id, name, type, data FROM files WHERE _id = $1;\"\n const { rows } = await db.query(sql, [_id])\n const file = rows[0]\n const fileContents = Buffer.from(file.data, 'base64')\n const readStream = new stream.PassThrough()\n readStream.end(fileContents)\n res.set('Content-disposition', `attachment; filename=${file.name}`)\n res.set('Content-Type', file.type)\n readStream.pipe(res)\n}\n```\n\n```js\nimport stream from 'stream'\nimport db from '$lib/db'\n\nexport async function get({ params }): Promise<any> {\n const { filenum } = params\n const { rows } = await db.query('SELECT _id, name, type, data FROM files WHERE _id = $1;', [filenum])\n \n if (rows) {\n const file = rows[0]\n const fileContents = Buffer.from(file.data, 'base64')\n const readStream = new stream.PassThrough()\n readStream.end(fileContents)\n let body\n readStream.pipe(body)\n\n return {\n headers: {\n 'Content-disposition': `attachment; filename=${file.name}`,\n 'Content-type': file.type\n },\n body\n }\n }\n}\n```\n\n```js\n// src/routes/api/file/_file.controller.ts\nimport { query } from '../_db'\n\ntype GetFileResponse = (fileNumber: string) => Promise<{\n headers: {\n 'Content-Disposition': string\n 'Content-Type': string\n }\n body: Uint8Array\n status?: number\n} | {\n status: number\n headers?: undefined\n body?: undefined\n}>\n\nexport const getFile: GetFileResponse = async (fileNumber: string) => {\n const { rows } = await query(`SELECT _id, name, type, data FROM files WHERE _id = $1;`, [fileNumber])\n if (rows) {\n const file = rows[0]\n return {\n headers: {\n 'Content-Disposition': `attachment; filename=\"${file.name}\"`,\n 'Content-Type': file.type\n },\n body: new Uint8Array(file.data)\n }\n } else return {\n status: 404\n }\n}\n```\n\n```js\n// src/routes/api/file/[filenum].ts\nimport type { RequestHandler } from '@sveltejs/kit'\nimport { getFile } from './_file.controller'\n\nexport const get: RequestHandler = async ({ params }) => {\n const { filenum } = params\n const fileResponse = await getFile(filenum)\n return fileResponse\n}\n```\n\n========================================\n\nComments:\n- Why do you want to remove the node dependency ? The endpoints run on the server, which for all adapters (except static) will be in a node environment anyway.\n- SvelteKit's docs on kit.svelte.dev/docs#routing-endpoints say, \"We don't interact with the req/res objects you might be familiar with from Node's http module or frameworks like Express, because they're only available on certain platforms. Instead, SvelteKit translates the returned object into whatever's required by the platform you're deploying your app to.\"\n- yes, but that doesn't mean you don't have access to other node functionality, just that sveltekit abstracts away the req/res part.\n- As res is not available in the get method, wondering how to call readStream.pipe(res).\n- just pipe it in another temporary variable ?\n- Just adjust the sample above. Getting \"TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined\"","metadata":{"transformedAt":"2026-08-18T18:33:40.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":163,"estimatedTokens":1346}}582{"id":"stack-67570098","source":"stackoverflow","questionId":67570098,"title":"Why button using 'focus-within' is not working on iOS","tags":["html","css","svelte"],"text":"Title: Why button using 'focus-within' is not working on iOS\nTags: html, css, svelte\nSource: Stack Overflow\n\nQuestion:\nI need a hidden delete button to appear and work when a input is focused using markup and CSS in Svelte.\n\nI got it all working in browsers for OS X and Raspberry Pi OS (Chrome, Chromium, Safari and Firefox). Click here to see it.\n\nThe problem is that the button appears but is not working in any of my iOS browsers (Safari or Firefox). Nothing is happening when the delete button is clicked.\n\nI've tried following:\n\n- focus-within works on Android browser but not iOS\n\n- How to make a button appear only when input is focused\n\nHere is the markup...\n\n```\n\n {#if $todos}\n {#each $todos as { data }, i}\n \n 🗑\n \n \n {/each}\n {/if}\n\n```\n\n...and here is the styling...\n\n```\n\n form,\n div {\n display: flex;\n flex-wrap: wrap;\n }\n\n input {\n border-style: none;\n font-size: 2vh;\n }\n\n input:focus {\n border-style: solid;\n }\n\n button {\n visibility: hidden;\n font-size: 2vh;\n }\n\n #todo:focus-within button {\n visibility: visible;\n }\n\n```\n\n\r\n\r\n\n```\nform,\ndiv {\n display: flex;\n}\n\nform {\n width: 100vw;\n}\n\ninput {\n border-style: none;\n}\n\ninput:focus {\n border-style: solid;\n}\n\nbutton {\n visibility: hidden;\n}\n\n#todo1:focus-within button {\n visibility: visible;\n}\n\n#todo2:focus-within button {\n visibility: visible;\n}\n\n#todo3:focus-within button {\n visibility: visible;\n}\n```\n\n\r\n\n```\n\n \n \n Svelte + Node.js API\n\n \n\n### To Do\n\n \n \n 🗑\n \n \n \n 🗑\n \n \n \n 🗑\n \n \n \n\n```\n\n========================================\n\nTop Answer:\nHere is a solution using \"opacity\" instead of \"visibility\" which seems to work also with iOS browsers.\n\n\r\n\r\n\n```\nform,\ndiv {\n display: flex;\n}\n\nform {\n width: 100vw;\n}\n\ninput {\n border-style: none;\n}\n\ninput:focus {\n border-style: solid;\n}\n\nbutton {\n opacity: 0;\n}\n\n#todo1:focus-within button {\n opacity: 1;\n}\n\n#todo2:focus-within button {\n opacity: 1;\n}\n\n#todo3:focus-within button {\n opacity: 1;\n}\n```\n\n\r\n\n```\n\n \n \n Svelte + Node.js API\n\n \n\n### To Do\n\n \n \n 🗑\n \n \n \n 🗑\n \n \n \n 🗑\n \n \n \n\n```\n\n========================================\n\nCode:\n```text\n<form>\n {#if $todos}\n {#each $todos as { data }, i}\n <div id=\"todo\">\n <button on:click|preventDefault={remove(i + 1)}>🗑</button>\n <input\n bind:value={data.name}\n on:change={update(i + 1)}\n size={data.name.length}\n maxlength=\"35\"\n />\n </div>\n {/each}\n {/if}\n</form>\n```\n\n```text\n<style>\n form,\n div {\n display: flex;\n flex-wrap: wrap;\n }\n\n input {\n border-style: none;\n font-size: 2vh;\n }\n\n input:focus {\n border-style: solid;\n }\n\n button {\n visibility: hidden;\n font-size: 2vh;\n }\n\n #todo:focus-within button {\n visibility: visible;\n }\n</style>\n```\n\n```css\nform,\ndiv {\n display: flex;\n}\n\nform {\n width: 100vw;\n}\n\ninput {\n border-style: none;\n}\n\ninput:focus {\n border-style: solid;\n}\n\nbutton {\n visibility: hidden;\n}\n\n#todo1:focus-within button {\n visibility: visible;\n}\n\n#todo2:focus-within button {\n visibility: visible;\n}\n\n#todo3:focus-within button {\n visibility: visible;\n}\n```\n\n```html\n<html lang=\"en\">\n\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <title>Svelte + Node.js API</title>\n</head>\n\n<body>\n <h1>To Do</h1>\n <form>\n <div id=\"todo1\">\n <button onclick=\"alert('Input deleted')\">🗑</button>\n <input value=\"Try it out\">\n </div>\n <div id=\"todo2\">\n <button onclick=\"alert('Input deleted')\">🗑</button>\n <input value=\"Fix the bug\">\n </div>\n <div id=\"todo3\">\n <button onclick=\"alert('Input deleted')\">🗑</button>\n <input value=\"Celebrate\">\n </div>\n </form>\n</body>\n\n</html>\n```\n\n```js\nfunction setLogs(element) {\n element.addEventListener(\"focus\", () => {\n console.log(\"focus\", element);\n });\n\n element.addEventListener(\"blur\", () => {\n console.log(\"blur\", element);\n });\n\n for (const child of element.children)\n setLogs(child);\n}\n\nsetLogs(document.body);\n```\n\n```css\nbutton {\n visibility: hidden;\n}\n\n#todo:focus-within button {\n visibility: visible;\n}\n```\n\n```html\n<div class=\"content\">\n <h1>To Do</h1>\n <form onsubmit=\"return false\">\n <div id=\"todo\">\n <button onclick=\"console.log('Input deleted')\">🗑</button>\n <input value=\"Try it out\">\n </div>\n </form>\n</div>\n```\n\n```text\n<div>\n```\n\n```text\n<input>\n```\n\n```text\n:focus-within\n```\n\n```text\n<div>\n```\n\n```css\nform,\ndiv {\n display: flex;\n}\n\nform {\n width: 100vw;\n}\n\ninput {\n border-style: none;\n}\n\ninput:focus {\n border-style: solid;\n}\n\nbutton {\n opacity: 0;\n}\n\n#todo1:focus-within button {\n opacity: 1;\n}\n\n#todo2:focus-within button {\n opacity: 1;\n}\n\n#todo3:focus-within button {\n opacity: 1;\n}\n```\n\n```html\n<html lang=\"en\">\n\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <title>Svelte + Node.js API</title>\n</head>\n\n<body>\n <h1>To Do</h1>\n <form>\n <div id=\"todo1\">\n <button onclick=\"alert('Input deleted')\">🗑</button>\n <input value=\"Try it out\">\n </div>\n <div id=\"todo2\">\n <button onclick=\"alert('Input deleted')\">🗑</button>\n <input value=\"Fix the bug\">\n </div>\n <div id=\"todo3\">\n <button onclick=\"alert('Input deleted')\">🗑</button>\n <input value=\"Celebrate\">\n </div>\n </form>\n</body>\n\n</html>\n```\n\n```text\nmousedown\n```\n\n```text\nclick\n```\n\n```text\nclick\n```\n\n```text\n<div id=\"todo1\" tabindex=\"0\">\n <button onclick=\"alert('Input deleted')\">🗑</button>\n <input value=\"Try it out\">\n</div>\n```\n\n```css\nform,\ndiv {\n display: flex;\n}\n\nform {\n width: 100vw;\n}\n\ninput {\n border-style: none;\n}\n\ninput:focus {\n border-style: solid;\n}\n\nbutton {\n visibility: hidden;\n}\n\n#todo1:focus-within button {\n visibility: visible;\n}\n\n#todo2:focus-within button {\n visibility: visible;\n}\n\n#todo3:focus-within button {\n visibility: visible;\n}\n```\n\n```html\n<html lang=\"en\">\n\n<head>\n <meta charset=\"utf8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <title>Svelte + Node.js API</title>\n</head>\n\n<body>\n <h1>To Do</h1>\n <form>\n <div id=\"todo1\" tabindex=\"0\">\n <button onclick=\"alert('Input deleted')\">🗑</button>\n <input value=\"Try it out\">\n </div>\n <div id=\"todo2\" tabindex=\"0\">\n <button onclick=\"alert('Input deleted')\">🗑</button>\n <input value=\"Fix the bug\">\n </div>\n <div id=\"todo3\" tabindex=\"0\">\n <button onclick=\"alert('Input deleted')\">🗑</button>\n <input value=\"Celebrate\">\n </div>\n </form>\n</body>\n\n</html>\n```\n\n```text\n<div id=\"todo1\">\n <div role=\"button\" tabindex=\"0\" onclick=\"alert('Input deleted')\">🗑</div>\n <input value=\"Try it out\">\n</div>\n```\n\n```css\nform,\ndiv {\n display: flex;\n}\n\nform {\n width: 100vw;\n}\n\ninput {\n border-style: none;\n}\n\ninput:focus {\n border-style: solid;\n}\n\ndiv[role=\"button\"] {\n visibility: hidden;\n}\n\n#todo1:focus-within div[role=\"button\"] {\n visibility: visible;\n}\n\n#todo2:focus-within div[role=\"button\"] {\n visibility: visible;\n}\n\n#todo3:focus-within div[role=\"button\"] {\n visibility: visible;\n}\n```\n\n```html\n<html lang=\"en\">\n\n<head>\n <meta charset=\"utf8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <title>Svelte + Node.js API</title>\n</head>\n\n<body>\n <h1>To Do</h1>\n <form>\n <div id=\"todo1\">\n <div role=\"button\" tabindex=\"0\" onclick=\"alert('Input deleted')\" style=\"cursor: pointer;\">🗑</div>\n <input value=\"Try it out\">\n </div>\n <div id=\"todo2\">\n <div role=\"button\" tabindex=\"0\" onclick=\"alert('Input deleted')\" style=\"cursor: pointer;\">🗑</div>\n <input value=\"Fix the bug\">\n </div>\n <div id=\"todo3\">\n <div role=\"button\" tabindex=\"0\" onclick=\"alert('Input deleted')\" style=\"cursor: pointer;\">🗑</div>\n <input value=\"Celebrate\">\n </div>\n </form>\n</body>\n\n</html>\n```\n\n```text\n<style>\ndiv:focus-within button {\nvisibility: visible;\n}\nbutton {\nvisibility: hidden;\n}\n</style>\n<div>\n <input type=\"text\" />\n <button onclick=\"alert('Hi there')\">Hello</button>\n <button tabindex=\"0\" onclick=\"alert('See ya!')\">Goodbye</button>\n</div>\n```\n\n```text\n:focus-within\n```\n\n```text\nonclick\n```\n\n```text\ntabindex=\"0\"\n```\n\n```text\nalert()\n```\n\n========================================\n\nComments:\n- I like your answer but why it works in other browsers than for iOS? Any solution?\n- I am honestly not sure why this works in other browsers (I've tried Chrome); to me, Apple's implementation or more consistent, but Google's implementation is more convenient.\n- The explanation is reasonable, but I don't think that's what's going on here. Even without hiding the button at all it doesn't get focused on iOS: jsfiddle.net/Levu1a64/2 . What's probably happening here is that Safari doesn't focus on button elements at all: developer.mozilla.org/en-US/docs/Web/HTML/Element/… stackoverflow.com/questions/42758815/…\n- Thanks for your suggestion! Tried it but unfortunately it broke my program. \"Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.\"\n- A network error is unrelated to this problem though, so it is more to do with your specific app than getting the button to trigger on ios","metadata":{"transformedAt":"2026-08-18T18:33:40.703Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":631,"estimatedTokens":2318}}583{"id":"stack-72815328","source":"stackoverflow","questionId":72815328,"title":"how can I resolve a collision between two events, click outside and on the button to close a menu in svelte kit?","tags":["javascript","button","onclick","svelte","sveltekit"],"text":"Title: how can I resolve a collision between two events, click outside and on the button to close a menu in svelte kit?\nTags: javascript, button, onclick, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a problem in `svelteKit` with a collision. The button opens the menu but when I try to close it, it doesn't. When I click outside the button, this triggers `handleClickOutside` which calls `clickOutside.js`, and then closes the menu.\n\nI think that the problem is that `element.contains` includes the button and for that, the menu didn't close.\n\nhowever, I couldn't fix it.\n\nI'm using `tailwindUI`, `tailwindCSS`, `SvelteKit`.\n\n***index.svelte***\n\n```\n\n // @ts-nocheck\n import bostonLogo from '../../img/bostonLogo.png';\n import { clickOutside } from '../../lib/clickOutside';\n\n // Example Profile\n let profile = {\n name: 'Matias',\n lastName: 'Barletta'\n };\n\n // Show/Hide Menu\n\n let menu = false;\n\n // COLLISION WITH HANDLENAV\n \n function handleClickOutside(event) { \n menu = false; \n }\n\n function handleNav() {\n\n menu = !menu;\n \n }\n\n \n \n \n \n...\n```\n\n***clickOutside.js***\n\n```\n// @ts-nocheck\n/** Dispatch event on click outside of element */\n// @ts-ignore\n\nexport function clickOutside(element) {\n // @ts-ignore\n\n const handleClick = (event) => {\n console.log(event.target, document.body)\n \n // element exist?, element contain where i did click, preventDefault = false?\n if (element && !element.contains(event.target) && !event.defaultPrevented) {\n element.dispatchEvent(\n // Dispatch and create new custom event.\n new CustomEvent('click_outside', element)\n );\n }\n };\n // add eventlistener when you click on document\n document.addEventListener('click', handleClick, true);\n\n return {\n destroy() {\n document.removeEventListener('click', handleClick, true);\n }\n };\n}\n```\n\n========================================\n\nTop Answer:\n**Typescript Version with Tailwind**\n\nAnybody coming in the future. Here is the typescript version.\n\n**click_outside.ts**\n\n```\nexport function clickOutside(node: HTMLElement, opts?: string) {\n function detect({ target }: MouseEvent) {\n if (opts !== undefined) {\n const ignore = document.getElementById(opts);\n if (ignore?.contains(target as Node)) return;\n\n if (!node.contains(target as Node)) {\n node.dispatchEvent(new CustomEvent('clickoutside'));\n }\n } else {\n if (!node.contains(target as Node)) {\n node.dispatchEvent(new CustomEvent('clickoutside'));\n }\n }\n }\n document.addEventListener('click', detect, { passive: true, capture: true });\n return {\n destroy() {\n document.removeEventListener('click', detect);\n }\n };\n}\n```\n\n**app.d.ts (for adding types)**\n\n```\ndeclare namespace svelteHTML {\n interface HTMLAttributes {\n 'on:clickoutside'?: (event: CustomEvent) => void;\n }\n }\n```\n\n**+page.svelte**\n\n```\n\n \n\n import { clickOutside } from './click_outside';\n\n let menu = false;\n\n {menu = !menu}}\n >Click!\n\n {menu = false}}\n \n class={`${menu ? 'block' : 'hidden'} absolute bg-blue-500 top-16 left-0 bg-slate-100 p-2`} \n >\n \n Some menu content here\n \n\n```\n\n========================================\n\nCode:\n```text\n<script>\n // @ts-nocheck\n import bostonLogo from '../../img/bostonLogo.png';\n import { clickOutside } from '../../lib/clickOutside';\n\n // Example Profile\n let profile = {\n name: 'Matias',\n lastName: 'Barletta'\n };\n\n // Show/Hide Menu\n\n let menu = false;\n\n // COLLISION WITH HANDLENAV\n \n function handleClickOutside(event) { \n menu = false; \n }\n\n function handleNav() {\n\n menu = !menu;\n \n }\n\n</script>\n\n<div>\n <!-- Static sidebar for desktop -->\n <div class=\" md:flex md:w-64 md:flex-col md:fixed md:inset-y-0\" class:hidden={!menu}>\n <!-- Sidebar component, swap this element with another sidebar if you like -->\n <div\n use:clickOutside\n on:click_outside={menu? handleClickOutside : ''}\n class:absolute={menu}\n class:mt-11={menu}\n class=\"md:flex-1 md:flex md:flex-col md:min-h-0 bg-gray-800\"\n >\n...\n```\n\n```text\n// @ts-nocheck\n/** Dispatch event on click outside of element */\n// @ts-ignore\n\nexport function clickOutside(element) {\n // @ts-ignore\n\n const handleClick = (event) => {\n console.log(event.target, document.body)\n \n // element exist?, element contain where i did click, preventDefault = false?\n if (element && !element.contains(event.target) && !event.defaultPrevented) {\n element.dispatchEvent(\n // Dispatch and create new custom event.\n new CustomEvent('click_outside', element)\n );\n }\n };\n // add eventlistener when you click on document\n document.addEventListener('click', handleClick, true);\n\n return {\n destroy() {\n document.removeEventListener('click', handleClick, true);\n }\n };\n}\n```\n\n```text\nsvelteKit\n```\n\n```text\nhandleClickOutside\n```\n\n```text\nclickOutside.js\n```\n\n```text\nelement.contains\n```\n\n```text\ntailwindUI\n```\n\n```text\ntailwindCSS\n```\n\n```text\nSvelteKit\n```\n\n```text\nfunction handleNav() {\n if (menu) return;\n menu = !menu;\n}\n```\n\n```html\n<button\n id=\"menu-button\"\n type=\"button\"\n value=\"button\"\n class=\"-ml-0.5 -mt-0.5 h-12 w-12 inline-flex items-center justify-center rounded-md text-gray-500 hover:text-gray-900 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-indigo-500\"\n on:click={handleNav}\n >...</button>\n```\n\n```html\n<div\n use:clickOutside={{ignore: 'menu-button'}}\n on:click_outside={menu? handleClickOutside : ''}\n class:absolute={menu}\n class:mt-11={menu}\n class=\"md:flex-1 md:flex md:flex-col md:min-h-0 bg-gray-800\"\n >\n <div class=\"h-40 w-40 bg-slate-600 p-3 text-white\">\n Some menu content here\n </div>\n</div>\n```\n\n```text\nconst handleClick = (event) => {\n event.preventDefault();\n \n // This function kinda rearranged with early returns to take the new parameter into account.\n if (!element) return;\n if (element.contains(event.target)) return;\n \n //Get the element based on the id we gave in the params\n const ignore = document.getElementById(opts.ignore)\n //Check that we're not clicking in the button.\n if (ignore.contains(event.target)) return;\n \n element.dispatchEvent(\n // Dispatch and create new custom event.\n new CustomEvent('click_outside', element)\n );\n};\n```\n\n```text\non:click_outside={menu? handleClickOutside : ''}\n```\n\n```text\nhandleClick\n```\n\n```text\nuse:clickOutside\n```\n\n```text\nexport function clickOutside(node: HTMLElement, opts?: string) {\n function detect({ target }: MouseEvent) {\n if (opts !== undefined) {\n const ignore = document.getElementById(opts);\n if (ignore?.contains(target as Node)) return;\n\n if (!node.contains(target as Node)) {\n node.dispatchEvent(new CustomEvent('clickoutside'));\n }\n } else {\n if (!node.contains(target as Node)) {\n node.dispatchEvent(new CustomEvent('clickoutside'));\n }\n }\n }\n document.addEventListener('click', detect, { passive: true, capture: true });\n return {\n destroy() {\n document.removeEventListener('click', detect);\n }\n };\n}\n```\n\n```text\ndeclare namespace svelteHTML {\n interface HTMLAttributes<T> {\n 'on:clickoutside'?: (event: CustomEvent) => void;\n }\n }\n```\n\n```text\n<svelte:head>\n <link href=\"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\" rel=\"stylesheet\">\n</svelte:head>\n\n<script>\n import { clickOutside } from './click_outside';\n\n let menu = false;\n</script>\n\n<button\n id=\"menu-button\"\n type=\"button\"\n value=\"button\"\n class=\"p-2\"\n on:click={()=> {menu = !menu}}\n >Click!</button>\n\n<div\n use:clickOutside={'menu-button'}\n on:click_outside={()=> {menu = false}}\n \n class={`${menu ? 'block' : 'hidden'} absolute bg-blue-500 top-16 left-0 bg-slate-100 p-2`} \n >\n <div>\n Some menu content here\n </div>\n</div>\n```\n\n========================================\n\nComments:\n- Thanks! I've already tried adding options by putting a conditional in clickOutside.js that compares to the event.target,is that what you mean?. The problem is that it always, the event.target, takes the element in which the action is implemented. In this case, always takes the 'div button menu'. So i can't take button like a exception.\n- If you could create your scenario with a repl, I can see if I can show you how to fix it (svelte.dev/repl)\n- I created this REPL. You have to look at mobile version. Thanks! svelte.dev/repl/3c1e7112967743039850de7081a8ee20?version=3.4‌​8.0\n- I've updated the original answer. As a friendly suggestion, in the future please minimize your REPL to only the necessary stuff. It's generally easier for strangers to help you if they don't have to sort through a lot of unnecessary code.\n- @Coo, your Repl is returning a 404. Would it be possible for you to see what going on, please? Would love to see your implementation there 🙏\n- @ItzaMi REPL has been remade. Not sure what happened to the old one, but this one should work.","metadata":{"transformedAt":"2026-08-18T18:33:40.703Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":390,"estimatedTokens":2272}}584{"id":"stack-76025963","source":"stackoverflow","questionId":76025963,"title":"SvelteKit keeping page data between pages","tags":["javascript","svelte","sveltekit"],"text":"Title: SvelteKit keeping page data between pages\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nIs it possible to do the following:\n\nGiven a route such as `/foo/[slug]` with `+page.js` in it to load some data based on the slug, can the data be kept when navigating to `/foo/[slug]/bar` and available in the `+page.svelte`? The context of this is that there is some file being loaded to render on `/foo/[slug]` and that same file is used on `/foo/[slug]/bar`, so having the file preloaded is ideal. This approach would also require the file being loaded if `/foo/[slug]/bar` is visited first. I believe that load functions perform dependency checking. Reading through the docs, especially under the section about running the parent load function, it seems like this should be possible, but I can't quite figure it out.\n\nSome approaches that would work are to use stores, or to use the layouts option, but is there a simpler approach?\n\nI've tried getting the page data on the nested page directly, but it results in an empty object instead of the content from the `/foo/[slug]` page, which suggests that the data is not being loaded properly.\n\n========================================\n\nCode:\n```text\n/foo/[slug]\n```\n\n```text\n+page.js\n```\n\n```text\n/foo/[slug]/bar\n```\n\n```text\n+page.svelte\n```\n\n```text\n/foo/[slug]\n```\n\n```text\n/foo/[slug]/bar\n```\n\n```text\n/foo/[slug]/bar\n```\n\n```text\n/foo/[slug]\n```\n\n```text\n+layout.ts\n```\n\n```text\n/foo/[slug]\n```\n\n```text\n/foo/[slug]/+layout.server.js\n```\n\n```text\n/foo/[slug]/+page.svelte\n```\n\n```text\n/foo/[slug]/bar/+page.svelte\n```\n\n```text\nfoo\n```\n\n```text\nbar\n```\n\n```text\nexport let data\n```\n\n```text\nload\n```\n\n========================================\n\nComments:\n- you should use a +layout at the slug level for all data that should be shared for pages below it\n- @pilchard so using `+layout.ts` at `/foo/[slug]` will have shared data in `/foo/slug/bar` ? The load function wont be run again?","metadata":{"transformedAt":"2026-08-18T18:33:40.703Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":89,"estimatedTokens":495}}585{"id":"stack-60214307","source":"stackoverflow","questionId":60214307,"title":"Retrieving JSON data in Svelte","tags":["javascript","json","svelte"],"text":"Title: Retrieving JSON data in Svelte\nTags: javascript, json, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm having a bit of a blank at the moment. \n\nI'm trying to retrieve some JSON data via the Youtube API.\n\nThe error I receive is \"Cannot read property 'getJSON' of undefined\". I've dropped my code below.\n\n```\n\n export let videoData = {};\n const { HEADING, HEADING2, SERVICE_LIST } = videoData;\n\n import { onMount } from \"svelte\";\n var key = 'my api key';\n var url = 'https://www.googleapis.com/youtube/v3/channels';\n var channelid = 'my channel id';\n\n var options = {\n part: 'snippet',\n key: key,\n id: channelid,\n maxresults: 20\n\n };\n loadvids();\n function loadvids(){\n this.getJSON(url, options, function(data){\n\n console.log(data);\n });\n }\n\n```\n\nThis is within a .svelte file. Any help would be appreciated.\n\n========================================\n\nCode:\n```text\n<script>\n export let videoData = {};\n const { HEADING, HEADING2, SERVICE_LIST } = videoData;\n\n import { onMount } from \"svelte\";\n var key = 'my api key';\n var url = 'https://www.googleapis.com/youtube/v3/channels';\n var channelid = 'my channel id';\n\n\n var options = {\n part: 'snippet',\n key: key,\n id: channelid,\n maxresults: 20\n\n };\n loadvids();\n function loadvids(){\n this.getJSON(url, options, function(data){\n\n console.log(data);\n });\n }\n\n</script>\n```\n\n```text\nconst url = 'https://www.googleapis.com/youtube/v3/channels';\nlet data = [];\n\n\nonMount(async function() {\n const response = await fetch(url, options);\n data = await response.json();\n });\n```\n\n========================================\n\nComments:\n- Thanks so much :).\n- I'm glad to help.","metadata":{"transformedAt":"2026-08-18T18:33:40.703Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":88,"estimatedTokens":419}}586{"id":"stack-71005226","source":"stackoverflow","questionId":71005226,"title":"Flaky cypress test with Svelte: Button is sometimes clicked, sometimes not","tags":["cypress","svelte","svelte-3","sveltekit"],"text":"Title: Flaky cypress test with Svelte: Button is sometimes clicked, sometimes not\nTags: cypress, svelte, svelte-3, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am testing my SvelteKit site with Cypress. I sometimes experience flaky tests, similar to what has been described here: https://www.cypress.io/blog/2019/01/22/when-can-the-test-click/. In short, Cypress sometimes finds and clicks a button before the event listeners are attached - as a result, the click goes nowhere. The proposed solution is to simply re-try clicking until the appropriate listeners have been attached. That works in my case as well. However, though I do understand why this can be an issue in the example given in the blog post (it's a large calendar modal), I find it hard to justify that this issue arises when using a simple Svelte button.\n\nHere is a simple example of a button that reveals some content when clicked:\n\n```\n\n let hide = true;\n\n {\n console.log('clicked');\n hide = false;\n }}>\n Show\n\nContent\n\n .hide {\n visibility: hidden;\n }\n\n```\n\nThe corresponding test sometimes passes, sometimes fails:\n\n```\nit('reveals content on click', () => {\n cy.contains('Show').click();\n cy.contains('Content').should('be.visible');\n});\n```\n\nAgain, I am aware this can be fixed by re-trying to click the button. And if this is what it takes to make Cypress work with Svelte/SvelteKit, then that's fine with me. But I am wondering: Why would this even be an issue?\n\nMinimal reproduction repo: https://github.com/sophiamersmann/test-svelte-kit-cypress\n\n========================================\n\nTop Answer:\nI think the problem lies with Vite, which uses ES modules to load the page and it's components.\n\nAdding an intercept before the cy.visit() seems to give consistent results.\n(Note the URL to intercept may vary, you can get it from the last entry in devtools Network).\n\n```\nbeforeEach(() => {\n cy.intercept('index.svelte?svelte&type=style&lang.css').as('svelte')\n cy.visit('/');\n cy.wait('@svelte')\n});\n```\n\nUsing cypress-grep to burn-test\n\n```\nnpx cypress run --env burn=100\n```\n\n### With intercept\n\n \nhttps://i.sstatic.net/QX3Tt.png\n\n### Without intercept\n\n \nhttps://i.sstatic.net/Y8ZxL.png\n\n### Why is it not hydration?\n\nIf you create an equivalent Svelte app with `hydratable` set to `true`, it will pass the burn test - IMO because it uses `rollup` instead of `vite` to deliver the app to the browser.\n\nhttps://i.sstatic.net/hNbkM.png\n\n========================================\n\nCode:\n```html\n<script>\n let hide = true;\n</script>\n\n<button\n on:click={() => {\n console.log('clicked');\n hide = false;\n }}>\n Show\n</button>\n\n<span class:hide>Content</span>\n\n<style>\n .hide {\n visibility: hidden;\n }\n</style>\n```\n\n```js\nit('reveals content on click', () => {\n cy.contains('Show').click();\n cy.contains('Content').should('be.visible');\n});\n```\n\n```js\nbeforeEach(() => {\n cy.intercept('index.svelte?svelte&type=style&lang.css').as('svelte')\n cy.visit('/');\n cy.wait('@svelte')\n});\n```\n\n```js\nnpx cypress run --env burn=100\n```\n\n```text\nhydratable\n```\n\n```text\ntrue\n```\n\n```text\nrollup\n```\n\n```text\nvite\n```\n\n```text\n<script>\n import { onMount } from 'svelte'; // <- Here\n\n let init = false;\n onMount(() => {\n init = true;\n });\n\n let hide = true;\n</script>\n\n<button\n data-init={init}\n on:click={() => {\n console.log('clicked');\n hide = false;\n }}>\n Show\n</button>\n\n<span class:hide>Content</span>\n\n<style>\n .hide {\n visibility: hidden;\n }\n</style>\n```\n\n```text\nit('reveals content on click', () => {\n cy.get('[data-init=true]').should('exist'); // <- Here\n cy.contains('Show').click();\n cy.contains('Content').should('be.visible');\n});\n```\n\n========================================\n\nComments:\n- I can't reproduce - repl'd your code and added your test. Two questions - where is your `cy.visit()` and how do you use sveltekit (repl only include svelte)\n- Here is a GitHub repo that reproduces the problem: github.com/sophiamersmann/test-svelte-kit-cypress This is a simple SvelteKit + Cypress setup. Re-run the test and it will eventually fail. I've also tried the same with Svelte (not SvelteKit) and could not reproduce the behaviour.\n- Another option is https://github.com/bahmutov/cypress-svelte-unit-test. It uses rollup, so you won't get loading issues.\n- But why does it not happen with Svelte?\n- I added more details to the answer\n- Ohh, it makes sense that this is related to hydration. Thank you for taking the time to give such a detailed response. Cheers!\n- This makes no sense - why would a simple click handler be hydrated?\n- Agreed, there's nothing to substantiate this, it's pure supposition and contrary to my tests.\n- Thanks for the additional info, but it doesn't really help. \"Svelte constructs HTML inside the browser\" - why does the test find the button but not it's click handler?\n- Hydration = Svelte takes over the rendered HTML. As long as that didn't happen yet, there's no event handler attached to the button. Event handler = Javascript = part of the hydration process.\n- But how would one work around this issue? How to ensure that hydration has passed before executing any specs?\n- @dummidum - that's not how hydration works.\n- It's hydration. The interception works because this makes Cypress wait longer before executing the test. You could intercept similar requests for Vite.\n- No, Svelte with hydration passes the burn test (see above).\n- Point is, to make the test work you have to wait anyway, if it's by the method given by @SophiaMersmann or by intercepting the ESM fetch. The only difference is the amount of code you need to write to do so.\n- Adding \"hydratable: true\" to your compiler options changes nothing, because you still start from an empty page. You need the server to render the full HTML and send that to the browser to take advantage of the hydratable option. The rollup template doesn't do this.\n- No, your \"empty page\" theory is not correct because the test immediately finds the button but not it's click handler.","metadata":{"transformedAt":"2026-08-18T18:33:40.703Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":196,"estimatedTokens":1498}}587{"id":"stack-73125324","source":"stackoverflow","questionId":73125324,"title":"Simple way to hide and show element with svelte","tags":["javascript","web","frameworks","svelte","astrojs"],"text":"Title: Simple way to hide and show element with svelte\nTags: javascript, web, frameworks, svelte, astrojs\nSource: Stack Overflow\n\nQuestion:\nI want to have a simple with way to hide and show an element with a button on svelte, how can I do it? Also is it simpler to do it in vanilla JS?\n\n========================================\n\nTop Answer:\nSvelte has the `{#if}` directive for that, which can be tied to local state, which in turn can be changed via a button's `on:click`.\n\nWhether it is easier in vanilla JS depends on many things, including the overall complexity. In the long run, things tend to be easier with Svelte.\n\nI would recommend doing the tutorial...\n\n========================================\n\nCode:\n```text\n<script>\n let visible = true;\n\n function toggleVissible() {\n visible = !visible\n }\n</script>\n\n<button on:click={toggleVissible}>\n Hide\n</button>\n\n{#if visible}\n <p>\n This text will hide.\n </p>\n{/if}\n```\n\n```text\n{#if}\n```\n\n```text\non:click\n```\n\n```html\n<button>Toggle</button>\n\n<p>Content</p>\n\n<script>\n document.querySelector('button').onclick = () => {\n const el = document.querySelector('p')\n el.style.display = el.style.display === 'none' ? 'block' : 'none'\n }\n</script>\n```\n\n```html\n<script>\n let toggle = true\n</script>\n\n<button on:click={() => (toggle = !toggle)}> Toggle </button>\n\n{#if toggle}\n <p>Content</p>\n{/if}\n```\n\n```astro\n---\nimport Svelte from \"./svelte.svelte\";\n---\n\n<Svelte client:load />\n```\n\n```text\n.astro\n```\n\n```text\nclient:\n```\n\n========================================\n\nComments:\n- One question, what if I have an astro page that contains an svelte component (`Modal.svelte`). This is hidden. How do I show the modal by clicking from the astro page? stackoverflow.com/questions/78330396/…","metadata":{"transformedAt":"2026-08-18T18:33:40.703Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":92,"estimatedTokens":450}}588{"id":"stack-78962048","source":"stackoverflow","questionId":78962048,"title":"With Svelte 5 runes mode, how can I derive properties from a dynamically rendered component","tags":["javascript","svelte","svelte-5"],"text":"Title: With Svelte 5 runes mode, how can I derive properties from a dynamically rendered component\nTags: javascript, svelte, svelte-5\nSource: Stack Overflow\n\nQuestion:\n### The goal:\n\nThe end goal is to simply get TabItem's title and icon to update based on the (in this example) Dashboard.svelte's title and icon from within itself, rather than the state for these properties being managed within TabItem, this makes each display component like Dashboard responsible for it's own information which makes sense to me. Here is the code I currently have:\n\n### TabsContainer.svelte\n\nNote that this is just the snippet that really matters from here:\n\n```\n\n \n {#each tabItems as tabItem, i}\n onTabSelected(i)}\n onClose={() => onTabClose(i)}\n />\n {/each}\n \n\n \n \n {#each tabItems as tabItem, i}\n \n \n \n {/each}\n \n\n```\n\n### TabItem.svelte\n\nThis holds the component and the instance of it that was created, I think this is the bit I am miss understanding the most. Whether I put the instance in to an $effect or use $derived, instance appears null the first run through, and then it updates to a Proxy object (which is good I think...) but still it doesn't seem to have access to the title or icon properties:\n\n```\n\n import { onMount } from \"svelte\";\n\n let {\n component,\n instance = null,\n active = false,\n onSelected = () => {},\n onClose = () => {}\n } = $props();\n\n let title = $state(\"None\");\n let icon = $state(\"fa fa-question\");\n\n $effect(() => {\n console.log(instance);\n if (instance) {\n title = instance.title;\n icon = instance.icon;\n }\n });\n\n \n \n {title}\n \n \n x\n \n\n```\n\n### Dashboard.svelte\n\nThis is a simple example of what a tab item should be.\n\n```\n\n import { onMount } from \"svelte\";\n\n let {\n title = \"Dashboard\",\n icon = \"fa fa-home\"\n } = $props();\n\n \n **\n {title}\n \n\n```\n\nNote that I'm very aware I'm not using TS, I am just trying to understand Svelte 5's way of handling this kind of thing. Also note that I have achieved this with Svelte 4 but after trying literally 20-30 different ways of doing this I can't get it to work atall so you're seeing v31 of my attempts to get this to work so I apologise in advance if I'm barking up the completely wrong tree 😂 I've been going around in circles for 3 days now.\n\nAny help is greatly appreciated but as I say, I would really like the Dashboard component here to be responsible for it's own information such as title and icon, I do not want the TabItem to have to maintain a seperate state for it, if that makes sense.\n\nThanks In advance for any help atall!😀\n\n========================================\n\nCode:\n```text\n<div class=\"outer-tab-container\">\n <div class=\"tab-items-container\">\n {#each tabItems as tabItem, i}\n <TabItem\n active={activeTabIndex === i}\n component={tabItem.component}\n instance={tabItem.instance}\n onSelected={() => onTabSelected(i)}\n onClose={() => onTabClose(i)}\n />\n {/each}\n </div>\n\n <div class=\"tab-content-container\">\n <!-- Render all components, but only show the active one based on index comparison -->\n {#each tabItems as tabItem, i}\n <div style=\"display: {activeTabIndex === i ? 'block' : 'none'};\">\n <tabItem.component this={tabItem.component} bind:this={tabItem.instance} />\n </div>\n {/each}\n </div>\n</div>\n```\n\n```text\n<script>\n import { onMount } from \"svelte\";\n\n let {\n component,\n instance = null,\n active = false,\n onSelected = () => {},\n onClose = () => {}\n } = $props();\n\n let title = $state(\"None\");\n let icon = $state(\"fa fa-question\");\n\n $effect(() => {\n console.log(instance);\n if (instance) {\n title = instance.title;\n icon = instance.icon;\n }\n });\n</script>\n\n<button class=\"tab-item\" class:active={active} onclick={onSelected} role=\"tab\" aria-selected={active}>\n <!-- <i class={icon}></i> -->\n <span>\n {title}\n </span>\n <div class=\"close\" onclick={onClose} title=\"Close tab\" tabindex=\"0\" role=\"button\" aria-label=\"Close tab\" aria-hidden=\"true\" aria-controls=\"tab-content\" aria-describedby=\"tab-content\">\n x\n </div>\n</button>\n```\n\n```text\n<script>\n import { onMount } from \"svelte\";\n\n let {\n title = \"Dashboard\",\n icon = \"fa fa-home\"\n } = $props();\n</script>\n\n<div>\n <h1>\n <i class={icon}></i>\n {title}\n </h1>\n</div>\n```\n\n```text\n<div class=\"outer-tab-container\">\n <div class=\"tab-items-container\">\n {#each tabItems as tabItem, i}\n <TabItem\n active={activeTabIndex === i}\n instance={tabItem.instance}\n onSelected={() => onTabSelected(i)}\n onClose={() => onTabClose(i)}\n />\n {/each}\n </div>\n\n <div class=\"tab-content-container\">\n <!-- Render all components, but only show the active one based on index -->\n {#each tabItems as tabItem, i}\n <TabContentContainer show={activeTabIndex === i}>\n <tabItem.component bind:this={tabItem.instance} />\n </TabContentContainer>\n {/each}\n </div>\n</div>\n```\n\n```text\n<script>\n import { onMount } from \"svelte\";\n\n let {\n instance = null,\n active = false,\n onSelected = () => {},\n onClose = () => {}\n } = $props();\n\n let instanceState = $derived(instance?.state ?? {\n title: \"No Title\",\n icon: \"fa fa-question\"\n });\n</script>\n\n<button class=\"tab-item\" class:active={active} onclick={onSelected} role=\"tab\" aria-selected={active}>\n <i class={instanceState.icon}></i>\n <span>\n {instanceState.title}\n </span>\n <div class=\"close\" onclick={onClose} title=\"Close tab\" tabindex=\"0\" role=\"button\" aria-label=\"Close tab\" aria-hidden=\"true\" aria-controls=\"tab-content\" aria-describedby=\"tab-content\">\n x\n </div>\n</button>\n```\n\n```text\n<script>\n import { onMount } from \"svelte\";\n\n export const state = $state({\n title: \"Dashboard\",\n icon: \"fa fa-home\"\n });\n\n onMount(() => {\n setTimeout(() => { state.title = \"Dashboard (Updated)\"; }, 1500);\n });\n</script>\n\n<div>\n <h1>\n <i class={state.icon}></i>\n {state.title}\n </h1>\n</div>\n```\n\n========================================\n\nComments:\n- Is the `Dashboard` only going to be used as a tab? If so, have you looked at coupling it more tightly via a shared Svelte context? Also, if the components only ever have one instance, the tab data could be moved to the `module` script which makes it more easily accessible.\n- Thanks, I'll look into what \"Svelte context\" is as I'm not sure sorry. In answer to your second point, nope there are going to be tabs which are the same \"definition\" but must hold their own state. Imagine a excel / spreadsheet document where you have multiple \"tabs\" with their own dataset. It's that kind of thing\n- Context: Docs - Tutorial. It's obvious that there would be multiple tabs, just not that there would be multiple \"Dashboard\" tabs.\n- Thanks that seems to make sense. And using the documentation I can see how to set and get the context, but I still have the same problem that it's not being reactive, it doesn't seem to update the title or icon whenever the instance context updates.\n- For reactive contexts, you need to pass stores through them.\n- Hmm yeah sorry I tried that too but still no luck, the main problem seems to be that within TabsContainer.svelte, this line is not simply updating the instance property within TabItem.svelte: Would you mind double checking the way I've done this between these two files and let me know if I've made an obvious mistake?","metadata":{"transformedAt":"2026-08-18T18:33:40.703Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":261,"estimatedTokens":1932}}589{"id":"stack-60956689","source":"stackoverflow","questionId":60956689,"title":"How do I re-render a component on variable change that determines state using a function?","tags":["svelte"],"text":"Title: How do I re-render a component on variable change that determines state using a function?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI have a component that maintains a selection as an array and a child component that determines its state by seeing if it is included in that array. When I change the array, the child component does not re-render. How do I fix this?\n\nREPL: https://svelte.dev/repl/f2074ef75dee444faaee005b8b7cf9b9\n\nApp.svelte\n\n```\n\n import Nested from \"./Nested.svelte\";\n\n let selection = [];\n\n function isSelected(n) {\n return selection.indexOf(n) > -1;\n }\n\n function click(e) {\n const n = e.detail.number;\n if (isSelected(n)) {\n selection = selection.filter(x => x != n);\n } else {\n selection = [...selection, n];\n }\n console.log(\"Selection is\", selection);\n }\n\n{#each [1, 2, 3] as number}\n \n{/each}\n```\n\nNested.svelte\n\n```\n\n export let selected, number;\n import { createEventDispatcher } from \"svelte\";\n\n const dispatch = createEventDispatcher();\n\n function click() {\n dispatch(\"click\", {\n number\n });\n }\n\n .selected {\n color: red;\n }\n\n {number}\n\n```\n\n========================================\n\nCode:\n```text\n<script>\n import Nested from \"./Nested.svelte\";\n\n let selection = [];\n\n function isSelected(n) {\n return selection.indexOf(n) > -1;\n }\n\n function click(e) {\n const n = e.detail.number;\n if (isSelected(n)) {\n selection = selection.filter(x => x != n);\n } else {\n selection = [...selection, n];\n }\n console.log(\"Selection is\", selection);\n }\n</script>\n\n{#each [1, 2, 3] as number}\n <Nested\n {number}\n selected={isSelected(number)}\n on:click={click} />\n{/each}\n```\n\n```text\n<script>\n export let selected, number;\n import { createEventDispatcher } from \"svelte\";\n\n const dispatch = createEventDispatcher();\n\n function click() {\n dispatch(\"click\", {\n number\n });\n }\n\n</script>\n\n<style>\n .selected {\n color: red;\n }\n</style>\n\n<div class:selected={selected} on:click={click}>\n {number}\n</div>\n```\n\n```html\nselected={isSelected(number)}\n```\n\n```js\nisSelected(number)\n```\n\n```html\nselected={selection.indexOf(number) > -1}\n```\n\n```html\nselected={selection, isSelected(number)}\n```\n\n```text\nisSelected\n```\n\n```text\nnumber\n```\n\n```text\nselection\n```\n\n```text\nselection\n```\n\n```text\nx, y\n```\n\n```text\n'a', 'b', 'c'\n```\n\n```text\nselection\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.703Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":160,"estimatedTokens":617}}590{"id":"stack-73531099","source":"stackoverflow","questionId":73531099,"title":"Sveltekit [...slug] dynamic routing returns 404 error after deployment","tags":["svelte","firebase-hosting","sveltekit","svelte-component"],"text":"Title: Sveltekit [...slug] dynamic routing returns 404 error after deployment\nTags: svelte, firebase-hosting, sveltekit, svelte-component\nSource: Stack Overflow\n\nQuestion:\nam developing Svelte application with dynamic routes, everything working fine in localhost for both development and production build. After deploying build using firebase, except base routes all other routes returning 404 error.\n\nHere I have attached my code structure\n\nhttps://i.sstatic.net/Yvids.png\n\nSvelte config JS file\n\n```\nimport adapter from '@sveltejs/adapter-static';\nimport preprocess from 'svelte-preprocess';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: [\n preprocess({\n postcss: true,\n preserve: ['ld+json'],\n }),\n ],\n\n kit: {\n adapter: adapter({\n pages: 'public',\n assets: 'public',\n fallback: null,\n precompress: false\n }),\n prerender: {\n default: true\n }\n }\n};\n\nexport default config;\n```\n\nBase route Link\n\nRoute with dynamic path after click All the dynamic paths are working while we are clicking item from base route when Javascript enabled. If we are reloading the page or when we are hitting this url directly it's not working.\n\nNotes : In localhost am not facing any issue in both production and development build.\n\n========================================\n\nCode:\n```text\nimport adapter from '@sveltejs/adapter-static';\nimport preprocess from 'svelte-preprocess';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: [\n preprocess({\n postcss: true,\n preserve: ['ld+json'],\n }),\n ],\n\n kit: {\n adapter: adapter({\n pages: 'public',\n assets: 'public',\n fallback: null,\n precompress: false\n }),\n prerender: {\n default: true\n }\n }\n};\n\nexport default config;\n```\n\n```text\n\"hosting\": {\n // ...\n\n \"appAssociation\": \"AUTO\", // required for Dynamic Links (default is AUTO if not specified)\n\n // Add the \"rewrites\" attribute within \"hosting\"\n \"rewrites\": [ {\n \"source\": \"/**\", // the Dynamic Links start with \"https://CUSTOM_DOMAIN/\"\n \"dynamicLinks\": true\n } ]\n}\n```\n\n```text\n\"hosting\": {\n\n // We should add \"cleanUrls\" attribute within \"hosting\"\n \"cleanUrls\": true\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.703Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":105,"estimatedTokens":620}}591{"id":"stack-69051857","source":"stackoverflow","questionId":69051857,"title":"Svelte - ReferenceError: buffer is not defined","tags":["webrtc","svelte"],"text":"Title: Svelte - ReferenceError: buffer is not defined\nTags: webrtc, svelte\nSource: Stack Overflow\n\nQuestion:\nTrying to setup a WebRtc connection in my new Svelte app, and am hitting this error whenever I try to import a library.\n\nReferenceError: buffer is not defined\n\n**Example Code:** https://github.com/nickgrealy/svelte-webrtc (link also below)\n\nHere are the steps to reproduce: install the library, then import it on a `*.svelte` component.\n\ne.g. peerjs\n\n```\nnpm i peerjs\nimport Peer from \"peerjs\";\n```\n\nalso occurs for this library - simple-peer\n\n```\nnpm i simple-peer\nimport Peer from \"simple-peer\";\n```\n\nBoth give the following error:\n\n```\nUncaught ReferenceError: buffer is not defined\n at main.ts:14\n```\n\nNot really sure what to try next... writing vanilla Javascript? Try other libraries?\n\nI don't know how to configure rollup... (hoping it's something simple that one of you have come across before!).\n\nN.B. not sure if relevant, I converted the Svelte project to Typescript (using the inbuilt script).\n\n### ** Added code to reproduce **\n\nhttps://github.com/nickgrealy/svelte-webrtc/blob/main/src/main.ts#L2\n\nConsole logs from `yarn dev`\n\n```\nyarn run v1.22.10\n$ rollup -c -w\nrollup v2.56.3\nbundles src/main.ts → public/build/bundle.js...\n(!) Missing shims for Node.js built-ins\nCreating a browser bundle that depends on \"buffer\" and \"events\". You might need to include https://github.com/snowpackjs/rollup-plugin-polyfill-node\nLiveReload enabled\n(!) Plugin node-resolve: preferring built-in module 'buffer' over local alternative at '/Users/userx/svelte-webrtc/node_modules/buffer/index.js', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning\n(!) Circular dependencies\nnode_modules/readable-stream/lib/_stream_readable.js -> node_modules/readable-stream/lib/_stream_duplex.js -> node_modules/readable-stream/lib/_stream_readable.js\nnode_modules/readable-stream/lib/_stream_duplex.js -> node_modules/readable-stream/lib/_stream_writable.js -> node_modules/readable-stream/lib/_stream_duplex.js\nnode_modules/readable-stream/lib/_stream_duplex.js -> node_modules/readable-stream/lib/_stream_writable.js -> /Users/userx/svelte-webrtc/node_modules/readable-stream/lib/_stream_duplex.js?commonjs-proxy -> node_modules/readable-stream/lib/_stream_duplex.js\nnode_modules/readable-stream/lib/_stream_readable.js -> node_modules/readable-stream/lib/_stream_duplex.js -> /Users/userx/svelte-webrtc/node_modules/readable-stream/lib/_stream_readable.js?commonjs-proxy -> node_modules/readable-stream/lib/_stream_readable.js\n(!) Missing global variable names\nUse output.globals to specify browser global variable names corresponding to external modules\nbuffer (guessing 'buffer')\nevents (guessing 'require$$0$1')\ncreated public/build/bundle.js in 2.9s\n\n[2021-09-05 00:31:10] waiting for changes...\n\n> svelte-app@1.0.0 start\n> sirv public --no-clear \"--dev\"\n\n Your application is ready~! 🚀\n\n - Local: http://localhost:5000\n - Network: Add `--host` to expose\n\n────────────────── LOGS ──────────────────\n\n [00:31:18] 200 ─ 5.50ms ─ /\n [00:31:18] 200 ─ 0.60ms ─ /global.css\n [00:31:18] 200 ─ 0.71ms ─ /build/bundle.css\n [00:31:18] 200 ─ 1.35ms ─ /build/bundle.js\n [00:31:22] 200 ─ 0.76ms ─ /global.css\n [00:31:22] 200 ─ 1.83ms ─ /build/bundle.css\n [00:31:22] 200 ─ 3.96ms ─ /build/bundle.js.map\n```\n\n### ** Update **\n\nAdded the node plugin, now getting this error...\n\nUncaught ReferenceError: require$$1$1 is not defined\n\n... with these logs.\n\n```\nyarn run v1.22.4\n$ rollup -c -w\nrollup v2.56.3\nbundles src/main.ts → public/build/bundle.js...\n(!) Missing shims for Node.js built-ins\nCreating a browser bundle that depends on \"buffer\". You might need to include https://github.com/snowpackjs/rollup-plugin-polyfill-node\nLiveReload enabled\n(!) Circular dependency\npolyfill-node.global.js -> polyfill-node.global.js\n(!) Missing global variable name\nUse output.globals to specify browser global variable names corresponding to external modules\nbuffer (guessing 'require$$1$1')\ncreated public/build/bundle.js in 2.6s\n\n[2021-09-05 00:57:04] waiting for changes...\nnpm WARN lifecycle The node binary used for scripts is /var/folders/05/qnr367194ss7ktgg_c2r57440000gp/T/yarn--1630767421122-0.4620373266212361/node but npm is using /Users/userx/.nvm/versions/node/v14.17.3/bin/node itself. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.\n\n> svelte-app@1.0.0 start /Users/userx/svelte-webrtc\n> sirv public --no-clear \"--dev\"\n\n Your application is ready~! 🚀\n```\n\n========================================\n\nCode:\n```text\nnpm i peerjs\nimport Peer from \"peerjs\";\n```\n\n```text\nnpm i simple-peer\nimport Peer from \"simple-peer\";\n```\n\n```text\nUncaught ReferenceError: buffer is not defined\n at main.ts:14\n```\n\n```text\nyarn run v1.22.10\n$ rollup -c -w\nrollup v2.56.3\nbundles src/main.ts → public/build/bundle.js...\n(!) Missing shims for Node.js built-ins\nCreating a browser bundle that depends on \"buffer\" and \"events\". You might need to include https://github.com/snowpackjs/rollup-plugin-polyfill-node\nLiveReload enabled\n(!) Plugin node-resolve: preferring built-in module 'buffer' over local alternative at '/Users/userx/svelte-webrtc/node_modules/buffer/index.js', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning\n(!) Circular dependencies\nnode_modules/readable-stream/lib/_stream_readable.js -> node_modules/readable-stream/lib/_stream_duplex.js -> node_modules/readable-stream/lib/_stream_readable.js\nnode_modules/readable-stream/lib/_stream_duplex.js -> node_modules/readable-stream/lib/_stream_writable.js -> node_modules/readable-stream/lib/_stream_duplex.js\nnode_modules/readable-stream/lib/_stream_duplex.js -> node_modules/readable-stream/lib/_stream_writable.js -> /Users/userx/svelte-webrtc/node_modules/readable-stream/lib/_stream_duplex.js?commonjs-proxy -> node_modules/readable-stream/lib/_stream_duplex.js\nnode_modules/readable-stream/lib/_stream_readable.js -> node_modules/readable-stream/lib/_stream_duplex.js -> /Users/userx/svelte-webrtc/node_modules/readable-stream/lib/_stream_readable.js?commonjs-proxy -> node_modules/readable-stream/lib/_stream_readable.js\n(!) Missing global variable names\nUse output.globals to specify browser global variable names corresponding to external modules\nbuffer (guessing 'buffer')\nevents (guessing 'require$$0$1')\ncreated public/build/bundle.js in 2.9s\n\n[2021-09-05 00:31:10] waiting for changes...\n\n> svelte-app@1.0.0 start\n> sirv public --no-clear \"--dev\"\n\n\n Your application is ready~! 🚀\n\n - Local: http://localhost:5000\n - Network: Add `--host` to expose\n\n────────────────── LOGS ──────────────────\n\n [00:31:18] 200 ─ 5.50ms ─ /\n [00:31:18] 200 ─ 0.60ms ─ /global.css\n [00:31:18] 200 ─ 0.71ms ─ /build/bundle.css\n [00:31:18] 200 ─ 1.35ms ─ /build/bundle.js\n [00:31:22] 200 ─ 0.76ms ─ /global.css\n [00:31:22] 200 ─ 1.83ms ─ /build/bundle.css\n [00:31:22] 200 ─ 3.96ms ─ /build/bundle.js.map\n```\n\n```text\nyarn run v1.22.4\n$ rollup -c -w\nrollup v2.56.3\nbundles src/main.ts → public/build/bundle.js...\n(!) Missing shims for Node.js built-ins\nCreating a browser bundle that depends on \"buffer\". You might need to include https://github.com/snowpackjs/rollup-plugin-polyfill-node\nLiveReload enabled\n(!) Circular dependency\npolyfill-node.global.js -> polyfill-node.global.js\n(!) Missing global variable name\nUse output.globals to specify browser global variable names corresponding to external modules\nbuffer (guessing 'require$$1$1')\ncreated public/build/bundle.js in 2.6s\n\n[2021-09-05 00:57:04] waiting for changes...\nnpm WARN lifecycle The node binary used for scripts is /var/folders/05/qnr367194ss7ktgg_c2r57440000gp/T/yarn--1630767421122-0.4620373266212361/node but npm is using /Users/userx/.nvm/versions/node/v14.17.3/bin/node itself. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.\n\n> svelte-app@1.0.0 start /Users/userx/svelte-webrtc\n> sirv public --no-clear \"--dev\"\n\n\n Your application is ready~! 🚀\n```\n\n```text\n*.svelte\n```\n\n```text\nyarn dev\n```\n\n```text\npeerjs\n```\n\n```text\nbrowserify\n```\n\n```text\nformat\n```\n\n```text\ncjs\n```\n\n```text\nrollup.config.js\n```\n\n```text\niife\n```\n\n```text\nstrict\n```\n\n```text\nrollup.config.js\n```\n\n```text\nstrict: false\n```\n\n========================================\n\nComments:\n- Sharing `main.ts` and full error stack may be helpful\n- Thanks @AllanChain - have added the logs and sample code... will try including rollup-plugin-polyfill-node / `preferBuiltins: false` / setting up globals... but have to work out how do that first.\n- Try install buffer package from npm: npmjs.com/package/buffer\n- @NickGrealy also add you `rollup.config.js` in your question with project structure.\n- Hi @Chandan - it's all in the public project I shared (to reproduce). Please check it out github.com/nickgrealy/svelte-webrtc\n- @NickGrealy setup `browserify` in `rollup.config.js` which is the requirement for `simple-peer` if you are working in browser.\n- I'm not sure how to config rollup for your case. However, for this specific package `simple-peer`, the problem can be solve by using the pre-build dist `import Peer from \"simple-peer/simplepeer.min.js\";`\n- @Chandan - stuck now on `ReferenceError: navigator is not defined` (github.com/nickgrealy/svelte-webrtc/tree/chandan)\n- @NickGrealy reorder these plugins in `rollup.config.js` as nodePolyfills, commonjs then resolve\n- @NickGrealy for `peerjs` there is no need for `browserify`\n- Thanks for the response. Would be good to know why `cjs` works. Also started getting this error \"module is not defined at main.ts:8\" - any idea why?\n- @NickGrealy I am not getting any error should I include `rollup.config.js` and I not sure but the problem maybe because of the libraries are in mixed formats.","metadata":{"transformedAt":"2026-08-18T18:33:40.703Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":263,"estimatedTokens":2467}}592{"id":"stack-57009558","source":"stackoverflow","questionId":57009558,"title":"Cannot read property 'fragment' of undefined","tags":["javascript","parcel","svelte"],"text":"Title: Cannot read property 'fragment' of undefined\nTags: javascript, parcel, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to nest one svelte component in another svelte component.\n\n```\n//index.js\nimport Parent from './Parent.svelte';\n\nnew Parent({\n target: document.querySelector('main')\n})\n\n// Parent.svelte\n\n import Child from \"./Child.svelte\";\n\nparent component\n\n// Child.svelte\nchild component\n\n```\n\nI expect Child.svelte to be nested in Parent.svelte, but I get this error message instead\n\n`Cannot read property 'fragment' of undefined`\n\nby the way: I´m using parcel with parcel-plugin-svelte\n\n========================================\n\nTop Answer:\nI had a similar issue and need to change the way how react is imported\n\n```\nimport { React } from 'react'\n```\n\nneed to change to\n\n```\nimport React from 'react'\n```\n\n========================================\n\nCode:\n```text\n//index.js\nimport Parent from './Parent.svelte';\n\nnew Parent({\n target: document.querySelector('main')\n})\n\n\n// Parent.svelte\n<script>\n import Child from \"./Child.svelte\";\n</script>\n\n<p>parent component</p>\n<Child />\n\n\n// Child.svelte\n<p>child component</p>\n```\n\n```text\nCannot read property 'fragment' of undefined\n```\n\n```sh\nparcel --no-hmr\n```\n\n```text\nparcel-svelte-plugin\n```\n\n```text\nhmr\n```\n\n```text\nimport { React } from 'react'\n```\n\n```text\nimport React from 'react'\n```\n\n========================================\n\nComments:\n- The `` element probably doesn't exist by the time this is called.\n- @Lewis the element exists. it is hard-coded into the index.html file. This will run if I remove the nested child\n- when using REPL on their site your sample works to me. could your reproduce full set up in codesandbox or something similar?\n- Same issue here when I try to add a child component. The issue goes away if I `parcel build` instead of `parcel watch` so I suspect parcel is doing something odd in dev builds\n- Its a confirmed bug: github.com/DeMoorJasper/parcel-plugin-svelte/issues/…\n- and if using other imports, it can be done this way: `import React, { useEffect, useRef, useState } from 'react';`","metadata":{"transformedAt":"2026-08-18T18:33:40.703Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":105,"estimatedTokens":526}}593{"id":"stack-72044263","source":"stackoverflow","questionId":72044263,"title":"Svelte Gantt Chart - Separate via months","tags":["javascript","svelte"],"text":"Title: Svelte Gantt Chart - Separate via months\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to have a gantt chart with all 12 months in it. I'm doing this by setting the `from` & `to` values to `currentDate.clone().endOf('year')` & `currentDate.clone().endOf('year')`. But the gantt chart stopping appearing when setting these values, if I print out the dates they are valid & weirdly if I change the values to `startOf('week')` & `endOf('week`)` it renders the chart fine. Is this possible to do?\n\nPackage I'm using: https://github.com/ANovokmet/svelte-gantt\n\nEdit:\nMy code is based on this index.js file: https://github.com/ANovokmet/svelte-gantt/blob/gh-pages/index.js\n\nIt might be simpler to ask, how can I modify it to show months instead of hours/days?\n\n```\nfunction time(input) {\n return moment(input, \"MMMM DD YYYY\");\n}\n\nconst currentStart = time(responseData.currentDate);\nconst currentEnd = time(responseData.currentDate);\n\ngantt.$set({\n fitWidth: false,\n columnUnit: 'month',\n rowPadding: 6,\n rowHeight: 52,\n columnOffset: 28.8,\n magnetOffset: 15,\n from: currentStart.clone().startOf('year'),\n to: currentStart.clone().endOf('year'),\n minWidth: 800,\n headers: [{ unit: 'month', format: 'MMMM YYYY' }, { unit: 'day', format: 'ddd DD' }]\n});\n```\n\n========================================\n\nCode:\n```text\nfunction time(input) {\n return moment(input, \"MMMM DD YYYY\");\n}\n\nconst currentStart = time(responseData.currentDate);\nconst currentEnd = time(responseData.currentDate);\n\ngantt.$set({\n fitWidth: false,\n columnUnit: 'month',\n rowPadding: 6,\n rowHeight: 52,\n columnOffset: 28.8,\n magnetOffset: 15,\n from: currentStart.clone().startOf('year'),\n to: currentStart.clone().endOf('year'),\n minWidth: 800,\n headers: [{ unit: 'month', format: 'MMMM YYYY' }, { unit: 'day', format: 'ddd DD' }]\n});\n```\n\n```text\nfrom\n```\n\n```text\nto\n```\n\n```text\ncurrentDate.clone().endOf('year')\n```\n\n```text\ncurrentDate.clone().endOf('year')\n```\n\n```text\nstartOf('week')\n```\n\n```text\nendOf('week\n```\n\n```js\nlet options = {\n dateAdapter: new MomentSvelteGanttDateAdapter(moment),\n rows: data.rows,\n tasks: data.tasks,\n timeRanges,\n columnOffset: 15,\n magnetOffset: 15,\n rowHeight: 52,\n rowPadding: 6,\n headers: [{ unit: 'day', format: 'MMMM Do' }, { unit: 'hour', format: 'H:mm' }],\n fitWidth: true,\n minWidth: 800,\n from: currentStart,\n to: currentEnd,\n tableHeaders: [{ title: 'Label', property: 'label', width: 140, type: 'tree' }],\n tableWidth: 240,\n ganttTableModules: [SvelteGanttTable]\n}\n```\n\n```js\nlet options = {\n dateAdapter: new MomentSvelteGanttDateAdapter(moment),\n rows: data.rows,\n tasks: data.tasks,\n columnUnit: 'month',\n columnOffset: 1,\n magnetOffset: 15,\n rowHeight: 52,\n rowPadding: 6,\n headers: [{ unit: 'year', format: 'YYYY' }, { unit: 'month', format: 'MMM' }],\n fitWidth: true,\n minWidth: 800,\n from: currentStart,\n to: currentEnd,\n tableHeaders: [{ title: 'Label', property: 'label', width: 140, type: 'tree' }],\n tableWidth: 240,\n ganttTableModules: [SvelteGanttTable]\n}\n```\n\n```js\nconst currentStart = moment().clone().startOf('year');\nconst currentEnd = moment().clone().endOf('year');\n```\n\n```js\n// start of task (random day (1-20) + month (1-12))\nconst rand_d = (Math.random() * 20) | 0 + 1\nconst rand_m = (Math.random() * 12) | 0 + 1\nconst from = moment(`${rand_d} ${rand_m}`, 'D M')\n// duration of task (random, 5 to 60 days)\nconst rand_l = (Math.random() * 55) | 0 + 5\nconst to = from.clone().add(rand_l, 'days')\ntasks.push({\n type: 'task',\n id: ids[i],\n resourceId: i,\n label: 'Task #' + ids[i],\n from,\n to,\n classes: colors[(Math.random() * colors.length) | 0],\n generation\n});\n```\n\n```text\nGanttOptions\n```\n\n```text\noptions\n```\n\n```text\nSvelteGantt\n```\n\n```text\nprops\n```\n\n```text\ntimeRanges\n```\n\n```text\ncolumnUnit\n```\n\n```text\n'month'\n```\n\n```text\ncolumnOffset\n```\n\n```text\n1\n```\n\n```text\nheaders\n```\n\n```text\nheaders: [{ unit: 'year', format: 'YYYY' }, { unit: 'month', format: 'MMM' }]\n```\n\n```text\noptions\n```\n\n```text\ncurrentStart\n```\n\n```text\ncurrentEnd\n```\n\n```text\ntime()\n```\n\n```text\nmoment\n```\n\n```text\nimport { time } from '../utils';\n```\n\n========================================\n\nComments:\n- This is lacking context. Is the chart a specific public library/component? Where is the code for manipulation of the dates coming from?\n- On top of what @H.B. said, you do realize that your dataset will become up to 52 times larger? Maybe the data source does not provide hourly data over a full year? Have you attempted changing the `columnUnit` value to `'day'` instead?\n- @ThomasHennes I've updated the question with some more context. I always tried changing the column unit to `'day'` & `'month'` but the whole page just freezes up & shows nothing\n- @H.B. I'm using a library called momentjs.com & passing in the current date for it to return the start & end of the year dates\n- Works mate, cheers. I’m going to fork the repo & pass in the current days for each month. Should be good from there.\n- You're welcome. Hopefully you can work out a solution to the variable month duration issue, but that might prove more complex than expected. If you cannot, there seem to be other Gantt libraries that work with Svelte and which might implement a different approach. gantt-schedule-timeline-calendar in particular looked promising. Good luck!","metadata":{"transformedAt":"2026-08-18T18:33:40.704Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":28,"totalLines":229,"estimatedTokens":1360}}594{"id":"stack-59910980","source":"stackoverflow","questionId":59910980,"title":"How can i get right http status code on sapper?","tags":["javascript","http","frontend","svelte","sapper"],"text":"Title: How can i get right http status code on sapper?\nTags: javascript, http, frontend, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI created register page, and submit without any input.\nI got 200 ok though backend server raise 400 reseponsed\nhow can i get right status on my js code?\n\nbelow image is api call to my backend server and responsed 400 status\n\n### api.js\n\n```\nconst base = 'https://gyma9z0wme.execute-api.ap-northeast-2.amazonaws.com/dev';\n// const base = 'http://127.0.0.1:8000';\n\nfunction send({ method, path, data, token }) {\n const fetch = process.browser ? window.fetch : require('node-fetch').default;\n\n const opts = { method, headers: {} };\n\n if (data) {\n opts.headers['Content-Type'] = 'application/json';\n opts.body = JSON.stringify(data);\n }\n\n if (token) {\n opts.headers['Authorization'] = `Bearer ${token}`;\n }\n\n return fetch(`${base}/${path}`, opts)\n .then(r => r.text())\n .then(json => {\n try {\n return JSON.parse(json);\n } catch (err) {\n return json;\n }\n });\n}\n\nexport function get(path, token) {\n return send({ method: 'GET', path, token });\n}\n\nexport function del(path, token) {\n return send({ method: 'DELETE', path, token });\n}\n\nexport function post(path, data, token) {\n return send({ method: 'POST', path, data, token });\n}\n\nexport function put(path, data, token) {\n return send({ method: 'PUT', path, data, token });\n}\n```\n\n### utils.js\n\n```\nexport function post(endpoint, data) {\n return fetch(endpoint, {\n method: 'POST',\n credentials: 'include',\n body: JSON.stringify(data),\n headers: {\n 'Content-Type': 'application/json'\n }\n }).then(r => r.json());\n}\n```\n\n### auth/register.js\n\n```\nimport * as api from \"api.js\";\n\nexport function post(req, res) {\n const user = req.body;\n\n api.post(\"users\", user).then(response => {\n if (response.user) {\n req.session.user = response;\n }\n\n res.setHeader(\"Content-Type\", \"application/json\");\n\n res.end(JSON.stringify(response));\n });\n}\n```\n\n### register/index.svelte\n\n```\n\n import { goto, stores } from \"@sapper/app\";\n import ListErrors from \"../_components/ListErrors.svelte\";\n import { post } from \"utils.js\";\n const { session } = stores();\n let username = \"\";\n let email = \"\";\n let password = \"\";\n let errors = null;\n async function submit(event) {\n const response = await post(`auth/register`, { username, email, password });\n // TODO handle network errors\n if (response.status === 400){\n errors = response;\n }\n if (response.sn) {\n $session.sn = response.sn;\n goto(\"/\");\n }\n }\n\n 회원가입 • Razberry\n\n \n \n \n \n\n### 회원가입\n\n \n 이미 회원인가요?\n \n\n \n\n \n \n \n \n \n \n \n \n \n \n 회원가입\n \n \n \n \n\n```\n\nI'm using realworld code.\n\nhttps://github.com/sveltejs/realworld \n\nTry logging in with incorrect information by here. you can get same result\n\nhttps://realworld.svelte.dev/login\n\n========================================\n\nTop Answer:\n```\napi.post(\"users\", user).then(response => {\nif (response.user) {\n req.session.user = response;\n}\n\nres.setHeader(\"Content-Type\", \"application/json\");\n\nres.end(JSON.stringify(response));\n```\n\nAfter the req.session.user = response, you have no 'else' clause, so the code falls through to setHeader and sends the response. What you need to do:\n\n```\napi.post(\"users\", user).then(response => {\nif (response.user) {\n req.session.user = response;\nres.setHeader(\"Content-Type\", \"application/json\");\nres.end(JSON.stringify(response));\n} else { res.sendStatus(403).end(); }\n```\n\n========================================\n\nCode:\n```js\nconst base = 'https://gyma9z0wme.execute-api.ap-northeast-2.amazonaws.com/dev';\n// const base = 'http://127.0.0.1:8000';\n\nfunction send({ method, path, data, token }) {\n const fetch = process.browser ? window.fetch : require('node-fetch').default;\n\n const opts = { method, headers: {} };\n\n if (data) {\n opts.headers['Content-Type'] = 'application/json';\n opts.body = JSON.stringify(data);\n }\n\n if (token) {\n opts.headers['Authorization'] = `Bearer ${token}`;\n }\n\n return fetch(`${base}/${path}`, opts)\n .then(r => r.text())\n .then(json => {\n try {\n return JSON.parse(json);\n } catch (err) {\n return json;\n }\n });\n}\n\nexport function get(path, token) {\n return send({ method: 'GET', path, token });\n}\n\nexport function del(path, token) {\n return send({ method: 'DELETE', path, token });\n}\n\nexport function post(path, data, token) {\n return send({ method: 'POST', path, data, token });\n}\n\nexport function put(path, data, token) {\n return send({ method: 'PUT', path, data, token });\n}\n```\n\n```js\nexport function post(endpoint, data) {\n return fetch(endpoint, {\n method: 'POST',\n credentials: 'include',\n body: JSON.stringify(data),\n headers: {\n 'Content-Type': 'application/json'\n }\n }).then(r => r.json());\n}\n```\n\n```js\nimport * as api from \"api.js\";\n\nexport function post(req, res) {\n const user = req.body;\n\n api.post(\"users\", user).then(response => {\n if (response.user) {\n req.session.user = response;\n }\n\n res.setHeader(\"Content-Type\", \"application/json\");\n\n res.end(JSON.stringify(response));\n });\n}\n```\n\n```html\n<script>\n import { goto, stores } from \"@sapper/app\";\n import ListErrors from \"../_components/ListErrors.svelte\";\n import { post } from \"utils.js\";\n const { session } = stores();\n let username = \"\";\n let email = \"\";\n let password = \"\";\n let errors = null;\n async function submit(event) {\n const response = await post(`auth/register`, { username, email, password });\n // TODO handle network errors\n if (response.status === 400){\n errors = response;\n }\n if (response.sn) {\n $session.sn = response.sn;\n goto(\"/\");\n }\n }\n</script>\n\n<svelte:head>\n <title>회원가입 • Razberry</title>\n</svelte:head>\n\n<div class=\"auth-page\">\n <div class=\"container page\">\n <div class=\"row\">\n <div class=\"col-md-6 offset-md-3 col-xs-12\">\n <h1 class=\"text-xs-center\">회원가입</h1>\n <p class=\"text-xs-center\">\n <a href=\"/login\">이미 회원인가요?</a>\n </p>\n\n <ListErrors {errors} />\n\n <form on:submit|preventDefault={submit}>\n <fieldset class=\"form-group\">\n <input\n class=\"form-control form-control-lg\"\n type=\"text\"\n placeholder=\"Your Name\"\n bind:value={username} />\n </fieldset>\n <fieldset class=\"form-group\">\n <input\n class=\"form-control form-control-lg\"\n type=\"text\"\n placeholder=\"Email\"\n bind:value={email} />\n </fieldset>\n <fieldset class=\"form-group\">\n <input\n class=\"form-control form-control-lg\"\n type=\"password\"\n placeholder=\"Password\"\n bind:value={password} />\n </fieldset>\n <button class=\"btn btn-lg btn-primary pull-xs-right\">회원가입</button>\n </form>\n </div>\n </div>\n </div>\n</div>\n```\n\n```text\n.catch(()=>{})\n```\n\n```text\napi.post(\"users\", user).then(response => {\nif (response.user) {\n req.session.user = response;\n}\n\nres.setHeader(\"Content-Type\", \"application/json\");\n\nres.end(JSON.stringify(response));\n```\n\n```text\napi.post(\"users\", user).then(response => {\nif (response.user) {\n req.session.user = response;\nres.setHeader(\"Content-Type\", \"application/json\");\nres.end(JSON.stringify(response));\n} else { res.sendStatus(403).end(); }\n```\n\n========================================\n\nComments:\n- You should post some code. Also a good practice is to post images on SO directly (no links!)\n- I can not Upload image directly. i need 3 more points\n- Now you should be able (I upvoted :P )\n- You don't need to upload images for code or error messages. So please post your code so we can help you properly.\n- I'm using realworld code. github.com/sveltejs/realworld Try logging in with incorrect information by here. realworld.svelte.dev/login\n- Might be that the server responds the request with a 200 / OK via http, even if there is an error on backend side. Bad behavior for a backend, but real world...\n- TypeError: res.sendStatus is not a function","metadata":{"transformedAt":"2026-08-18T18:33:40.704Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":366,"estimatedTokens":2030}}595{"id":"stack-50459938","source":"stackoverflow","questionId":50459938,"title":"Is there a way to use pugjs in svelte components?","tags":["webpack","pugjs","svelte"],"text":"Title: Is there a way to use pugjs in svelte components?\nTags: webpack, pugjs, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to rewrite my app made with pugjs and express in sveltejs. I really like to write html in pugjs. I was wondering if there is anyway I can use pugjs in svelte components. I am assuming I may need to use svelte-loader and do some preprocessing or is that even possible? I'm using Sapper to rewrite my application in svelte. Can anyone help me how to do that in Sapper?\n\n========================================\n\nTop Answer:\nThere is a Svelte preprocessor wrapper with baked in support for common used preprocessors, including Pug: https://github.com/kaisermann/svelte-preprocess\n\nHere are my pug mixins, including a bonus `show` mixin (like Vue's `v-show`).\nAt the bottom you can see how to integrate them with svelte-preprocess.\n\n\r\n\r\n\n```\nconst pugMixins = `\r\n\r\nmixin if(condition)\r\n | {#if !{condition}}\r\n block\r\n | {/if}\r\n\r\nmixin else\r\n | {:else}\r\n block\r\n\r\nmixin elseif(condition)\r\n | {:elseif !{condition}}\r\n block\r\n\r\nmixin each(loop)\r\n | {#each !{loop}}\r\n block\r\n | {/each}\r\n\r\nmixin await(promise)\r\n | {#await !{promise}}\r\n block\r\n | {/await}\r\n\r\nmixin then(answer)\r\n | {:then !{answer}}\r\n block\r\n\r\nmixin catch(error)\r\n | {:catch !{error}}\r\n block\r\n\r\nmixin debug(variables)\r\n | {@debug !{variables}}\r\n\r\nmixin show(condition)\r\n div(style!=\"display: {\" + condition + \" ? 'initial' : 'none'}\")\r\n block\r\n\r\n`\r\n\r\nexport default {\r\n /** Transform the whole markup before preprocessing */\r\n onBefore({ content, filename }) {\r\n return content.replace('', '' + pugMixins)\r\n }\r\n}\n```\n\n========================================\n\nCode:\n```text\n{#if|each|await}\n```\n\n```text\n{interpolation}\n```\n\n```js\nconst pugMixins = `\n\nmixin if(condition)\n | {#if !{condition}}\n block\n | {/if}\n\nmixin else\n | {:else}\n block\n\nmixin elseif(condition)\n | {:elseif !{condition}}\n block\n\nmixin each(loop)\n | {#each !{loop}}\n block\n | {/each}\n\nmixin await(promise)\n | {#await !{promise}}\n block\n | {/await}\n\nmixin then(answer)\n | {:then !{answer}}\n block\n\nmixin catch(error)\n | {:catch !{error}}\n block\n\nmixin debug(variables)\n | {@debug !{variables}}\n\nmixin show(condition)\n div(style!=\"display: {\" + condition + \" ? 'initial' : 'none'}\")\n block\n\n`\n\nexport default {\n /** Transform the whole markup before preprocessing */\n onBefore({ content, filename }) {\n return content.replace('<template lang=\"pug\">', '<template lang=\"pug\">' + pugMixins)\n }\n}\n```\n\n```text\nshow\n```\n\n```text\nv-show\n```\n\n========================================\n\nComments:\n- Yes I'm doing that already, just forgot to answer my own question.\n- the svelte-preprocess package has added pug mixins natively using a similar method to yours\n- @MatthewPrasinov Thanks, I didn't know. The `show` mixin above is still missing and nice to add ;)","metadata":{"transformedAt":"2026-08-18T18:33:40.704Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":145,"estimatedTokens":722}}596{"id":"stack-78906849","source":"stackoverflow","questionId":78906849,"title":"Is there a way to debounce a Svelte 5 $derived value?","tags":["svelte","debouncing","svelte-5"],"text":"Title: Is there a way to debounce a Svelte 5 $derived value?\nTags: svelte, debouncing, svelte-5\nSource: Stack Overflow\n\nQuestion:\nI tried with:\n\n```\nlet searchText = $derived(debounce((typedText) => typedText, 2000)(typedText));\n```\n\nBut `searchText` is not assigned!\n\nReproduction with `$derived`: `searchText` is not assigned.\n\nReproduction with `$effect()`: `searchText` assignment is not debounced at all.\n\n========================================\n\nTop Answer:\nYou can simply call a debounced function inside the setter of your variable. This does not use `$derived` but it achieves what you want:\n\n```\nexport function useSearch() {\n let query = $state(\"\");\n let result = $state([]);\n\n const debouncedSearch = debounce(\n (q: string) => {\n result = callSomeApi(q)\n },\n 500,\n );\n\n return {\n // this will get bound to the text field\n get query() {\n return query;\n },\n set query(value) {\n query = value;\n // here's where we trigger our debounced function\n debouncedSearch(value);\n },\n get result() {\n return result;\n },\n };\n}\n```\n\n========================================\n\nCode:\n```text\nlet searchText = $derived(debounce((typedText) => typedText, 2000)(typedText));\n```\n\n```text\nsearchText\n```\n\n```text\n$derived\n```\n\n```text\nsearchText\n```\n\n```text\n$effect()\n```\n\n```text\nsearchText\n```\n\n```js\nconst update = debounce(v => searchText = v, 300);\n$effect(() => update(typedText));\n```\n\n```js\nfunction debouncer(getter, wait, immediate) {\n let current = $state();\n const update = debounce(v => current = v, wait, immediate);\n $effect(() => update(getter()));\n\n return () => current;\n}\n\nlet typedText = $state();\nconst searchText = $derived.by(debouncer(() => typedText, 300));\n```\n\n```text\ndebounce\n```\n\n```text\n$effect\n```\n\n```text\n$derived.by\n```\n\n```none\nexport function useSearch() {\n let query = $state(\"\");\n let result = $state([]);\n\n const debouncedSearch = debounce(\n (q: string) => {\n result = callSomeApi(q)\n },\n 500,\n );\n\n return {\n // this will get bound to the text field\n get query() {\n return query;\n },\n set query(value) {\n query = value;\n // here's where we trigger our debounced function\n debouncedSearch(value);\n },\n get result() {\n return result;\n },\n };\n}\n```\n\n```text\n$derived\n```\n\n```js\nexport function debounce<T>(f: (...args: T[]) => unknown, ms: number) {\n let id: null | number = null;\n return (...args: T[]) => {\n if (id) {\n clearTimeout(id);\n }\n id = setTimeout(() => {\n f(...args);\n }, ms);\n };\n}\n\nexport function debounced<T>(stateGetter: () => T, ms: number) {\n let state = $state(stateGetter());\n const update = debounce<T>((v) => (state = v), ms);\n $effect(() => update(stateGetter()));\n\n return () => state;\n}\n```\n\n```none\nlet getDebouncedSearch = debounced(() => search, 500)\n```\n\n```none\nconst search = $state(\"\");\n\n$effect(() => {\n debounced(() => getSearchResults(search), 500);\n});\n```\n\n========================================\n\nComments:\n- I thought you could not set state inside a derived?\n- @DaviAreias: The only thing that actually happens in a derived context here is the returning of the `current` state (since this is `$derived.by`). You could extract the call to `debouncer` to a separate variable first and only pass the getter it returns into `$derived.by`, that might make the relationship more clear.\n- this doesn't appear to work when you set state instead of calling a fn, eg `debounced(() => someExternalState.search = search, 500);` it gets called on each keypress","metadata":{"transformedAt":"2026-08-18T18:33:40.704Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":181,"estimatedTokens":882}}597{"id":"stack-72738353","source":"stackoverflow","questionId":72738353,"title":"how add coffeescript in svelte on Rails 7?","tags":["javascript","ruby-on-rails","coffeescript","svelte"],"text":"Title: how add coffeescript in svelte on Rails 7?\nTags: javascript, ruby-on-rails, coffeescript, svelte\nSource: Stack Overflow\n\nQuestion:\nI have a Rails 7 app with esbuild :\n\nesbuild.config.js :\n\n```\n#!/usr/bin/env node\n\nconst watch = process.argv.includes(\"--watch\");\nconst esbuild = require('esbuild')\nconst coffeeScriptPlugin = require('esbuild-coffeescript');\nconst esbuildSvelte = require('esbuild-svelte');\nconst sveltePreprocess = require('svelte-preprocess');\n\nesbuild\n .build({\n entryPoints: [\"app/javascript/all.js\"],\n bundle: true,\n outfile: \"app/assets/builds/all.js\",\n // outdir: \"app/assets/builds/\",\n plugins: [\n esbuildSvelte({\n preprocess: sveltePreprocess({coffeescript: { bare: true }}),\n }),\n // coffeeScriptPlugin({bare: true}), I TRIED THIS TOO...\n ],\n logLevel: \"debug\",\n watch: watch\n })\n .catch(() => process.exit(1));\n```\n\nmy.svelte :\n\n```\n\n test = ->\n console.log 'test coffee'\n\n test()\n\n```\n\ngot an error :\n\n$ yarn build --watch yarn run v1.22.19 $ node ./esbuild.config.js\n--watch ✘ [ERROR] [plugin esbuild-svelte] Unexpected token\n\n```\napp/javascript/all.js:3:3:\n 3 │ 1: \n ╵ ^\n\n 2: \n 3: test = ->\n ^ \n 4: console.log 'test coffee' \n 5: test()\n```\n\nThe plugin \"esbuild-svelte\" was triggered by this import\n\n```\napp/javascript/svelte_src.js:6:32:\n 6 │ import DemoSvelteComponent from './svelte/DemoSvelteComponent.svelte'\n ╵ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n```\n\n1 error [watch] build finished, watching for changes... error Command\nfailed with exit code 1. info Visit\nhttps://yarnpkg.com/en/docs/cli/run for documentation about this\ncommand.\n\n```\n$ node -v\nv18.4.0\n```\n\npackage.json :\n\n```\n{\n \"name\": \"app\",\n \"private\": \"true\",\n \"dependencies\": {\n \"@hotwired/stimulus\": \"^3.0.1\",\n \"@hotwired/turbo-rails\": \"^7.1.3\",\n \"esbuild\": \"^0.14.43\",\n \"esbuild-coffeescript\": \"^2.1.0\",\n \"esbuild-svelte\": \"^0.7.1\",\n \"sass\": \"^1.52.3\",\n \"svelte\": \"^3.48.0\",\n \"svelte-preprocess\": \"^4.10.7\"\n },\n \"scripts\": {\n \"build\": \"node ./esbuild.config.js\"\n }\n}\n```\n\n**How add coffeescript in svelte with Rails ?**\n\n========================================\n\nTop Answer:\nThis setup works with *node* `v18.4.0` `v16.15.1` `v14.19.3`. It turned out pretty much identical to what you have, except I don't know what's in your *all.js* file.\n\n```\n// package.json\n\n{\n \"name\": \"app\",\n \"private\": \"true\",\n \"dependencies\": {\n \"@hotwired/stimulus\": \"^3.0.1\",\n \"@hotwired/turbo-rails\": \"^7.1.3\",\n \"esbuild\": \"^0.14.43\",\n \"esbuild-coffeescript\": \"^2.0.0\",\n \"esbuild-svelte\": \"^0.7.1\",\n \"svelte\": \"^3.48.0\",\n \"svelte-preprocess\": \"^4.10.7\"\n },\n \"scripts\": {\n \"build\": \"node ./esbuild.config.js\"\n }\n}\n```\n\n```\n// esbuild.config.js\n\nconst watch = process.argv.includes(\"--watch\");\nconst esbuild = require(\"esbuild\");\nconst esbuildSvelte = require(\"esbuild-svelte\");\nconst sveltePreprocess = require(\"svelte-preprocess\");\n\nesbuild\n .build({\n entryPoints: [\"app/javascript/all.js\"],\n outdir: \"app/assets/builds/\",\n bundle: true,\n sourcemap: true,\n plugins: [\n esbuildSvelte({\n preprocess: sveltePreprocess(),\n }),\n ],\n logLevel: \"debug\",\n watch: watch,\n })\n .catch(() => process.exit(1));\n```\n\n```\n// app/javascript/all.js\n\nimport App from \"./my.svelte\";\nnew App({ target: document.body });\n```\n\n```\n\n test = ->\n console.log 'test coffee'\n test()\n\n```\n\nCompiles:\n\n```\n$ yarn build --watch\nyarn run v1.22.19\n$ node ./esbuild.config.js --watch\n[watch] build finished, watching for changes...\n[watch] build started (change: \"app/javascript/my.svelte\")\n[watch] build finished\n```\n\nand shows up in the browser console:\n\n```\ntest coffee my.svelte:1\n```\n\nThis is a smaller working example, maybe it'll help eliminate the source of the error. It compiles *my.svelte* file directly and prints out the source.\n\n```\n// package.json\n{\n \"dependencies\": {\n \"esbuild\": \"^0.14.43\",\n \"esbuild-coffeescript\": \"^2.1.0\",\n \"esbuild-svelte\": \"^0.7.1\",\n \"svelte\": \"^3.48.0\",\n \"svelte-preprocess\": \"^4.10.7\"\n }\n}\n\n// esbuild.config.js\nrequire(\"esbuild\").build({\n entryPoints: [\"app/javascript/my.svelte\"],\n plugins: [require(\"esbuild-svelte\")({ preprocess: require(\"svelte-preprocess\")() })],\n}).catch(() => process.exit(1));\n```\n\n```\n$ node --version\nv18.4.0\n\n$ node ./esbuild.config.js\nimport { SvelteComponent, init, safe_not_equal } from \"svelte/internal\";\nfunction instance($$self) {\n var test;\n test = function() {\n return console.log(\"test coffee\");\n };\n test();\n return [];\n}\nclass My extends SvelteComponent {\n constructor(options) {\n super();\n init(this, options, instance, null, safe_not_equal, {});\n }\n}\nexport default My;\n```\n\n========================================\n\nCode:\n```text\n#!/usr/bin/env node\n\nconst watch = process.argv.includes(\"--watch\");\nconst esbuild = require('esbuild')\nconst coffeeScriptPlugin = require('esbuild-coffeescript');\nconst esbuildSvelte = require('esbuild-svelte');\nconst sveltePreprocess = require('svelte-preprocess');\n\nesbuild\n .build({\n entryPoints: [\"app/javascript/all.js\"],\n bundle: true,\n outfile: \"app/assets/builds/all.js\",\n // outdir: \"app/assets/builds/\",\n plugins: [\n esbuildSvelte({\n preprocess: sveltePreprocess({coffeescript: { bare: true }}),\n }),\n // coffeeScriptPlugin({bare: true}), I TRIED THIS TOO...\n ],\n logLevel: \"debug\",\n watch: watch\n })\n .catch(() => process.exit(1));\n```\n\n```text\n<script lang=\"coffee\">\n test = ->\n console.log 'test coffee'\n\n test()\n</script>\n```\n\n```text\napp/javascript/all.js:3:3:\n 3 │ 1: \n ╵ ^\n\n 2: <script lang=\"coffee\">\n 3: test = ->\n ^ \n 4: console.log 'test coffee' \n 5: test()\n```\n\n```text\napp/javascript/svelte_src.js:6:32:\n 6 │ import DemoSvelteComponent from './svelte/DemoSvelteComponent.svelte'\n ╵ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n```\n\n```text\n$ node -v\nv18.4.0\n```\n\n```text\n{\n \"name\": \"app\",\n \"private\": \"true\",\n \"dependencies\": {\n \"@hotwired/stimulus\": \"^3.0.1\",\n \"@hotwired/turbo-rails\": \"^7.1.3\",\n \"esbuild\": \"^0.14.43\",\n \"esbuild-coffeescript\": \"^2.1.0\",\n \"esbuild-svelte\": \"^0.7.1\",\n \"sass\": \"^1.52.3\",\n \"svelte\": \"^3.48.0\",\n \"svelte-preprocess\": \"^4.10.7\"\n },\n \"scripts\": {\n \"build\": \"node ./esbuild.config.js\"\n }\n}\n```\n\n```text\nesbuild-coffeescript\n```\n\n```js\n// package.json\n\n{\n \"name\": \"app\",\n \"private\": \"true\",\n \"dependencies\": {\n \"@hotwired/stimulus\": \"^3.0.1\",\n \"@hotwired/turbo-rails\": \"^7.1.3\",\n \"esbuild\": \"^0.14.43\",\n \"esbuild-coffeescript\": \"^2.0.0\",\n \"esbuild-svelte\": \"^0.7.1\",\n \"svelte\": \"^3.48.0\",\n \"svelte-preprocess\": \"^4.10.7\"\n },\n \"scripts\": {\n \"build\": \"node ./esbuild.config.js\"\n }\n}\n```\n\n```js\n// esbuild.config.js\n\nconst watch = process.argv.includes(\"--watch\");\nconst esbuild = require(\"esbuild\");\nconst esbuildSvelte = require(\"esbuild-svelte\");\nconst sveltePreprocess = require(\"svelte-preprocess\");\n\nesbuild\n .build({\n entryPoints: [\"app/javascript/all.js\"],\n outdir: \"app/assets/builds/\",\n bundle: true,\n sourcemap: true,\n plugins: [\n esbuildSvelte({\n preprocess: sveltePreprocess(),\n }),\n ],\n logLevel: \"debug\",\n watch: watch,\n })\n .catch(() => process.exit(1));\n```\n\n```text\n// app/javascript/all.js\n\nimport App from \"./my.svelte\";\nnew App({ target: document.body });\n```\n\n```html\n<!-- app/javascript/my.svelte -->\n\n<script lang=\"coffee\">\n test = ->\n console.log 'test coffee'\n test()\n</script>\n```\n\n```text\n$ yarn build --watch\nyarn run v1.22.19\n$ node ./esbuild.config.js --watch\n[watch] build finished, watching for changes...\n[watch] build started (change: \"app/javascript/my.svelte\")\n[watch] build finished\n```\n\n```txt\ntest coffee my.svelte:1\n```\n\n```js\n// package.json\n{\n \"dependencies\": {\n \"esbuild\": \"^0.14.43\",\n \"esbuild-coffeescript\": \"^2.1.0\",\n \"esbuild-svelte\": \"^0.7.1\",\n \"svelte\": \"^3.48.0\",\n \"svelte-preprocess\": \"^4.10.7\"\n }\n}\n\n// esbuild.config.js\nrequire(\"esbuild\").build({\n entryPoints: [\"app/javascript/my.svelte\"],\n plugins: [require(\"esbuild-svelte\")({ preprocess: require(\"svelte-preprocess\")() })],\n}).catch(() => process.exit(1));\n```\n\n```js\n$ node --version\nv18.4.0\n\n$ node ./esbuild.config.js\nimport { SvelteComponent, init, safe_not_equal } from \"svelte/internal\";\nfunction instance($$self) {\n var test;\n test = function() {\n return console.log(\"test coffee\");\n };\n test();\n return [];\n}\nclass My extends SvelteComponent {\n constructor(options) {\n super();\n init(this, options, instance, null, safe_not_equal, {});\n }\n}\nexport default My;\n```\n\n```text\nv18.4.0\n```\n\n```text\nv16.15.1\n```\n\n```text\nv14.19.3\n```\n\n```text\n\"build-es\": \"esbuild app/javascript/*.* --bundle --sourcemap --outdir=app/assets/builds --public-path=assets\"\n```\n\n```text\n\"build\": \"node ./esbuild.config.js\",\n```\n\n========================================\n\nComments:\n- maby it will help you: github.com/svelte-add/coffeescript\n- I see it, but it's works only with sveltKit and other. We don't have this tools when use esbuild with Rails...\n- `Unexpected token app/javascript/svelte_src.js:10:10: 10 │ 8: --> ╵ ^ 9: 10: test = -> ^ 11: console.log 'test coffee' 12: test() The plugin \"esbuild-svelte\" was triggered by this import` I use node v17.7.1 I can try update...\n- I update node, nothing change... I edit my post and the error message... You keep `coffeescript` package but don't use it in build script... it's curious coffeescript works for you... I realy don't understand\n- @Matrix I'm not sure where `esbuild-coffeescript` is used, but it doesn't work without it. I can't even get the error that you're getting. It only failed for me on node v12 but with a different error. I tried on Ubuntu and OSX. You must have something else installed that's running with esbuild, like `esbuild-coffeescript` does. try removing *node_modules*. Try a smaller build. I see in your error `svelte_src.js` and `DemoSvelteComponent`, all these extra files are not needed while trying to debug.\n- it's same file, I just rename for abstract exemple, but nothing change ;) I will try on new app for see\n- These are not foolproof, but you can check for funky characters: `cat app/javascript/my.svelte | LESSCHARSET=\"ascii\" less` or check all files `LC_ALL=c grep -Pn \"[^[:ascii:]]\" app/javascript/**/*.js`.","metadata":{"transformedAt":"2026-08-18T18:33:40.704Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":467,"estimatedTokens":2564}}598{"id":"stack-67366554","source":"stackoverflow","questionId":67366554,"title":"SvelteKit SSR - how to block server-side render until data has been fetched?","tags":["svelte","svelte-3","sveltekit"],"text":"Title: SvelteKit SSR - how to block server-side render until data has been fetched?\nTags: svelte, svelte-3, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am using SvelteKit and, for SEO reasons, I would like to use full SSR and to ensure that all data is fetched and rendered server-side before being delivered to the browser. In other words, all calls to the back-end API should have completed before the initial page response is delivered.\n\nHowever, it is unclear to me from the documentation how to achieve this. (I may have missed something.)\n\nI have tried the following, but this just delivers a completely empty body:\n\n```\n\n let promise = fetch('https://swapi.dev/api/people/1/')\n .then((response) => response.json());\n\n{#await promise then character}\n\n \n\n### Your character\n\n Name is {character.name}\n\n{/await}\n```\n\nDoes anyone know how to block server-side render using SvelteKit until data has been fetched?\n\n========================================\n\nTop Answer:\nAs noted above, the answer is to export a `load` function (as described here), but just to add a working example of this:\n\n```\n\n /**\n * @type {import('@sveltejs/kit').Load}\n */\n export async function load({ page, fetch, session, context }) {\n const url = `https://swapi.dev/api/people/1/`;\n const res = await fetch(url);\n\n if (res.ok) {\n return {\n props: {\n character: await res.json()\n }\n };\n }\n\n return {\n status: res.status,\n error: new Error(`Could not load ${url}`)\n };\n }\n\n export let character: any;\n\n \n\n### Your character:\n\n Name is {character.name}\n\n Hair color is {character.hair_color}\n\n```\n\n========================================\n\nCode:\n```html\n<script>\n let promise = fetch('https://swapi.dev/api/people/1/')\n .then((response) => response.json());\n</script>\n\n{#await promise then character}\n<main>\n <h1>Your character</h1>\n Name is {character.name}\n</main>\n{/await}\n```\n\n```text\nload\n```\n\n```html\n<script context=\"module\">\n /**\n * @type {import('@sveltejs/kit').Load}\n */\n export async function load({ page, fetch, session, context }) {\n const url = `https://swapi.dev/api/people/1/`;\n const res = await fetch(url);\n\n if (res.ok) {\n return {\n props: {\n character: await res.json()\n }\n };\n }\n\n return {\n status: res.status,\n error: new Error(`Could not load ${url}`)\n };\n }\n</script>\n\n<script lang=\"typescript\">\n export let character: any;\n</script>\n\n<main>\n <h1>Your character:</h1>\n <p>Name is {character.name}</p>\n <p>Hair color is {character.hair_color}</p>\n</main>\n```\n\n```text\nload\n```\n\n========================================\n\nComments:\n- Thank you - I had missed that as I'd understood (wrongly) from external tutorials that Svelte didn't have a set place or way to load external data.","metadata":{"transformedAt":"2026-08-18T18:33:40.704Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":133,"estimatedTokens":715}}599{"id":"stack-73618851","source":"stackoverflow","questionId":73618851,"title":"Svelte return 404 error Not found: /signup Error: Not found: /signup","tags":["visual-studio-code","npm","svelte","sveltekit","custom-error-pages"],"text":"Title: Svelte return 404 error Not found: /signup Error: Not found: /signup\nTags: visual-studio-code, npm, svelte, sveltekit, custom-error-pages\nSource: Stack Overflow\n\nQuestion:\nMy project is returning this annoying 404 error when I click on sign up page. No idea what could be.\nMy main page with the login form, its this one below:\n\n```\n\n import supabase from \"$lib/external/supa\";\n import { goto } from \"$app/navigation\";\n\n let email = \"\";\n let password = \"\";\n\n export let title;\n\n async function handleLogin() {\n if (title == \"Login\") {\n const { user, error } = await supabase.auth.signIn({\n email: email,\n password: password,\n });\n if (user) {\n goto(\"/dashboard\");\n } else {\n console.log(error);\n }\n } else {\n const { user, error } = await supabase.auth.signUp({\n email: email,\n password: password,\n });\n if (user) {\n goto(\"/dashboard\");\n } else {\n console.log(error);\n }\n }\n }\n\n \n\n### {title}\n\n \n \n \n {title}\n \n Not a member? Sign up\n\n```\n\nWhen I click on the sign up button, I got the error below:\n\n```\n404\nNot found: /signup\nError: Not found: /signup\n at resolve (file:////node_modules/@sveltejs/kit/src/runtime/server/index.js:326:13)\n at Object.handle (file:////node_modules/@sveltejs/kit/src/exports/vite/dev/index.js:319:66)\n at respond (file:////node_modules/@sveltejs/kit/src/runtime/server/index.js:345:30)\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\n at async file:////node_modules/@sveltejs/kit/src/exports/vite/dev/index.js:385:22\n```\n\nAnd this mine signup.svelte\n\n```\n\n import LoginForm from \"$lib/components/loginForm.svelte\";\n\n \n\n```\n\nI'm not an expert on Svelte or in front development, but I think that could be something related to the route, when I inpect the page, I just got\n\n```\nFailed to load resource: the server responded with a status of 404 (Not Found)\n```\n\nI used this video as reference:\n\nhttps://www.youtube.com/watch?v=z3BAuF2XZng\n\nMy src/routes:\nhttps://i.sstatic.net/TVUYp.png\n\nThanks!\n\n========================================\n\nCode:\n```text\n<script>\n import supabase from \"$lib/external/supa\";\n import { goto } from \"$app/navigation\";\n\n let email = \"\";\n let password = \"\";\n\n export let title;\n\n async function handleLogin() {\n if (title == \"Login\") {\n const { user, error } = await supabase.auth.signIn({\n email: email,\n password: password,\n });\n if (user) {\n goto(\"/dashboard\");\n } else {\n console.log(error);\n }\n } else {\n const { user, error } = await supabase.auth.signUp({\n email: email,\n password: password,\n });\n if (user) {\n goto(\"/dashboard\");\n } else {\n console.log(error);\n }\n }\n }\n</script>\n\n<div class=\"loginFormContainer\">\n <h1>{title}</h1>\n <form class=\"loginForm\" on:submit|preventDefault={handleLogin}>\n <input type=\"email\" bind:value={email} placeholder=\"email@email.com\"/>\n <input type=\"password\" bind:value={password} placeholder=\"password\"/>\n <button type=\"submit\">{title}</button>\n </form>\n <a href=\"/signup\">Not a member? Sign up</a>\n</div>\n```\n\n```text\n404\nNot found: /signup\nError: Not found: /signup\n at resolve (file:///<path>/node_modules/@sveltejs/kit/src/runtime/server/index.js:326:13)\n at Object.handle (file:///<path>/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js:319:66)\n at respond (file:///<path>/node_modules/@sveltejs/kit/src/runtime/server/index.js:345:30)\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\n at async file:///<path>/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js:385:22\n```\n\n```text\n<script>\n import LoginForm from \"$lib/components/loginForm.svelte\";\n</script>\n\n<div class=\"container\">\n <LoginForm title=\"Sign Up\" />\n</div>\n```\n\n```text\nFailed to load resource: the server responded with a status of 404 (Not Found)\n```\n\n```text\n/src\n /routes\n /dashboard\n +page.svelte\n /signup\n +page.svelte\n +page.svelte\n```\n\n========================================\n\nComments:\n- Could you please your `src/routes` structure with us?\n- This could just be a typo here, but you've spelt `signup.svelte` as `isgnup.svelte`. Sure you got the filenames right?\n- I added my src/routes on the description @phaberest\n- @SSBakh I have checked my code few times, and I didn't any typo, besides that on the description\n- the page name literal \"+page.svelte\"\n- Wait so you are saying if I upgraded svelte my entire application is now broken because they changed how it works? This does not inspire confidence :-)\n- It was changed during the pre-release of SvelteKit, so only if you upgraded from a beta version to another beta version you had this issue. Note that this is also 1.5 years ago, not really relevant for anyone starting now.","metadata":{"transformedAt":"2026-08-18T18:33:40.704Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":187,"estimatedTokens":1193}}600{"id":"stack-70588096","source":"stackoverflow","questionId":70588096,"title":"Error in svelte.config.js Syntax Error: Cannot use import statement outside a module","tags":["svelte","svelte-3"],"text":"Title: Error in svelte.config.js Syntax Error: Cannot use import statement outside a module\nTags: svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI setting up `svelte.config.js` like code below:\n\n```\nimport preprocess from 'svelte-preprocess';\n\nconst config = {\n preprocess: preprocess(),\n};\n\nexport default config;\n```\n\nSuddenly, my Svelte codes keep getting error `Error in svelte.config.js SyntaxError: Cannot use import statement outside a module`\n\nHow to fix this issue? But I still be able to run the project using npm\n\n========================================\n\nTop Answer:\nI fixed the issue by setting up **Svelte Language-server: Runtime on VSCode**\n\nGo to `File > Preferences > Settings` search `svelte` in searchbox, then find `Svelte > Language-server: Runtime`\n\nAfter that, add full path `node.exe` (e.g: `C:\\\\Program Files\\\\nodejs\\\\node.exe`) to `Svelte > Language-server: Runtime`\n\n========================================\n\nCode:\n```text\nimport preprocess from 'svelte-preprocess';\n\nconst config = {\n preprocess: preprocess(),\n};\n\nexport default config;\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nError in svelte.config.js SyntaxError: Cannot use import statement outside a module\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\npackage.json\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nrequire()\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nsvelte.config.mjs\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\npackage.json\n```\n\n```text\nFile > Preferences > Settings\n```\n\n```text\nsvelte\n```\n\n```text\nSvelte > Language-server: Runtime\n```\n\n```text\nnode.exe\n```\n\n```text\nC:\\\\Program Files\\\\nodejs\\\\node.exe\n```\n\n```text\nSvelte > Language-server: Runtime\n```\n\n```text\nnpm i svelte-preprocess\n```\n\n```text\nnpm i -D eslint eslint-plugin-svelte\n```\n\n```text\n<script>\n```\n\n```text\n<script>\n```\n\n```bash\ndeno run -RWE npm:create-vite-extra@latest\n```\n\n```text\ndeno-svelte\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nsvelte.config.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.704Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":138,"estimatedTokens":482}}601{"id":"stack-76764249","source":"stackoverflow","questionId":76764249,"title":"Linking css file with svelte component","tags":["css","svelte"],"text":"Title: Linking css file with svelte component\nTags: css, svelte\nSource: Stack Overflow\n\nQuestion:\nI am trying to link css file with my svelte kit component. I used link element to link it but it did not work. If I made internal style the css style will be applied to the component but when I try to link the component with css file it did not work and the style did not apply\n\n```\n\n### Welcome to your library project\n\nCreate your package using @sveltejs/package and preview/showcase your work with SvelteKit\n\nVisit kit.svelte.dev to read the documentation\n\n`\n```\n\n========================================\n\nTop Answer:\nYou can import styles into a svelte component by simply importing the css file inside your `script` tags as shown below:\n\n```\n\n// Your other imports here...\n\nimport './styles.css';\n\n### This is a title\n\nMore content\n\n```\n\nThis is useful if you want to reuse some css for different component files.\n\nHowever, please keep in mind that it's usually better to isolate styles into their own component file. Another alternative is using the `+layout.svelte` file and putting the CSS there, and as long as all of your components are in the same layout, they will that style.\n\n========================================\n\nCode:\n```html\n<svelte:head>\n<link href=\"../style/index.css\">\n</svelte:head>\n<h1>Welcome to your library project</h1>\n<p>Create your package using @sveltejs/package and preview/showcase your work with SvelteKit</p>\n<p>Visit <a href=\"https://kit.svelte.dev\">kit.svelte.dev</a> to read the documentation</p>`\n```\n\n```html\n...\n\n<h1>This is a title</h1>\n<p>More content</p>\n\n...\n\n<style>\n@import './styles.css';\n</style>\n```\n\n```text\n@import\n```\n\n```text\n+layout.svelte\n```\n\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<link rel=\"stylesheet\" href=\"/style/index.css\">\n<!-- ... other head elements ... -->\n</head>\n<body>\n<script type=\"module\" src=\"/build/bundle.js\"></script>\n</body>\n</html>\n```\n\n```html\n<script>\n// Your other imports here...\n\nimport './styles.css';\n</script>\n\n<h1>This is a title</h1>\n<p>More content</p>\n```\n\n```text\nscript\n```\n\n```text\n+layout.svelte\n```\n\n```text\n<link rel=\"stylesheet\" href=/styles/index.css\">\n```\n\n========================================\n\nComments:\n- I guess my first question would be: Why are you writing CSS separate from your component?\n- I tried to add it to app.html but svelte say Error: Not found\n- This answer does not work for me. Check out my answer below.","metadata":{"transformedAt":"2026-08-18T18:33:40.704Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":115,"estimatedTokens":615}}602{"id":"stack-72856695","source":"stackoverflow","questionId":72856695,"title":"VSCode Typescript intellisense wrong","tags":["javascript","typescript","visual-studio-code","svelte"],"text":"Title: VSCode Typescript intellisense wrong\nTags: javascript, typescript, visual-studio-code, svelte\nSource: Stack Overflow\n\nQuestion:\nI have been trying to create ServiceWorker for my website using SvelteKit, but am running into an issue here. I created a file `/src/service-worker.ts` and in there, I put the following code\n\n```\nimport { build, files, prerendered, version } from '$service-worker';\n\nconst applicationCache = `applicationCache-v${version}`;\nconst staticCache = `staticCache-v${version}`;\n\nconst returnSSRpage = (path) =>\n caches.open(\"ssrCache\").then((cache) => cache.match(path));\n\n// Caches the svelte app (not the data)\nself.addEventListener(\"install\", (event) => {\n event.waitUntil(\n Promise.all([\n caches\n .open(\"ssrCache\")\n .then((cache) => cache.addAll([\"/\"])),\n caches\n .open(applicationCache)\n .then((cache) => cache.addAll(build)),\n caches\n .open(staticCache)\n .then((cache) => cache.addAll(files))\n ])\n .then(self.skipWaiting()),\n )\n})\n... reduced code\n```\n\nWhen running `npm run build` this code compiles perfectly fine and the code runs in the browser. However, my VSCode intellisense gets some stuff wrong. Most notably, it says that the `waitUntil` property of `event` does not exist.\n`Property 'waitUntil' does not exist on type 'Event'.ts(2339)` among other things, such as `Property 'skipWaiting' does not exist on type 'Window & typeof globalThis'.ts(2339)` and `Cannot find name 'clients'.ts(2304)`.\n\nNow, I am quite new to Javascript and Typescript, but from my experience, the Intellisense should not output an error that doesn't also appear during compilation. Why does this happen?\n\nI am unsure of what information to provide. My TS version is 4.7.4 which is also the version VSCode is using for Intellisense. I have installed the ESLint extension for JS and TS.\n\nWhat could be the problem here?\nThanks!\n\n========================================\n\nTop Answer:\nThis worked very well for me:\n\n```\nconst sw: ServiceWorkerGlobalScope = self as unknown as ServiceWorkerGlobalScope;\n```\n\nNow you replace `self` with `sw`, which kinda makes more sense, and also you get correct types.\n\n========================================\n\nCode:\n```text\nimport { build, files, prerendered, version } from '$service-worker';\n\nconst applicationCache = `applicationCache-v${version}`;\nconst staticCache = `staticCache-v${version}`;\n\nconst returnSSRpage = (path) =>\n caches.open(\"ssrCache\").then((cache) => cache.match(path));\n\n// Caches the svelte app (not the data)\nself.addEventListener(\"install\", (event) => {\n event.waitUntil(\n Promise.all([\n caches\n .open(\"ssrCache\")\n .then((cache) => cache.addAll([\"/\"])),\n caches\n .open(applicationCache)\n .then((cache) => cache.addAll(build)),\n caches\n .open(staticCache)\n .then((cache) => cache.addAll(files))\n ])\n .then(self.skipWaiting()),\n )\n})\n... reduced code\n```\n\n```text\n/src/service-worker.ts\n```\n\n```text\nnpm run build\n```\n\n```text\nwaitUntil\n```\n\n```text\nevent\n```\n\n```text\nProperty 'waitUntil' does not exist on type 'Event'.ts(2339)\n```\n\n```text\nProperty 'skipWaiting' does not exist on type 'Window & typeof globalThis'.ts(2339)\n```\n\n```text\nCannot find name 'clients'.ts(2304)\n```\n\n```text\ndeclare var self: ServiceWorkerGlobalScope;\n```\n\n```text\n\"WebWorker\"\n```\n\n```text\ncompilerOptions.lib\n```\n\n```text\ntsconfig.json\n```\n\n```text\nself\n```\n\n```text\nTypeScript: Restart TS Server\n```\n\n```js\nconst sw: ServiceWorkerGlobalScope = self as unknown as ServiceWorkerGlobalScope;\n```\n\n```text\nself\n```\n\n```text\nsw\n```\n\n========================================\n\nComments:\n- Oh nice!!, I wish I could have found this info before.. I'll delete my answer as I've just updated my code for this way.. :)\n- Oh that seems to help! However, this solution still seems to work, even if I don't add the \"WebWorker\" to tsconfig.json and only use the declare function. Also, another piece of code (another event.waitUntil, but with two parameters now) is complaining that it expects 1 but got 2 parameters. However, it still compiles... What could be the issue there?\n- @DutchEllie Your build might not be checking the types correctly or at all. `waitUntil` only takes one argument, anything beyond the first one will simply be ignored at run time.\n- @DutchEllie You seem to have put an extra comma at the end -> `.then(self.skipWaiting()),` Although for me that does not error, are you using something like ESLint?, and it sees this as an extra param?\n- @Keith: Trailing commas like this one will not be considered a separate argument, so this is not the location of the referenced error. (Code is abridged)\n- @H.B. I think I solved it by just wrapping that stuff also in another Promise.all, seems to work just fine.\n- @Keith I removed that, but also removed the braces from the skipWaiting, now there are no more errors!\n- @H.B. Yeah, like I pointed out, it's not erroring for me,.. But if the OP is using something like TSLint, etc. If might be just a linting error. Personally I don't bother with ES/TSLint, as Typescripts error checking seem plenty good.. :)\n- If you use JSDoc: `const sw = /** @type {ServiceWorkerGlobalScope} */ ( /** @type {unknown} */ ( self ) );`","metadata":{"transformedAt":"2026-08-18T18:33:40.704Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":165,"estimatedTokens":1304}}603{"id":"stack-72101008","source":"stackoverflow","questionId":72101008,"title":"How to access sveltekit session in endpoint?","tags":["javascript","svelte","sveltekit"],"text":"Title: How to access sveltekit session in endpoint?\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nHow do you access a session in an endpoint in sveltekit? I've tried this but no luck:\n\n```\nimport { get } from 'svelte/store'; \nimport { getStores} from \"$app/stores\";\n\nfunction getUser() { // get(session).user\n }\n}\n```\n\n========================================\n\nTop Answer:\nThe session store only works inside svelte components, (it uses context under the hood) this provides isolation between users.\n\nYou can import the `getSession()` from `src/hooks.js` and pass the event to reuse the logic that extracts session data from the request.\n\n========================================\n\nCode:\n```text\nimport { get } from 'svelte/store'; \nimport { getStores} from \"$app/stores\";\n\nfunction getUser() { // <- call this at component initialization\n const { session } = getStores();\n \n return {\n current: () => get(session).user\n }\n}\n```\n\n```js\nexport async function get({ locals }) {\n // code goes here\n}\n```\n\n```text\nsrc/hooks.js\n```\n\n```text\nhandle\n```\n\n```text\nevent.locals\n```\n\n```text\ngetSession\n```\n\n```text\nevent.locals\n```\n\n```text\nload\n```\n\n```text\nlocals\n```\n\n```text\ngetSession\n```\n\n```text\nhandle\n```\n\n```text\ngetSession()\n```\n\n```text\nsrc/hooks.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.704Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":88,"estimatedTokens":322}}604{"id":"stack-71481056","source":"stackoverflow","questionId":71481056,"title":"SvelteKit: How to refer to the /routes folder from components and endpoints via alias, like $routes?","tags":["svelte","sveltekit"],"text":"Title: SvelteKit: How to refer to the /routes folder from components and endpoints via alias, like $routes?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nThe next is my (simplified) project structure:\n\n```\nappname\n|\n|__src\n| |__lib\n| |__routes\n|\n|__jsconfig.json\n```\n\nIn the jsconfig.js file, I have paths key with an alias to a './src/lib' folder in form of $lib.\n\n```\n{\n \"compilerOptions\": {\n \"baseUrl\": \".\",\n \"paths\": {\n \"$lib\": [\"src/lib\"],\n \"$lib/*\": [\"src/lib/*\"],\n }\n },\n \"include\": [\"src/**/*.d.ts\", \"src/**/*.js\", \"src/**/*.svelte\"]\n}\n```\n\nI want to access routes folder with $routes alias in the same way as $lib.\nBut if I add \"$routes\": `[\"src/routes\"]` in above JSON file, sveltekit cannot resolve the path starting with `'$routes/somefile'`\n\nExample:\n\n```\n{\n \"compilerOptions\": {\n \"baseUrl\": \".\",\n \"paths\": {\n \"$lib\": [\"src/lib\"],\n \"$lib/*\": [\"src/lib/*\"],\n \"$routes\": [\"src/routes\"],\n \"$routes/*\": [\"src/routes/*\"],\n }\n },\n \"include\": [\"src/**/*.d.ts\", \"src/**/*.js\", \"src/**/*.svelte\"]\n}\n```\n\nendpoint.js\n\n```\nimport { db } from '$routes/db';\n```\n\nWhat am I doing wrong?\n\n========================================\n\nTop Answer:\n**Oct 2022:** The official documentation for Alias makes it clear:\n\n```\n// @svelte.config.js\n\nkit: {\n adapter: adapter(),\n alias: {\n '$routes': './src/routes',\n '$routes/*': './src/routes/*',\n },\n}\n```\n\n- No need to modify `tsconfig.json`\n\n- Make sure you run `npm run dev` after making the changes\n\n========================================\n\nCode:\n```text\nappname\n|\n|__src\n| |__lib\n| |__routes\n|\n|__jsconfig.json\n```\n\n```text\n{\n \"compilerOptions\": {\n \"baseUrl\": \".\",\n \"paths\": {\n \"$lib\": [\"src/lib\"],\n \"$lib/*\": [\"src/lib/*\"],\n }\n },\n \"include\": [\"src/**/*.d.ts\", \"src/**/*.js\", \"src/**/*.svelte\"]\n}\n```\n\n```text\n{\n \"compilerOptions\": {\n \"baseUrl\": \".\",\n \"paths\": {\n \"$lib\": [\"src/lib\"],\n \"$lib/*\": [\"src/lib/*\"],\n \"$routes\": [\"src/routes\"],\n \"$routes/*\": [\"src/routes/*\"],\n }\n },\n \"include\": [\"src/**/*.d.ts\", \"src/**/*.js\", \"src/**/*.svelte\"]\n}\n```\n\n```text\nimport { db } from '$routes/db';\n```\n\n```text\n[\"src/routes\"]\n```\n\n```text\n'$routes/somefile'\n```\n\n```js\nkit: {\n vite: {\n resolve: {\n alias: {\n $routes: path.resolve('./src/routes')\n }\n }\n } \n}\n```\n\n```text\n/src/routes/db.js\n```\n\n```text\nhttp://yoursite.domain/db\n```\n\n```text\nlib\n```\n\n```text\n+page.svelte\n```\n\n```text\n/src/routes/about/+page.svelte\n```\n\n```text\n/about\n```\n\n```json\n{\n \"extends\": \"./.svelte-kit/tsconfig.json\",\n \"compilerOptions\": {\n \"baseUrl\": \".\",\n \"paths\": {\n \"$routes\": [\"src/routes\"],\n \"$routes/*\": [\"src/routes/*\"]\n }\n }\n}\n```\n\n```js\nimport path from 'path';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n kit: {\n vite:{\n resolve: {\n alias: {\n $routes: path.resolve('./src/routes'),\n }\n }\n },\n },\n};\n```\n\n```js\n/// <reference types=\"vitest\" />\nimport { defineConfig } from 'vite';\nimport { svelte } from '@sveltejs/vite-plugin-svelte';\n\nimport { viteConfig } from './svelte.config.js';\n\nimport type { UserConfig } from 'vite';\n\nexport default defineConfig({\n ...(viteConfig as UserConfig),\n plugins: [svelte()],\n});\n```\n\n```text\ntsconfig.json\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nconfig.kit.vite\n```\n\n```text\nvite.config.ts\n```\n\n```text\n// @svelte.config.js\n\nkit: {\n adapter: adapter(),\n alias: {\n '$routes': './src/routes',\n '$routes/*': './src/routes/*',\n },\n}\n```\n\n```text\ntsconfig.json\n```\n\n```text\nnpm run dev\n```\n\n```text\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n kit: {\n alias: {\n $routes: path.resolve('./src/routes'),\n }\n },\n};\n```\n\n```text\nkit.vite.resolve.alias\n```\n\n```text\nkit.alias:\n```\n\n========================================\n\nComments:\n- Yes, you are right. That's VS code's file structure confused me. There is a small indentation and it seemed that my hooks.js, db.js, and other files are under routes, but they are under the src folder. But anyway, now I need to access the $src folder. And when I add $src: path.resolve('./src') it says that path is not defined. What is the path variable in here? Do I need to import it?\n- yes, you have to import path: `import path from 'path';` should do\n- This is the better answer at this time, and can be simplified to just `alias: {$routes: 'src/routes'},`. If you're wondering why you'd want this, absolute paths are easier to change and search (and usually read IMO). VSCode and the Svelte language tools are pretty good at updating import paths automatically when you rename files, so it's less important to avoid breaking imports, but there's enough cases where I dislike relative paths that I sought this out.","metadata":{"transformedAt":"2026-08-18T18:33:40.704Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":276,"estimatedTokens":1201}}605{"id":"stack-70824882","source":"stackoverflow","questionId":70824882,"title":"vitePluginString is not a function","tags":["svelte","vite"],"text":"Title: vitePluginString is not a function\nTags: svelte, vite\nSource: Stack Overflow\n\nQuestion:\nCreated a vite + svelte\n\n```\n$ npm init vite@latest\n✔ Project name: … app1\n✔ Select a framework: › svelte\n✔ Select a variant: › svelte-ts\n```\n\nwanted to include vite-plugin-string to use `glsl` file\n\ninstalled\n\n`npm install --save-dev vite-plugin-string`\n\nconfigured `vite.config.js` file as below\n\n```\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\nimport vitePluginString from 'vite-plugin-string'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [svelte(),vitePluginString()]\n})\n```\n\nAs soon as run `npm run dev`\n\nI get this error\n\n```\n> app1@0.0.0 dev\n> vite\n\nfailed to load config from ....../Six/trailRun/vite.config.js\nerror when starting dev server:\nTypeError: vitePluginString is not a function\n at file:///....../Six/trailRun/vite.config.js?t=1642958252054:8:22\n at ModuleJob.run (node:internal/modules/esm/module_job:195:25)\n at async Promise.all (index 0)\n at async ESMLoader.import (node:internal/modules/esm/loader:337:24)\n at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)\n at async loadConfigFromFile (/....../Six/trailRun/node_modules/vite/dist/node/chunks/dep-f5552faa.js:75089:31)\n at async resolveConfig (/....../Six/trailRun/node_modules/vite/dist/node/chunks/dep-f5552faa.js:74656:28)\n at async createServer (/....../Six/trailRun/node_modules/vite/dist/node/chunks/dep-f5552faa.js:60326:20)\n at async CAC. (/....../Six/trailRun/node_modules/vite/dist/node/cli.js:688:24)\n```\n\nWhat changes I need to make to correct this?\n\n========================================\n\nCode:\n```text\n$ npm init vite@latest\n✔ Project name: … app1\n✔ Select a framework: › svelte\n✔ Select a variant: › svelte-ts\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\nimport vitePluginString from 'vite-plugin-string'\n\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [svelte(),vitePluginString()]\n})\n```\n\n```text\n> app1@0.0.0 dev\n> vite\n\nfailed to load config from ....../Six/trailRun/vite.config.js\nerror when starting dev server:\nTypeError: vitePluginString is not a function\n at file:///....../Six/trailRun/vite.config.js?t=1642958252054:8:22\n at ModuleJob.run (node:internal/modules/esm/module_job:195:25)\n at async Promise.all (index 0)\n at async ESMLoader.import (node:internal/modules/esm/loader:337:24)\n at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)\n at async loadConfigFromFile (/....../Six/trailRun/node_modules/vite/dist/node/chunks/dep-f5552faa.js:75089:31)\n at async resolveConfig (/....../Six/trailRun/node_modules/vite/dist/node/chunks/dep-f5552faa.js:74656:28)\n at async createServer (/....../Six/trailRun/node_modules/vite/dist/node/chunks/dep-f5552faa.js:60326:20)\n at async CAC.<anonymous> (/....../Six/trailRun/node_modules/vite/dist/node/cli.js:688:24)\n```\n\n```text\nglsl\n```\n\n```text\nnpm install --save-dev vite-plugin-string\n```\n\n```text\nvite.config.js\n```\n\n```text\nnpm run dev\n```\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\nimport vitePluginString from 'vite-plugin-string'\n\nexport default defineConfig({\n plugins: [\n svelte(),\n vitePluginString.default(), 👈\n ],\n})\n```\n\n```text\ndefault\n```\n\n========================================\n\nComments:\n- I have several Vite plugins where this seems to be a problem, yet they all document their usage as *not* requiring the `.default`. There seems to be a problem at a deeper level, since it seems obvious that this is not the intended usage.\n- Perhaps it is supposed to be imported like this `import { plugin as vitePluginString } from 'vite-plugin-string'`","metadata":{"transformedAt":"2026-08-18T18:33:40.704Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":136,"estimatedTokens":952}}606{"id":"stack-66297540","source":"stackoverflow","questionId":66297540,"title":"Passing props to the root component of Svelte","tags":["svelte","svelte-3","svelte-component"],"text":"Title: Passing props to the root component of Svelte\nTags: svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI understand that like in many front-end frameworks, Svelte allows the developer to separate logic into smaller, reusable component files. In doing so, you can pass props from a parent to a child component.\n\nI would like to know if it is possible to pass props to the root component itself. I am trying to create a model using Svelte, and require some variables to be determined outside of scope of App.svelte (i.e. variables that are assigned at the same level that imports `bundle.js`)\n\n========================================\n\nCode:\n```text\nbundle.js\n```\n\n```html\n<!-- index.html -->\n<script>\n document.myapp = {\n name: 'Svelte'\n }\n</script>\n<script defer src=\"build/bundle.js\"></script>\n```\n\n```js\n// main.js\nconst app = new App({\n target: document.body,\n props: {\n name: document.myapp.name\n }\n});\n```\n\n```js\n//store.js\nexport const name = readable(document.myapp.name)\n```\n\n```js\n// main.js\nimport App from './App.svelte'\nexport default App\n```\n\n```html\n<!-- index.html -->\n<head>\n <script src='/build/bundle.js'></script>\n</head>\n<body>\n <script>\n new app({\n target: document.body,\n props: {\n name: 'from App'\n }\n })\n </script>\n</body>\n```\n\n```js\n//rollup.config.js\noutput: {\n sourcemap: true,\n format: 'iife',\n name: 'app',\n file: 'public/build/bundle.js'\n},\n```\n\n```text\nindex.html\n```\n\n```text\nmain.js\n```\n\n```text\ndocument.myapp.name\n```\n\n```text\nmain.js\n```\n\n```text\nmain.js\n```\n\n```text\nrollup.config.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.705Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":97,"estimatedTokens":412}}607{"id":"stack-77586510","source":"stackoverflow","questionId":77586510,"title":"SvelteKit JS - Unable to change favicon","tags":["javascript","svelte","sveltekit"],"text":"Title: SvelteKit JS - Unable to change favicon\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nMy package JSON\n\n```\n{\n \"name\": \"WEBSITE_NAME\",\n \"version\": \"0.0.1\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"vite dev\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\",\n \"check\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json\",\n \"check:watch\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch\",\n \"lint\": \"prettier --check .\",\n \"format\": \"prettier --write .\"\n },\n \"devDependencies\": {\n \"@sveltejs/adapter-auto\": \"^2.0.0\",\n \"@sveltejs/kit\": \"^1.27.4\",\n \"prettier\": \"^3.0.0\",\n \"prettier-plugin-svelte\": \"^3.0.0\",\n \"svelte\": \"^4.2.7\",\n \"svelte-check\": \"^3.6.0\",\n \"tslib\": \"^2.4.1\",\n \"typescript\": \"^5.0.0\",\n \"vite\": \"^4.4.2\"\n },\n \"type\": \"module\"\n}\n```\n\nMy app.html file is such\n\n```\n\n \n\n \n \n \n \n \n \n %sveltekit.head%\n\n %sveltekit.body%\n\n```\n\nI've tried what feels like everything and used favicon.io to create my images. I then created a favicon folder in the static folder which should work, but nothing is working. I've also tried moving these links into svelte:head but that didn't work either.\n\nAm I missing something? Could it be an issue in the svelte.config.js file? It's not working locally nor on the deployed website.\n\n========================================\n\nTop Answer:\nI fixed this by adding the following to `+layout.svelte` as explained here:\n\n```\n\n \n\n```\n\nIn my case, `` because I saved the image as `/static/favicon.png`.\n\n========================================\n\nCode:\n```json\n{\n \"name\": \"WEBSITE_NAME\",\n \"version\": \"0.0.1\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"vite dev\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\",\n \"check\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json\",\n \"check:watch\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch\",\n \"lint\": \"prettier --check .\",\n \"format\": \"prettier --write .\"\n },\n \"devDependencies\": {\n \"@sveltejs/adapter-auto\": \"^2.0.0\",\n \"@sveltejs/kit\": \"^1.27.4\",\n \"prettier\": \"^3.0.0\",\n \"prettier-plugin-svelte\": \"^3.0.0\",\n \"svelte\": \"^4.2.7\",\n \"svelte-check\": \"^3.6.0\",\n \"tslib\": \"^2.4.1\",\n \"typescript\": \"^5.0.0\",\n \"vite\": \"^4.4.2\"\n },\n \"type\": \"module\"\n}\n```\n\n```html\n<!doctype html>\n<svelte:head>\n <link href=\"https://fonts.googleapis.com/css?family=Lato\" rel=\"stylesheet\" />\n</svelte:head>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <link rel=\"apple-touch-icon\" sizes=\"180x180\" href=\"%sveltekit.assets%/favicon/apple-touch-icon.png\">\n <link rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"%sveltekit.assets%/favicon/favicon-32x32.png\">\n <link rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"%sveltekit.assets%/favicon/favicon-16x16.png\">\n <link rel=\"manifest\" href=\"%sveltekit.assets%/favicon/site.webmanifest\">\n %sveltekit.head%\n</head>\n\n<body data-sveltekit-preload-data=\"hover\">\n <div style=\"display: contents\">%sveltekit.body%</div>\n</body>\n\n</html>\n```\n\n```text\n├── src\n│ ├── app.d.ts\n│ ├── app.html\n│ ├── hooks.server.ts\n│ ├── lib\n│ │ └── ...\n│ └── routes\n│ └── ...\n├── static\n│ ├── apple-touch-icon.png│\n│ ├── browserconfig.xml\n│ ├── favicon-16x16.png\n| ├── images\n| | └── ...\n│ ├── favicon-32x32.png\n│ ├── favicon.ico\n│ ├── manifest.json\n| └── safari-pinned-tab.svg\n└── tests\n └── ...\n```\n\n```text\n<!-- app.html -->\n<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <link\n href=\"https://fonts.googleapis.com/css2?family=Montserrat:wght@200;400;600;700&display=swap\"\n rel=\"stylesheet\"\n />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=5\" />\n <!-- Generated from https://realfavicongenerator.net/ -->\n <link rel=\"apple-touch-icon\" sizes=\"180x180\" href=\"/apple-touch-icon.png\" />\n <link rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"/favicon-32x32.png\" />\n <link rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"/favicon-16x16.png\" />\n <link rel=\"manifest\" href=\"/manifest.json\" crossorigin=\"use-credentials\" />\n <link rel=\"mask-icon\" href=\"/safari-pinned-tab.svg\" color=\"#5bbad5\" />\n <link rel=\"shortcut icon\" href=\"/favicon.ico\" />\n <meta name=\"msapplication-TileColor\" content=\"#00a300\" />\n <meta name=\"msapplication-config\" content=\"/browserconfig.xml\" />\n <meta name=\"theme-color\" content=\"#ffffff\" />\n %sveltekit.head%\n </head>\n <body>\n <app>%sveltekit.body%</app>\n </body>\n</html>\n```\n\n```text\nfavicon.io\n```\n\n```text\napp.html\n```\n\n```text\n%sveltekit.assets%\n```\n\n```text\n<svelte:head>\n```\n\n```text\napp.html\n```\n\n```text\n<head>\n```\n\n```text\n<svelte:head>\n <link rel=\"icon\" type=\"image/svg\" href={icon-path} />\n</svelte:head>\n```\n\n```text\n+layout.svelte\n```\n\n```text\n<link rel=\"icon\" type=\"image/svg\" href=\"/favicon.png\" />\n```\n\n```text\n/static/favicon.png\n```\n\n========================================\n\nComments:\n- The issue was that I was using in the app.html file. When I instead moved my line to and got rid of those contents are no longer being placed in the content body. I talked to the Svelte team here github.com/sveltejs/kit/issues/11158#issuecomment-1837136799\n- If you do not see it yet, try in private window","metadata":{"transformedAt":"2026-08-18T18:33:40.705Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":226,"estimatedTokens":1370}}608{"id":"stack-69360819","source":"stackoverflow","questionId":69360819,"title":"How to get data attribute of event target in svelte?","tags":["javascript","svelte"],"text":"Title: How to get data attribute of event target in svelte?\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI'd like to get the value of `data-url` in:\n\n```\n{#each profiles as p}\n \n \n \n \n \n\n \n \n \n \n **{p.fn} {p.ln}**\n\n {p.ttl}\n \n\n \n \n {p.dsc}\n \n \n {/each}\n```\n\nThe function is:\n\n```\nconst goToPage = (e) => {\n var slug = e.target.querySelector(\"item\").getAttribute(\"url\");\n console.log(\"slug is:\", slug);\n window.location.href = slug;\n };\n```\n\nHowever it does not work and I get\n\n```\nUncaught TypeError: Cannot read properties of null (reading 'getAttribute')\n```\n\nI have tried other things like\n\n```\ne.target.querySelector(\"item\").getAttribute(\"data-url\");\n```\n\nand\n\n```\ne.target.getAttribute(\"data-url\");\n```\n\nbut none of them worked.\n\n========================================\n\nTop Answer:\n`e.target` references the thing you just clicked, you'll need to use `currentTarget` instead and you don't need to do `querySelector`\n\nEG:\n\n```\nvar slug = e.currentTarget.getAttribute(\"data-url\");\n```\n\nI've done a basic example\n\n\r\n\r\n\n```\nfunction goToPage(e){\n console.debug(e.currentTarget.getAttribute('data-url'));\n}\n```\n\n\r\n\n```\n\n \n \n \n \n\n \n \n \n \n **{p.fn} {p.ln}**\n\n {p.ttl}\n \n\n \n \n {p.dsc}\n \n \n \n \n \n \n \n \n\n \n \n \n \n **{p.fn} {p.ln}**\n\n {p.ttl}\n \n\n \n \n {p.dsc}\n \n \n```\n\n========================================\n\nCode:\n```text\n{#each profiles as p}\n <div data-url={p.url} class=\"item\" on:click={goToPage}>\n <div class=\"row\">\n <div class=\"col s12 l4\">\n <div class=\"a\">\n <br />\n </div>\n </div>\n <div class=\"col s12 l8\">\n <p>\n <strong>{p.fn} {p.ln}</strong><br />\n {p.ttl}\n </p>\n </div>\n </div>\n {p.dsc}\n <hr />\n </div>\n {/each}\n```\n\n```text\nconst goToPage = (e) => {\n var slug = e.target.querySelector(\"item\").getAttribute(\"url\");\n console.log(\"slug is:\", slug);\n window.location.href = slug;\n };\n```\n\n```text\nUncaught TypeError: Cannot read properties of null (reading 'getAttribute')\n```\n\n```text\ne.target.querySelector(\"item\").getAttribute(\"data-url\");\n```\n\n```text\ne.target.getAttribute(\"data-url\");\n```\n\n```text\ndata-url\n```\n\n```html\n<div data-url={p.url} class=\"item\" on:click={() => goToPage(p.url)}>\n```\n\n```js\nconst goToPage = (slug) => {\n console.log(\"slug is:\", slug);\n window.location.href = slug;\n};\n```\n\n```text\nvar slug = e.currentTarget.getAttribute(\"data-url\");\n```\n\n```js\nfunction goToPage(e){\n console.debug(e.currentTarget.getAttribute('data-url'));\n}\n```\n\n```html\n<div data-url=\"https://google.com\" class=\"item\" onClick=\"goToPage(event)\">\n <div class=\"row\">\n <div class=\"col s12 l4\">\n <div class=\"a\">\n <br />\n </div>\n </div>\n <div class=\"col s12 l8\">\n <p>\n <strong>{p.fn} {p.ln}</strong><br />\n {p.ttl}\n </p>\n </div>\n </div>\n {p.dsc}\n <hr />\n </div>\n \n <div data-url=\"https://google2.com\" class=\"item\" onClick=\"goToPage(event)\">\n <div class=\"row\">\n <div class=\"col s12 l4\">\n <div class=\"a\">\n <br />\n </div>\n </div>\n <div class=\"col s12 l8\">\n <p>\n <strong>{p.fn} {p.ln}</strong><br />\n {p.ttl}\n </p>\n </div>\n </div>\n {p.dsc}\n <hr />\n </div>\n```\n\n```text\ne.target\n```\n\n```text\ncurrentTarget\n```\n\n```text\nquerySelector\n```\n\n```text\nnull\n```\n\n```text\nnull.getAttribute()\n```\n\n```text\n.item\n```\n\n```text\n.querySelector(\".item\")\n```\n\n```text\nA.querySelector(B)\n```\n\n```text\ne.target\n```\n\n```text\ne.target.querySelector('.item')\n```\n\n```text\ne.currentTarget\n```\n\n```text\nitemElm.dataset.url\n```\n\n```text\nitemElm.getAttribute('data-url')\n```\n\n========================================\n\nComments:\n- Use attribute binding for it. svelte.dev/docs#bind_element_property\n- @SandipNirmal that is not applicable because the div is in a loop and there are several `someUrl`s here.\n- It works but is a hit-and-miss. Please refer to my edited question. I'd like the whole `div class=\"item\"` be anchored.\n- @Babr Not 100% clear on what you need, it would be helpful to see the whole code - if this is in a loop there's definitely a lot of missed context to what you're trying to achieve that would be useful in helping you\n- Right, I added the div in loop (a bit abbreviated). Please see the question. Basically I'd like the whole div to be clickable.\n- @Babr I've extended my answer and included a working snippet.\n- This does not work either. I get `slug is: null` in the console.\n- It works in the snippet, what do you get when you `console.debug(e.currentTarget)`?\n- Let us continue this discussion in chat.\n- Yes! this way data attribute `data-url={p.url}` is not even needed and we are saved from intericacies of javascript event object. Thanks for the tip.\n- The trouble is that if you're rendering a large table or list of many clickable items, there is a copy of that anon function for every single row/item, which can cause performance problems. If you have 100 rows, you have 100 copies of that function. If you just supply a named function, this doesn't happen.","metadata":{"transformedAt":"2026-08-18T18:33:40.705Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":304,"estimatedTokens":1292}}609{"id":"stack-72124828","source":"stackoverflow","questionId":72124828,"title":"Svelte reactive statement with a variable fron onMount","tags":["scope","svelte","reactive","sveltekit"],"text":"Title: Svelte reactive statement with a variable fron onMount\nTags: scope, svelte, reactive, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm trying to style the currently active tab of my web project with the class \"active\". To target my tab elements I am using\n\n```\nonMount(() => {\n const links = document.querySelectorAll(\".topnav a\");\n});\n```\n\nI am then using a reactive statement to style the appropriate element like this\n\n```\n$: {\n links.forEach((link) => {\n if (link.getAttribute(\"id\") === $page.url.pathname) {\n link.classList.add(\"active\");\n } else {\n link.classList.remove(\"active\");\n }\n });\n}\n```\n\nHowever, I have no way of sharing the `links` variable to my reactive statement. I also tried putting `document.querySelectorAll` inside my reactive statement (not using onMount at all), which worked flawlessly until i reloaded the page. What is the conventional approach to this?\n\n========================================\n\nTop Answer:\nUsing `document.querySelectorAll` is *not* idiomatic Svelte.\n\nChanging class (or other attributes) use the template syntax:\n\n```\n\n {link.label}\n\n```\n\nIf you really need access to the DOM api's Svelte has bind:this or action to get access to specific elements.\n\n========================================\n\nCode:\n```text\nonMount(() => {\n const links = document.querySelectorAll(\".topnav a\");\n});\n```\n\n```text\n$: {\n links.forEach((link) => {\n if (link.getAttribute(\"id\") === $page.url.pathname) {\n link.classList.add(\"active\");\n } else {\n link.classList.remove(\"active\");\n }\n });\n}\n```\n\n```text\nlinks\n```\n\n```text\ndocument.querySelectorAll\n```\n\n```js\nlet links = null;\n\nonMount(() => {\n links = ...;\n);\n\n$: if (links != null) {\n links.forEach((link) => {\n});\n```\n\n```text\nonMount\n```\n\n```html\n<a class:active={link.id === $page.url.pathname}>\n {link.label}\n</a>\n```\n\n```text\ndocument.querySelectorAll\n```\n\n========================================\n\nComments:\n- Is the navigation not in Svelte? Because in Svelte components one should generally not need to use `querySelector` or the like to access DOM.\n- Have a look at the `class:` directive to conditionally apply a class in Svelte","metadata":{"transformedAt":"2026-08-18T18:33:40.705Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":104,"estimatedTokens":546}}610{"id":"stack-72740143","source":"stackoverflow","questionId":72740143,"title":"Cannot apply typescript type to a derived svelte store","tags":["typescript","svelte","svelte-store"],"text":"Title: Cannot apply typescript type to a derived svelte store\nTags: typescript, svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI have a working dervived store called **selectedDocument** in svelte. I am getting the following TS linting error when I attempt to add the correct type to it. (And the intellisense is not working)\n\n### TS Linting errors\n\n### on the definition of the **selectedDocument** store\n\n```\nExpected 2 type arguments, but got 1.ts(2558)\n```\n\n### on ([$selectedDocId, $userDocuments])\n\n```\nType '{ view_id: never; user_id: never; doc_id: never; user_name: never; user_avatar: never; cardMap: never; cards: never; }' must have a '[Symbol.iterator]()' method that returns an iterator.ts(2488)\n```\n\n### THE CODE\n\nThe store works and the type works with other similar data\n\n### Interfaces\n\n```\nexport interface MainView {\n view_id: string;\n user_id: string;\n doc_id: string;\n user_name: string;\n user_avatar: string;\n cardMap: CardMap;\n cards: {\n [key: string]: Card;\n };\n}\nexport interface Document {\n doc_id: string;\n createDate: Date;\n createdBy: string;\n title: string;\n }\n```\n\n### Stores\n\n```\nconst userDocuments = writable(); \n\nconst selectedDocId = writable(\"\"); // Selected doucment Id\n\nconst selectedDocument = derived(\n [selectedDocId, userDocuments],\n ([$selectedDocId, $userDocuments]) =>\n getObjByIdReturnOneObj($userDocuments, $selectedDocId, \"doc_id\")\n);\n```\n\nThe function getObjByIdReturnOneObj takes in the array of documents and returns a single object (not in an array)\n\n```\nexport interface MainView {\n view_id: string;\n user_id: string;\n doc_id: string;\n user_name: string;\n user_avatar: string;\n cardMap: CardMap;\n cards: {\n [key: string]: Card;\n };\n}\nexport interface Document {\n doc_id: string;\n createDate: Date;\n createdBy: string;\n title: string;\n }\n```\n\n### Stores\n\n```\nconst userDocuments = writable(); \n\nconst selectedDocId = writable(\"\"); // Selected doucment Id\n\nconst selectedDocument = derived(\n [selectedDocId, userDocuments],\n ([$selectedDocId, $userDocuments]) =>\n getObjByIdReturnOneObj($userDocuments, $selectedDocId, \"doc_id\")\n);\n```\n\nThe function getObjByIdReturnOneObj takes in the array of documents and returns a single object (not in an array)\n\n========================================\n\nCode:\n```text\nExpected 2 type arguments, but got 1.ts(2558)\n```\n\n```text\nType '{ view_id: never; user_id: never; doc_id: never; user_name: never; user_avatar: never; cardMap: never; cards: never; }' must have a '[Symbol.iterator]()' method that returns an iterator.ts(2488)\n```\n\n```text\nexport interface MainView {\n view_id: string;\n user_id: string;\n doc_id: string;\n user_name: string;\n user_avatar: string;\n cardMap: CardMap;\n cards: {\n [key: string]: Card;\n };\n}\nexport interface Document {\n doc_id: string;\n createDate: Date;\n createdBy: string;\n title: string;\n }\n```\n\n```text\nconst userDocuments = writable<Document[]>(); \n\nconst selectedDocId = writable<string>(\"\"); // Selected doucment Id\n\nconst selectedDocument = derived<Document>(\n [selectedDocId, userDocuments],\n ([$selectedDocId, $userDocuments]) =>\n getObjByIdReturnOneObj($userDocuments, $selectedDocId, \"doc_id\")\n);\n```\n\n```text\nexport interface MainView {\n view_id: string;\n user_id: string;\n doc_id: string;\n user_name: string;\n user_avatar: string;\n cardMap: CardMap;\n cards: {\n [key: string]: Card;\n };\n}\nexport interface Document {\n doc_id: string;\n createDate: Date;\n createdBy: string;\n title: string;\n }\n```\n\n```text\nconst userDocuments = writable<Document[]>(); \n\nconst selectedDocId = writable<string>(\"\"); // Selected doucment Id\n\nconst selectedDocument = derived<Document>(\n [selectedDocId, userDocuments],\n ([$selectedDocId, $userDocuments]) =>\n getObjByIdReturnOneObj($userDocuments, $selectedDocId, \"doc_id\")\n);\n```\n\n```js\nexport declare function derived<S extends Stores, T>(\n stores: S,\n fn: (values: StoresValues<S>) => T\n): Readable<T>;\n```\n\n```js\ndeclare type Stores =\n Readable<any> |\n [Readable<any>, ...Array<Readable<any>>] |\n Array<Readable<any>>;\n```\n\n```js\nconst selectedDocument = derived<\n [typeof selectedDocId, typeof userDocuments],\n ReturnType<typeof getObjByIdReturnOneObj>\n>(...)\n```\n\n```js\nconst selectedDocument = derived<\n [Readable<string>, Readable<Document[]>],\n Document // Based on type specified in question\n>(...)\n```\n\n```text\nderived\n```\n\n```text\ngetObjByIdReturnOneObj\n```\n\n```text\nReadable\n```\n\n```text\nStores\n```\n\n```text\ntypeof\n```\n\n========================================\n\nComments:\n- Could you also provide the typing of `getObjByIdReturnOneObj` ?\n- Thats great! I appreciate the thorough answer\n- Thanks, though the example could have been simpler to understand using one store dependency, like: const originalStore = writable([]); const derivedStore = derived(originalStore, $originalStore => … But I get use just responded to this specifice usecase...","metadata":{"transformedAt":"2026-08-18T18:33:40.705Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":228,"estimatedTokens":1227}}611{"id":"stack-73569508","source":"stackoverflow","questionId":73569508,"title":"How could I get each field in the circle to be the same size and clickable?","tags":["javascript","html","css","svelte"],"text":"Title: How could I get each field in the circle to be the same size and clickable?\nTags: javascript, html, css, svelte\nSource: Stack Overflow\n\nQuestion:\nFor the following code:\nREPL\n\nHow could I make each field of the circle be the same size in a simple way? The fields on the top and bottom are currently bigger than the other ones for obvious reasons.\n\nI could do some complicated calculations with position relative and absolute, but I wonder if there's an easy solution for my problem?\n\nThis is what it should look like:\nhttps://i.sstatic.net/m4oxI.png\n\n========================================\n\nTop Answer:\nI could do some **complicated calculations** with position relative and absolute, but I wonder if there's an easy solution for my problem?\n\nI'm afraid there is no solution completely without *calculations*, but at least this one is not *complicated*.\n\nYou can use conic-gradient and split it by degrees (in my example by 60deg) but the corners tend to be too pixelated. You can also use repeating-conic-gradient.\n\n\r\n\r\n\n```\ndiv {\n position: relative;\n width: 200px;\n height: 200px;\n border-radius: 100%;\n background: conic-gradient( \n /* per 60deg - 5*2deg for white space */\n white 5deg,\n red 5deg 55deg, white 55deg 65deg,\n orange 65deg 115deg, white 115deg 125deg,\n blue 125deg 175deg, white 175deg 185deg,\n pink 185deg 235deg, white 235deg 245deg,\n gray 245deg 295deg, white 295deg 305deg,\n yellow 305deg 355deg, white 355deg 360deg\n );\n}\ndiv:after {\n content: '';\n position: absolute;\n left: 20px;\n top: 20px;\n width: 160px;\n height: 160px;\n background: white;\n border-radius: 100%;\n}\n```\n\n\r\n\n```\n\n```\n\n========================================\n\nCode:\n```text\n<script>\n const size = 300\n let strokeWidth = 25\n let gap = 20\n\n $: circumference = Math.PI * (size - strokeWidth)\n $: r = size/2 - strokeWidth/2\n\n let pieces = [\n {stroke: 'teal'},\n {stroke: 'magenta'},\n {stroke: 'orange'},\n ]\n\n let color = '#1411DF'\n</script>\n\n<div style:width=\"{size}px\">\n <svg width={size} height={size} style=\"transform: rotate({-90+(gap/2/r/Math.PI*180)}deg)\">\n {#each pieces as piece, index}\n {@const ownLength = circumference / pieces.length - gap}\n <circle r={r}\n cx={size/2}\n cy={size/2}\n style:stroke-width={strokeWidth}\n style:stroke={piece.stroke}\n style:stroke-dasharray=\"{ownLength} {circumference}\"\n style=\"fill: none; transform-origin: center;\"\n style:transform=\"rotate({index * 360 / pieces.length}deg)\"\n on:click=\"{() => console.log(piece.stroke)}\"\n />\n {/each}\n </svg>\n\n <input type=\"color\" bind:value={color}>\n <button on:click={() => pieces = [...pieces, {stroke: color}]}>\n add piece\n </button>\n\n <label>\n stroke-width:\n <input type=\"range\" bind:value={strokeWidth} min=\"1\" max={size/5}>\n {strokeWidth}\n </label>\n\n <label>\n gap:\n <input type=\"range\" bind:value={gap} min=\"1\" max={size/5}>\n {gap}\n </label>\n\n</div>\n\n<style>\n circle:hover {\n stroke: black !important;\n }\n div {\n margin: 0 auto;\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n svg {\n display: block;\n margin-bottom: 2rem;\n }\n label {\n width: 100%;\n font-size: .9rem;\n padding: 1rem 0;\n }\n input {\n padding: 0;\n }\n</style>\n```\n\n```text\n<script>\n let colors = ['teal', 'DarkOrchid', 'orange']\n let color = '#2E15D1'\n\n const size = 300\n let strokeWidth = 10\n let gap = 10 // degree\n\n $: r = size/2 - strokeWidth/2\n\n $: deg = (180 - (360 / colors.length) + gap) / 2\n $: x = r * Math.cos(rad(deg))\n $: y = r * Math.sin(rad(deg))\n\n function rad(angle) {\n return angle * Math.PI / 180;\n } \n</script>\n\n<div style:width=\"{size}px\">\n <svg width={size} height={size} viewbox=\"{-size/2} {-size/2} {size} {size}\" xmlns=\"http://www.w3.org/2000/svg\">\n {#each colors as color, index}\n <path d=\"M -{x} -{y} A {r} {r} 0 0 1 {x} -{y}\"\n style=\"fill: none;\"\n style:stroke={color}\n style:stroke-width=\"{strokeWidth}\"\n style:transform=\"rotate({360 / colors.length * index}deg)\"\n on:click=\"{() => console.log(color)}\"\n />\n {/each}\n<!-- <circle cx=\"0\" cy=\"0\" {r} fill=\"none\" stroke=\"black\"></circle> -->\n<!-- <circle cx=\"0\" cy=\"0\" r=\"2\"></circle> -->\n </svg>\n\n <input type=\"color\" bind:value={color}>\n <button on:click={() => colors = [...colors, color]}>\n add piece\n </button>\n\n <label>\n stroke-width:\n <input type=\"range\" bind:value={strokeWidth} min=\"1\" max={size/5}>\n {strokeWidth}\n </label>\n\n <label>\n gap:\n <input type=\"range\" bind:value={gap} min=\"1\" max={(360/colors.length)-1}>\n {gap}°\n </label>\n\n</div>\n\n<style>\n div {\n margin: 0 auto;\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n svg {\n margin: 2rem;\n /* transform: rotate(180deg); */\n }\n path:hover {\n stroke: black !important;\n }\n input {\n padding: 0;\n margin: .4rem;\n }\n label {\n display: grid;\n align-items: center;\n grid-template-columns: 1fr max-content 1fr;\n font-size: .9rem;\n white-space: nowrap;\n }\n</style>\n```\n\n```text\n<svg>\n```\n\n```text\nfill: none;\n```\n\n```css\ndiv {\n position: relative;\n width: 200px;\n height: 200px;\n border-radius: 100%;\n background: conic-gradient( \n /* per 60deg - 5*2deg for white space */\n white 5deg,\n red 5deg 55deg, white 55deg 65deg,\n orange 65deg 115deg, white 115deg 125deg,\n blue 125deg 175deg, white 175deg 185deg,\n pink 185deg 235deg, white 235deg 245deg,\n gray 245deg 295deg, white 295deg 305deg,\n yellow 305deg 355deg, white 355deg 360deg\n );\n}\ndiv:after {\n content: '';\n position: absolute;\n left: 20px;\n top: 20px;\n width: 160px;\n height: 160px;\n background: white;\n border-radius: 100%;\n}\n```\n\n```html\n<div></div>\n```\n\n```text\nA rx ry x-axis-rotation large-arc-flag sweep-flag x y\n a rx ry x-axis-rotation large-arc-flag sweep-flag dx dy\n```\n\n```html\n<svg width=\"320\" height=\"320\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M 50 50 a 50 50 0 0 1 50 0\" stroke=\"black\" stroke-width=\"20\" fill=\"none\"/>\n</svg>\n```\n\n```html\n<script>\n let radius = 150;\n let stroke = 20;\n let gap = 5;\n let segments = [\n '#ff0000',\n '#00ff00',\n '#0000ff',\n ];\n \n function getCoordinates(i, gap) {\n const angleDelta = 360 / segments.length;\n \n const start = polarToCartesian(radius, i * angleDelta + gap);\n const end = polarToCartesian(radius, i * angleDelta + angleDelta);\n\n return { start, end };\n }\n \n const polarToCartesian = (r, angle) => {\n return {\n x: r * Math.cos(rad(angle)),\n y: r * Math.sin(rad(angle)),\n }\n }\n const rad = x => x * Math.PI / 180;\n const onClick = i => alert('Segment ' + i);\n</script>\n\n<div>\n <svg width=\"320\" height=\"320\" xmlns=\"http://www.w3.org/2000/svg\">\n <g transform=\"translate(160, 160) rotate({-90 - gap/2})\">\n {#each segments as segment, i (i)}\n {@const { start, end } = getCoordinates(i, gap)}\n <path d=\"M {start.x} {start.y}\n A {radius} {radius} 0 0 1 {end.x} {end.y}\"\n stroke={segment} stroke-width={stroke} fill=\"none\"\n tabindex={0}\n on:keydown={e => { if (e.key == 'Enter') onClick(i); }}\n on:click={() => onClick(i)} />\n {/each}\n </g>\n </svg>\n</div>\n```\n\n```text\npath\n```\n\n========================================\n\nComments:\n- It's not clear what you are asking. The heights of every lines in the circle are the same.\n- Please include *all* relevant code in the question.\n- @AmauryHanser I added a picture to my original question.\n- @H.B. everything is in the REPL I linked.\n- That is not relevant: StackOverflow requires questions to be *self-contained*, any links should be completely optional to the question.\n- I just updated my answer with a more detailed implementation, by the way.\n- That's what I thought of first. The problem is that I need each field to be clickable (Probably should have mentioned that) and I don't think that works with using conic gradients, or does it?\n- It could be possible with https://developer.mozilla.org/en-US/docs/Web/HTML/Element/map but in that case it is probably better to create your own SVG and paste it as a https://developer.mozilla.org/en-US/docs/Web/SVG.\n- This answer might be helpful.\n- That's definitely interesting! Building the paths itself seem cleaner than the `stroke-dasharray` approach - but it's also quite complicated ;-D I was trying this a bit differently, but gave up... One thing both our examples could probably be improved is the overall rotation ~ starting at the right with either the gap above or below always feels a bit off :)\n- True, nothing some *quick maths* can't fix though 😄\n- Using `stroke-dasharray` is quite a creative approach. I just implemented an arc-based solution, maybe you will find that interesting.\n- @Corrl: Change fill to `fill: none` - now the click should be working as expected. fill transparent will create an invisible area, that's why you can't select the correct pie wedges (the last segment is actually overlapping the previous segments)\n- @Corrl Thank you for the simple solution! I’ve searched for a long time and the solutions I found were either complicated or non existent.\n- @herrstrietzel I encountered another small issue. Some of the circle elements overlap buttons which are below my svg. So whenever I click on one of the circles, the text inside of my button gets highlighted as well. Do you have a solution for that problem?\n- @h-thilo do you mean by highlighted the text of the button is selected? Maybe something `user-select: none;` can fix..?\n- @Corrl Yeah, that's what I mean. The problem with user-select none is that I don't allow selecting the text anymore, which is not the greatest solution. I thought that there would maybe be a solution by manipulating the circle elements directly.\n- @Corrl user-select: none; unfortunately doesn't fix the problem. I am using the second solution.\n- @h-thilo do you have a Repl showing the problem? Probably would be best to start a new question with this...\n- @Corrl I don't, but I can try to reproduce it. Unfortunately it's part of a larger application","metadata":{"transformedAt":"2026-08-18T18:33:40.705Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":352,"estimatedTokens":2717}}612{"id":"stack-50723487","source":"stackoverflow","questionId":50723487,"title":"Svelte: refs undefined","tags":["svelte"],"text":"Title: Svelte: refs undefined\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI'm using Svelte (v2.7) and Sapper (v0.12). According to the docs, `this.refs` should be available, but it's `undefined` for me, both in `oncreate` and custom methods.\n\nMy index.html looks like this:\n\n```\n\n...\n\n export default {\n oncreate() {\n console.log('this.refs is undefined here', this.refs);\n },\n methods: {\n getIsValid() {\n console.log('this.refs is undefined here too', this.refs);\n // ...\n },\n // ...\n }\n };\n\n```\n\n(Full code here).\n\nI'm presuming this isn't a bug (otherwise everyone would have run into it?) and I've got something wrong as it's my first time using it.\n\n========================================\n\nTop Answer:\nThis is deprecated, I believe the new syntax is ``\n\n========================================\n\nCode:\n```text\n<select id=\"wifi-ssid\" ref=\"wifi-ssid\">\n...\n\n<script>\n export default {\n oncreate() {\n console.log('this.refs is undefined here', this.refs);\n },\n methods: {\n getIsValid() {\n console.log('this.refs is undefined here too', this.refs);\n // ...\n },\n // ...\n }\n };\n</script>\n```\n\n```text\nthis.refs\n```\n\n```text\nundefined\n```\n\n```text\noncreate\n```\n\n```text\nref\n```\n\n```text\nref:name\n```\n\n```text\nref=\"name\"\n```\n\n```text\n<select ref:wifissid>\n```\n\n```text\nwifi-ssid\n```\n\n```text\nrefs\n```\n\n```text\n<select bind:this={wifissid}>\n```\n\n========================================\n\nComments:\n- Oops. Eyesight Error :-D Thanks!\n- This syntax is Deprecated\n- This is outdated now, see the other answer.","metadata":{"transformedAt":"2026-08-18T18:33:40.705Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":106,"estimatedTokens":404}}613{"id":"stack-72162106","source":"stackoverflow","questionId":72162106,"title":"How to update data between tabs using Svelte Store","tags":["local-storage","svelte","svelte-store"],"text":"Title: How to update data between tabs using Svelte Store\nTags: local-storage, svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI'm creating a Store in Svelte that subscribes to value changes and stores the value on localStorage.\n\nWhen opening the page there is an input tag with the value binded to the store. Everything works as intended and after refreshing the last value is there.\n\nMy problem and what I don't know how to achieve (If it's even possible) Having a 2nd tab of the same page open, as I type in one I want to see the value update on the other tab.\n\n(I understand that the problem is that this 2nd tab is not aware of localStorage changing)\n\nMy hack solution was an interval reading an updating the value from localStorage, but that's clearly a hack and not a solution.\n\nHow would we go around something like this?\n\nHere is a gist with the 2 files used. https://gist.github.com/MrAmericanMike/b2ddea28e4a4716e43abe03c6211c8b7\n\n========================================\n\nCode:\n```js\nwindow.addEventListener('storage', event => {\n if (event.key == 'DATA') {\n // do something with the newly updated store\n }\n})\n```\n\n```text\nstorage\n```\n\n========================================\n\nComments:\n- Thanks a lot, used the event listener and it works perfectly for my needs.","metadata":{"transformedAt":"2026-08-18T18:33:40.705Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":38,"estimatedTokens":322}}614{"id":"stack-74517909","source":"stackoverflow","questionId":74517909,"title":"Escape Root Layout Svelte Sveltekit","tags":["svelte","sveltekit"],"text":"Title: Escape Root Layout Svelte Sveltekit\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nAccording to the new routing system you can now group routes and have specific layout files in each group. These files inherit for their parent layout files. You can omit this, by using `layout@.svelte`.\n\nHowever in want to omit the root layout file at `src/routes/layout.svelte`. Is there a way to do that?\n\n(Here is the guide: https://kit.svelte.dev/docs/advanced-routing#advanced-layouts)\n\n========================================\n\nTop Answer:\nYou can't.\n\nJust make the root layout empty (i.e. it only contains ``).\n\n========================================\n\nCode:\n```text\nlayout@.svelte\n```\n\n```text\nsrc/routes/layout.svelte\n```\n\n```text\nsrc/routes/\n├ (app)/\n│ ├ blog/\n│ │ └ +page.svelte\n│ ├ +page.svelte\n│ └ +layout.svelte\n└ (login)/\n ├ login/\n │ └ +page.svelte\n └ +layout.svelte\n```\n\n```text\n<slot />\n```\n\n```text\n+page@\n```\n\n```text\n@\n```\n\n```text\nsrc/routes/\n├-child\n│ ├+layout.svelte\n│ ├+layout.ts\n│ └+page.svelte\n└+layout.svelte\n ├layout.ts\n └page.svelte\n```\n\n```js\n// ./src/routes/child/layout.ts\nimport type { LayoutLoad } from './$types';\n\nexport const load: LayoutLoad = () => {\n return {\n skipRootLayout: true, \n };\n};\n```\n\n```html\n<!-- ./src/routes/layout.svelte -->\n<script lang=\"ts\">\n import { page } from '$app/state';\n\n let { children } = $props();\n</script>\n\n{#if !page.data.skipRootLayout}\n <div class=\"some-root-layout-class\">\n {@render children?.()}\n <div>\n{:else}\n <!-- direct rendering without any element wrapping it -->\n {@render children?.()}\n{/else}\n```\n\n```text\npage.data\n```\n\n```text\nroot\n```\n\n```text\nchild\n```\n\n```text\nroot\n```\n\n```text\nroot\n```\n\n```text\nsrc/routes/child/layout.ts\n```\n\n```text\nskipRootLayout\n```\n\n```text\nroot\n```\n\n```text\n$app/state\n```\n\n========================================\n\nComments:\n- I assumed so... If I do that, how do I style the index page (`src/routes/+page.svelte`)?\n- Just put whatever you need into the page file itself if it is specific to that one page. Layouts are simply for shared code and styling, everything that is more specific should be handled by the pages themselves.\n- Advanced layout docs show a similar grouping example with a layout file at the top-level. It's not clear if grouping will still \"escape\" the ungrouped root layout under that condition.\n- Thanks for your answer! But this does'nt work for the root layout either as it states \"The root layout applies to every page of your app, you cannot break out of it.\"\n- You can break out of it with groups. kit.svelte.dev/docs/advanced-routing#advanced-layouts-group\n- It skips parent layouts except the root layout. You can handle it in the root somehow by providing information through exported LayoutLoad at the +layout.ts\n- This works perfectly. Thank you for this. Exactly what I was looking for.","metadata":{"transformedAt":"2026-08-18T18:33:40.705Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":140,"estimatedTokens":717}}615{"id":"stack-65841762","source":"stackoverflow","questionId":65841762,"title":"Bind radio group to a boolean value using svelte","tags":["typescript","svelte"],"text":"Title: Bind radio group to a boolean value using svelte\nTags: typescript, svelte\nSource: Stack Overflow\n\nQuestion:\nI want to create a svelte component that exports a boolean value that can be binded and represents the state of a radio button group, like the following code:\n\n```\n\n export let firstSelected = true;\n\n```\n\nThe problem with this is that `svelte-check` issues the errors:\n\n```\nError: Type 'true' is not assignable to type 'string | number | string[]'. (ts)\nError: Type 'false' is not assignable to type 'string | number | string[]'. (ts)\n```\n\nA possible fix is to use a number instead of a boolean, however this changes the interface of the component:\n\n```\n\n export let firstSelected = 1;\n\n```\n\nIs there a way to fix this while still exposing a bindable boolean value?\nIf not, is there a way to ignore this error?\n\nREPL with example: https://svelte.dev/repl/b6e9042a1b594f2bb77b1e8e7b38ffe1?version=3.31.2\n\n========================================\n\nTop Answer:\nThis was an overly strict typing of the Svelte tooling, which is relaxed in the latest version of Svelte for VS Code (105.9.0) and `svelte-check` (2.2.12).\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n export let firstSelected = true;\n</script>\n\n<input type=\"radio\" bind:group={firstSelected} value={true}/>\n<input type=\"radio\" bind:group={firstSelected} value={false}/>\n```\n\n```text\nError: Type 'true' is not assignable to type 'string | number | string[]'. (ts)\nError: Type 'false' is not assignable to type 'string | number | string[]'. (ts)\n```\n\n```text\n<script lang=\"ts\">\n export let firstSelected = 1;\n</script>\n\n<input type=\"radio\" bind:group={firstSelected} value={1}/>\n<input type=\"radio\" bind:group={firstSelected} value={0}/>\n```\n\n```text\nsvelte-check\n```\n\n```text\n<script lang=\"ts\">\n export let firstSelected = true;\n \n $: _firstSelected = Number(firstSelected);\n \n function handleChange(e) {\n firstSelected = Boolean(_firstSelected);\n }\n</script>\n\n<input type=\"radio\" bind:group={_firstSelected} value={1} on:change={handleChange}/>\n<input type=\"radio\" bind:group={_firstSelected} value={0} on:change={handleChange}/>\n```\n\n```text\non:change\n```\n\n```text\n<script lang=\"ts\">\n export let firstSelected = true;\n \n let group\n \n $: group = firstSelected ? 1 : 0\n</script>\n\n<input type=\"radio\" bind:group={group} value={1}/>\n<input type=\"radio\" bind:group={group} value={0}/>\n```\n\n```text\nsvelte-check\n```\n\n```text\n<input type=\"checkbox\" on:change=\"{myvar = (myvar === true) ? false : true}\">\n```\n\n========================================\n\nComments:\n- The problem with this is that this doesn't work as a two-way binding! When a radio button is clicked, `firstSelected` isn't updated.\n- However adding a `on:change` function the inputs that updates `firstSelected` from `group` seems to work.","metadata":{"transformedAt":"2026-08-18T18:33:40.705Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":113,"estimatedTokens":712}}616{"id":"stack-73300193","source":"stackoverflow","questionId":73300193,"title":"Svelte Reactive Value with Typescript Type","tags":["typescript","svelte"],"text":"Title: Svelte Reactive Value with Typescript Type\nTags: typescript, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get a timestamp from a Date object in Svelte and TypeScript. I want the timestamp to update whenever the Date object is updated, so I'm trying to make it reactive. Here's the code I tried:\n\n```\nlet date: Date = new Date();\n$: timestamp: string = date.getHours() + ':' + date.getMinutes() + \":\" + \n date.getSeconds(); // timestamp in format hh:mm:ss\n```\n\nBut I'm getting this error from TypeScript: `'string' only refers to a type, but is being used as a value here.`. If I remove the type, then everything works. I think multiple meanings of a colon is confusing the compiler but I'm not sure. Is there any way I can do this while keeping the type?\n\n========================================\n\nCode:\n```text\nlet date: Date = new Date();\n$: timestamp: string = date.getHours() + ':' + date.getMinutes() + \":\" + \n date.getSeconds(); // timestamp in format hh:mm:ss\n```\n\n```text\n'string' only refers to a type, but is being used as a value here.\n```\n\n```text\nlet timestamp: string;\n$: timestamp = date.getHours() + ':' + date.getMinutes() + \":\" + \n date.getSeconds(); // timestamp in format hh:mm:ss\n```\n\n```text\nstring\n```\n\n========================================\n\nComments:\n- You're overdoing type definitions. TypeScript will infer the types. Just do `let date = new Date(); $: timestamp = date.getHours() + ... + date.getSeconds();`\n- Too bad we need such an ugly hack.","metadata":{"transformedAt":"2026-08-18T18:33:40.705Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":43,"estimatedTokens":375}}617{"id":"stack-71855962","source":"stackoverflow","questionId":71855962,"title":"Which is the best/most idiomatic way to communicate with components in Svelte?","tags":["svelte"],"text":"Title: Which is the best/most idiomatic way to communicate with components in Svelte?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI am trying to understand how to communicate with Svelte components. In my app I have created two components. In one, *Antescript.svelte*, I communicate with App.svelte using *bind*; in the other, *Postscript.svelte*, I communicate using *dispatch*.\n\nIs one method preferred over the other?\n\nMight I encounter problems using on method rather than the other?\n\nThe *dispatch* method certainly takes more coding, is that a problem?\n\nREPL\n\n**App.svelte**\n\n```\n\n### {antescript} {junction} {postscript}\n\n \n\n \n\nimport AnteScript from \"./AnteScript.svelte\";\nimport PostScript from \"./PostScript.svelte\";\n \n let antescript = 'start';\n let junction = 'and';\n let postscript = 'finish';\n \n function postscriptChanged(event) {\n postscript = event.detail.text;\n }\n\n```\n\n**AnteScript.svelte**\n\n```\n\n export let antescript;\n\n```\n\n**PostScript.svelte**\n\n```\n\n import { createEventDispatcher } from 'svelte';\n const dispatch = createEventDispatcher();\n \n export let postscript;\n \n function textChanged() {\n let postscript_input = document.getElementById(\"postscript\");\n dispatch('message', {\n text: postscript_input.value\n });\n }\n\n```\n\n========================================\n\nCode:\n```text\n<h1>{antescript} {junction} {postscript}</h1>\n<div>\n <AnteScript bind:antescript={antescript}/>\n</div>\n<div>\n <PostScript on:message={postscriptChanged} {postscript}/>\n</div>\n\n<script>\nimport AnteScript from \"./AnteScript.svelte\";\nimport PostScript from \"./PostScript.svelte\";\n \n let antescript = 'start';\n let junction = 'and';\n let postscript = 'finish';\n \n function postscriptChanged(event) {\n postscript = event.detail.text;\n }\n</script>\n```\n\n```text\n<input type=\"text\" bind:value={antescript} />\n\n<script>\n export let antescript;\n</script>\n```\n\n```text\n<input id=\"postscript\" type=\"text\" on:input={textChanged} value={postscript}/>\n\n<script>\n import { createEventDispatcher } from 'svelte';\n const dispatch = createEventDispatcher();\n \n export let postscript;\n \n function textChanged() {\n let postscript_input = document.getElementById(\"postscript\");\n dispatch('message', {\n text: postscript_input.value\n });\n }\n</script>\n```\n\n```text\npostscript\n```\n\n========================================\n\nComments:\n- Your comment down below: *I'm sure I've read somewhere that bind can cause problems* ~ you might refer to this question Binding can make problems if you overuse it and connect too much values between various components and lose track of what changes happen when from where. So it can be said *use it with caution*. But it can save boilderplate like in your example here, just compare the length of both versions. No argument for using dispatch in this case comes to my mind...\n- *The dispatch method certainly takes more coding, is that a problem?* ~ Less code is probably faster and easier understood (for others that read your code and for yourself). Look at this again after some time and see how long it takes for you to get what's happening in each component... Keeping things simple might seem boring, but might on the other hand save time and nerves\n- I'm sure I've read somewhere that *bind* can cause problems - perhaps a little knowledge is a dangerous thing","metadata":{"transformedAt":"2026-08-18T18:33:40.705Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":126,"estimatedTokens":841}}618{"id":"stack-61462558","source":"stackoverflow","questionId":61462558,"title":"Listening to a dispatched event from a Svelte component","tags":["javascript","svelte","svelte-3","svelte-component"],"text":"Title: Listening to a dispatched event from a Svelte component\nTags: javascript, svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI am looking for a way to listen to a dispatched event from a Svelte component within another component from JavaScript (and not from the `on:` syntax).\n\nHere is the code I am trying to achieve on REPL.\n\nThe expected behaviour would be to have **0** displayed in the console when the button *Close 0* is clicked, and so on for the other ones.\n\n========================================\n\nTop Answer:\nI make use of svelte stores and reactivity:\n\nsignals.js:\n\n```\nimport { writable } from 'svelte/store';\nexport const endSignal = writable({});\n```\n\nSender.svelte:\n\n```\n\nimport { endSignal } from './signals.js';\nconst signal = $endSignal;\n\nfunction handleEndSignal(){\n // do other stuff, then send signal\n endSignal.update(()=> signal);\n}\n\nThe End\n```\n\nReceiver.svelte:\n\n```\n\nimport { endSignal } from './signals.js';\n\n$: endItAll(), $endSignal;\n\nlet countEnds = 0;\n\nfunction endItAll(){\n countEnds +=1;\n}\n\ntimes end signal received: {countEnds}\n\n```\n\nBasically, every time we click the button in Sender.svelte, the value \"endSignal\" in \"signals.js\" is overwritten, hence in Receiver.svelte the updated variable in the \"$:\" statement triggers the function \"endItAll()\".\n\n========================================\n\nCode:\n```text\non:\n```\n\n```text\n<script context=\"module\">\n let counter = 0\n</script>\n\n<script>\n import { createEventDispatcher, onMount } from 'svelte';\n // add this\n import { get_current_component } from 'svelte/internal'; \n let _this;\n const id = counter++\n const dispatch = createEventDispatcher()\n /*********\n and add this reactive statement\n **********/\n $: {\n if (_this){\n _this.parentNode.hosts = (_this.parentNode.hosts || []);\n _this.parentNode.hosts.push(get_current_component());\n }\n } \n /*********\n end\n **********/\n function onClose() {\n dispatch('close', id)\n }\n</script>\n<!-- bind this -->\n<button bind:this={_this} class='nested-button' on:click={onClose}>\n Close {id}\n</button>\n```\n\n```text\n<script>\n import { onMount } from 'svelte'\n import Nested from './Nested.svelte'\n\n let element\n\n onMount(() => {\n // requestAnimationFrame is required!\n requestAnimationFrame(() => element.hosts.forEach(nestedButton => {\n nestedButton.$on('close', (e) => {\n console.log(e.detail)\n })\n }));\n })\n</script>\n\n<ul bind:this={element}>\n <Nested/>\n <Nested />\n <Nested />\n</ul>\n```\n\n```text\nfunction onClose() {\n dispatch('close', id)\n this.dispatchEvent(new CustomEvent('close', {detail: id}));\n }\n```\n\n```text\nonClose\n```\n\n```text\n$on\n```\n\n```text\nget_current_component\n```\n\n```text\nonMount\n```\n\n```text\nparentNode.hosts\n```\n\n```text\nul\n```\n\n```text\n$on\n```\n\n```text\nelement.hosts\n```\n\n```text\nimport { writable } from 'svelte/store';\nexport const endSignal = writable({});\n```\n\n```text\n<script>\nimport { endSignal } from './signals.js';\nconst signal = $endSignal;\n\nfunction handleEndSignal(){\n // do other stuff, then send signal\n endSignal.update(()=> signal);\n}\n</script>\n\n<button on:click={handleEndSignal}>The End</button>\n```\n\n```text\n<script>\nimport { endSignal } from './signals.js';\n\n$: endItAll(), $endSignal;\n\nlet countEnds = 0;\n\nfunction endItAll(){\n countEnds +=1;\n}\n</script>\n\n<p>times end signal received: {countEnds}</p>\n```\n\n========================================\n\nComments:\n- Thank you for this complete answer and this tricky workaround. I will check it out but yes, it seems that svelte is not intended to allow catching its component events...","metadata":{"transformedAt":"2026-08-18T18:33:40.705Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":201,"estimatedTokens":931}}619{"id":"stack-62186324","source":"stackoverflow","questionId":62186324,"title":"Svelte bind is not working when customElement: true is set","tags":["javascript","data-binding","svelte"],"text":"Title: Svelte bind is not working when customElement: true is set\nTags: javascript, data-binding, svelte\nSource: Stack Overflow\n\nQuestion:\nI want to build a custom element using Svelte.\n\nThus in `rollup.config.js` I set `customElement: true`, and then I have to use the to refer to my child components.\n\nBut I found that in this way, the `bind` will not work. Here is the code example\n\nHelloWorld.svelte (child)\n\n```\n\n import Hello from './components/Hello'\n import World from './components/World'\n export let value;\n\n```\n\nApp.svslte(parent) part of it.\n\n```\n\n```\n\nThen the parent will show an error: `'value' is not a valid binding on elements.`\n\nHow could I solve this `bind` problem?\n\n========================================\n\nCode:\n```js\n<script>\n import Hello from './components/Hello'\n import World from './components/World'\n export let value;\n</script>\n\n<svelte:options tag={'x-app-helloworld'}/>\n<input type=\"text\" bind:value={value} >\n\n<input>\n<x-app-hello />\n<x-app-world />\n```\n\n```js\n<x-app-helloworld bind:value={value}/>\n```\n\n```text\nrollup.config.js\n```\n\n```text\ncustomElement: true\n```\n\n```text\nbind\n```\n\n```text\n'value' is not a valid binding on <x-app-helloworld> elements.\n```\n\n```text\nbind\n```\n\n```html\n<x-app-helloworld onValueChange=\"{(x) => value = x}\"/>\n```\n\n```html\n<script>\n export let onValueChange;\n export let value;\n\n $: onValueChange(value);\n</script>\n```\n\n```text\nvalue\n```\n\n```text\n<input>\n```\n\n```text\nchange\n```\n\n```text\ninput\n```\n\n========================================\n\nComments:\n- today I come across this issue with using shoe-lace UI components. I think this approach is interesting","metadata":{"transformedAt":"2026-08-18T18:33:40.705Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":106,"estimatedTokens":409}}620{"id":"stack-71180051","source":"stackoverflow","questionId":71180051,"title":"How do I re-render component when a variable changes in svelte-kit?","tags":["svelte","sveltekit"],"text":"Title: How do I re-render component when a variable changes in svelte-kit?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have an array `selectedWeek` in svelte-kit which gets updated when a user clicks a different week on a a calender. However I need to redraw the page, which isn't happening.\n\n`$: selectedWeek` doesn't seem to do anything.\n\n========================================\n\nTop Answer:\nTry adding this simple line\n\n```\nselectedWeek = selectedWeek;\n```\n\nhttps://svelte.dev/tutorial/updating-arrays-and-objects\n\n========================================\n\nCode:\n```text\nselectedWeek\n```\n\n```text\n$: selectedWeek\n```\n\n```text\nselectedWeek = [...selectedWeek, theNewValue]\n```\n\n```text\nselectedWeek = selectedWeek;\n```\n\n========================================\n\nComments:\n- Hard to tell without seeing a bit more code. But one surefire way to re-render a block when a variable is updated is to use the key block `{#key selectedWeek}{/key}`\n- what does `key` do?\n- doesn't do anything anyway\n- Here's a simple example svelte.dev/repl/679ddc8392ee449591e5133598f111ae?version=3.4‌​6.4 But adding more code for your example would be a much quicker way to get help. If you provide a MRE then surely someone will have a valid solution for your issue.\n- pls Show whole code...\n- doesn't do anything.\n- It should. Maybe there's something else in your code. Could you the component code?\n- Turns out I was using beforeUpdate. Don’t know why but removing that solved all the problems.","metadata":{"transformedAt":"2026-08-18T18:33:40.705Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":50,"estimatedTokens":378}}621{"id":"stack-72896690","source":"stackoverflow","questionId":72896690,"title":"Close other dropdown on click in svelte","tags":["javascript","svelte","sveltekit"],"text":"Title: Close other dropdown on click in svelte\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nThis is the simple dropdown component I use.\n\n```\n\n let show = false;\n\n show = !show }>Show Dropdown\n {#if show}\n \n Option 1\n Option 2\n Option 3\n Option 4\n \n {/if}\n\n a { display: block; }\n\n```\n\nI am using this component in parent three times as :\n\n```\n\n import Dropdown from './dropdown.svelte';\n\n \n \n \n\n```\n\nOnce I click first dropdown its respective dropdown content opens, but upon clicking next dropdown how do I close previous dropdowns and open only the one that is clicked?\n\nThank You\n\n========================================\n\nTop Answer:\nWell i never touched svelte but i know an method how to do it.\n\nYou can use `focus` and `blur` events\n\nYou add `tabindex=\"0\"` to the element and whenever you open it, you focus the element. Now, whenever you click outside of the element the blur event will be triggered. It even gets triggerd if you click outside of your browser.\n\n```\n\nimport { tick } from 'svelte';\nlet show = false;\nlet dropdownElement;\nasync function showDropdown() {\n show = !show;\n //we need to wait with tick, until DOM nodes have mounted\n await tick();\n dropdownElement.focus()\n}\n\n Show Dropdown\n {#if show}\n show = false} tabindex=\"0\" bind:this={dropdownElement}>\n Option1\n Option2\n Option3\n \n {/if}\n\n```\n\nI use `div` instead of `a` tags because when you click on the `a` tags, the parent loses its focus.\n\n========================================\n\nCode:\n```text\n<script>\n let show = false;\n</script>\n\n<div>\n <button on:click={() => show = !show }>Show Dropdown</button>\n {#if show}\n <div>\n <a href=\"/\">Option 1</a>\n <a href=\"/\">Option 2</a>\n <a href=\"/\">Option 3</a>\n <a href=\"/\">Option 4</a>\n </div>\n {/if}\n</div>\n\n<style>\n a { display: block; }\n</style>\n```\n\n```text\n<script>\n import Dropdown from './dropdown.svelte';\n</script>\n\n<div>\n <Dropdown />\n <Dropdown />\n <Dropdown />\n</div>\n```\n\n```html\n<script>\n let show = false;\n let container;\n \n function onWindowClick(e) {\n if (container.contains(e.target) == false)\n show = false;\n }\n</script>\n\n<svelte:window on:click={onWindowClick} />\n\n<div bind:this={container}>\n <button on:click={() => show = !show }>Show Dropdown</button>\n ...\n</div>\n```\n\n```text\nclick\n```\n\n```text\nsvelte:window\n```\n\n```text\na\n```\n\n```text\nbutton\n```\n\n```text\nrole\n```\n\n```text\n<script>\nimport { tick } from 'svelte';\nlet show = false;\nlet dropdownElement;\nasync function showDropdown() {\n show = !show;\n //we need to wait with tick, until DOM nodes have mounted\n await tick();\n dropdownElement.focus()\n}\n</script>\n\n<div>\n <button on:click={ showDropdown }>Show Dropdown</button>\n {#if show}\n <div on:blur={() => show = false} tabindex=\"0\" bind:this={dropdownElement}>\n <div>Option1</div>\n <div>Option2</div>\n <div>Option3</div>\n </div>\n {/if}\n</div>\n```\n\n```text\nfocus\n```\n\n```text\nblur\n```\n\n```text\ntabindex=\"0\"\n```\n\n```text\ndiv\n```\n\n```text\na\n```\n\n```text\na\n```\n\n========================================\n\nComments:\n- Using the correct element for a particular task is important for accessibility. This is a hack that prevent using interacting with the options via the keyboard and things like screen readers lack critical information about what the elements represent.\n- Agree, it's better to keep tags intact for both screen readers and ease of use, thank you\n- You can use `` instead of relying on `onMount` and `document.addEventListener`\n- @StephaneVanraes: True, simplifies the code a bit, thanks","metadata":{"transformedAt":"2026-08-18T18:33:40.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":207,"estimatedTokens":917}}622{"id":"stack-71185085","source":"stackoverflow","questionId":71185085,"title":"sveltekit Hash-based routing","tags":["routes","svelte","preload","prefetch","sveltekit"],"text":"Title: sveltekit Hash-based routing\nTags: routes, svelte, preload, prefetch, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm pretty new to svelte and especially SvelteKit. Currently, I'm working on 2 projects.\n\nThe 1st one is a SPA in which I use svelte-spa-router to manage the different states and bring the ability to navigate back and forward like we would do in an old-school website.\nThis works perfectly :)\n\nThe 2nd project is a SvelteKit app. I have 3 use cases:\n\n- Search a product\n\n- Create a product\n\n- Display the top 10 products\n\nIn the first place, I thought that it would be interesting to be able to prefetch some kind of JSON data if needed for each use case, but on the other hand, I didn't want to create a route page for each sub use case because I didn't want the page to refresh each time the user makes a simple action. So, I'm using 3 routes to navigate between these 3 \"use cases\":\n\n```\nsrc/routes/search_product/+page.svelte\nsrc/routes/create_product_page/+page.svelte\nsrc/routes/show_top_10_products/+page.svelte\n```\n\nNow, I have a problem ... there's 3 steps to create a product page. These 3 steps are represented by the 3 different Svelte components below:\n\n- `EnterProductBasicInfo.svelte`\n\n- `UploadPictures.svelte`\n\n- `GivePrices.svelte`\n\nIf the user is in the process of creating a product page and is at step 2), he is shown the `UploadPictures.svelte` component .... but if he press the back button, he will quit the `create_product_page` route instead of getting back to step 1) that is the `EnterProductBasicInfo.svelte` component.\n\nSo, I was thinking that I may use the `svelte-spa-router` that I've used for the SPA, but I'm asking experts here if there is another built-in solution in SvelteKit to be able to manage routes without refreshing the whole page each time a route changes. If you have some good link about SPA, SSR, preloading vs prefetching, I'll take it cause it's still a bit blurry to me.\n\nThank you so much for your help.\n\n========================================\n\nTop Answer:\nStarting with SvelteKit 2.14, hash-based routing is supported and can be configured via `svelte.config.js`.\n\n```\nexport default {\n kit: {\n router: { type: 'hash' }\n }\n}\n```\n\n========================================\n\nCode:\n```bash\nsrc/routes/search_product/+page.svelte\nsrc/routes/create_product_page/+page.svelte\nsrc/routes/show_top_10_products/+page.svelte\n```\n\n```text\nEnterProductBasicInfo.svelte\n```\n\n```text\nUploadPictures.svelte\n```\n\n```text\nGivePrices.svelte\n```\n\n```text\nUploadPictures.svelte\n```\n\n```text\ncreate_product_page\n```\n\n```text\nEnterProductBasicInfo.svelte\n```\n\n```text\nsvelte-spa-router\n```\n\n```html\n<script>\n import { page } from \"$app/stores\";\n</script>\n\n{#if $page.url.hash === \"#step2\"}\n <a href=\"#step1\">Back to step 1</a>\n{:else}\n <a href=\"#step2\">Goto step 2</a>\n{/if}\n```\n\n```js\nexport default {\n kit: {\n router: { type: 'hash' }\n }\n}\n```\n\n```text\nsvelte.config.js\n```\n\n========================================\n\nComments:\n- Just for the record, the key thing using SSR is that pages don't reload as long as routes shares the same `__layout.svelte`.","metadata":{"transformedAt":"2026-08-18T18:33:40.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":118,"estimatedTokens":780}}623{"id":"stack-61858333","source":"stackoverflow","questionId":61858333,"title":"Transitions with Await in Svelte","tags":["javascript","css","templates","transition","svelte"],"text":"Title: Transitions with Await in Svelte\nTags: javascript, css, templates, transition, svelte\nSource: Stack Overflow\n\nQuestion:\nConsider this svelte code\n\n```\n{#await}\n \n LOADING LOGO ANIMATION\n\n \n {:then value}\n \n Main site content\n\n \n```\n\nI'd like to add a transition or animation from the loading 'await' part to when everything is loaded. I'd like the loading part to fade out, and only when its fully faded out for the loaded content to then fade in. Any ideas ? Can this be done this way ?\n\n========================================\n\nTop Answer:\nYou can add a delay to the in transition which is greater than the out transition. e.g.\n\n```\n{#await}\n \n LOADING LOGO ANIMATION\n\n \n{:then value}\n \n Main site content\n\n \n{/await}\n```\n\nThis will avoid having both elements in the DOM at the same time.\n\nIf you always add delays to the beginning of transitions then whenever one component replaces another they should not appear in the DOM at the same time. Even if the components have no information about each other except for the transition duration.\n\n========================================\n\nCode:\n```text\n{#await}\n <div class='loading'>\n <p>LOADING LOGO ANIMATION</p>\n </div> \n {:then value}\n <div class='loaded'>\n <p>Main site content</p>\n </div>\n```\n\n```text\n{#await promise}\n <p transition:fade\n on:introstart=\"{() => visible = false}\"\n on:outroend=\"{() => visible = true}\">\n ...waiting </p>\n{:then value}\n {#if visible}\n <div class=\"loaded\" in:fade>\n <p>Main site content</p>\n </div>\n {/if}\n{/await}\n```\n\n```text\n<script>\n```\n\n```text\nimport { fade } from 'svelte/transition'\n```\n\n```text\nvisible\n```\n\n```text\nfalse\n```\n\n```html\n{#await}\n <div out:fade={{ duration: 100 }} class='loading'>\n <p>LOADING LOGO ANIMATION</p>\n </div> \n{:then value}\n <div in:fade={{ delay: 101, duration: 100 }} class='loaded'>\n <p>Main site content</p>\n </div>\n{/await}\n```\n\n========================================\n\nComments:\n- Hiya! Thanks for the great answer! Yes that does work, however for some reason it takes a very long time after the logo has faded out for the next part to appear. I'm really not understanding why that is. When I remove the transition it works, but without the animation and without any delay.. its very odd :(\n- Glad to know it's working out for you (almost...). It might be worth setting up a Svelte REPL to show what you mean.\n- The REPL link seems to be outdated now.","metadata":{"transformedAt":"2026-08-18T18:33:40.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":108,"estimatedTokens":611}}624{"id":"stack-72139142","source":"stackoverflow","questionId":72139142,"title":"Get parent node dimensions in svelte","tags":["html","css","svelte"],"text":"Title: Get parent node dimensions in svelte\nTags: html, css, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use Svelte and it's my first time so sorry for maybe the stupid question. I read the Svelte documentation but I'm stuck with a simple problem.\n\nBasically, I would like to get the parent dimensions (width and height) of a component.\n\nExample:\n\n```\n\n \n\n```\n\nInside `MyNode` I would like to have the dimensions of the parent `div`. How can I do that?\n\nI tried this:\n\n```\n\n import { onMount, tick } from 'svelte'\n\n let w = 0\n let h = 0\n console.log({ w, h })\n\n onMount(async () => {\n console.log('on mount')\n console.log({ w, h })\n // await tick()\n })\n\n \n side menu\n\n \n content\n \n \n\n```\n\nthis is what I get:\n\nhttps://i.sstatic.net/1CUgS.png\n\nThis is printed only the first time (of course, it is inside the onMount), if I resize the window, nothing change.\nI need to have `w` and `h` always updated. How can I do?\n\n========================================\n\nTop Answer:\nUnlike in other frameworks the code between `script` tags is only executed *once*, during initialization. This explains why you see the `{w: 0, h: 0 }` as those are values at that time.\n\nTo indicate that a piece of code should run again, you have to explicetely mark it as 'reactive'. In your case this would be:\n\n```\n$: console.log({w, h});\n```\n\nYou can do the tutorial to learn more about this: https://svelte.dev/tutorial/reactive-assignments\n\n========================================\n\nCode:\n```text\n<div>\n <MyNode />\n</div>\n```\n\n```text\n<script lang=\"ts\">\n import { onMount, tick } from 'svelte'\n\n let w = 0\n let h = 0\n console.log({ w, h })\n\n onMount(async () => {\n console.log('on mount')\n console.log({ w, h })\n // await tick()\n })\n</script>\n\n<main>\n <div class=\"flex w-screen h-screen\">\n <div class=\"white w-150 min-w-150 h-full\">side menu</div>\n\n <div\n class=\"bg-ligthGrey flex-grow h-full border border-orange-500\"\n bind:clientWidth={w}\n bind:clientHeight={h}\n >\n content\n </div>\n </div>\n</main>\n```\n\n```text\nMyNode\n```\n\n```text\ndiv\n```\n\n```text\nw\n```\n\n```text\nh\n```\n\n```text\n<script>\n import MyNode from './MyNode.svelte'\n \n let w, h\n</script>\n\n<div bind:clientWidth={w} bind:clientHeight={h}>\n <MyNode parentWidth={w} parentHeight={h}/>\n</div>\n\n<style>\n div {\n background: lightblue;\n }\n</style>\n```\n\n```text\n<script>\n export let parentWidth, parentHeight \n</script>\n\nMyNode - parentWidth: {parentWidth} - parentHeight: {parentHeight}\n```\n\n```text\n$: console.log({ w, h })\n```\n\n```text\nw\n```\n\n```text\nh\n```\n\n```text\nparentWidth\n```\n\n```text\nparentHeight\n```\n\n```text\nundefined\n```\n\n```js\n$: console.log({w, h});\n```\n\n```text\nscript\n```\n\n```text\n{w: 0, h: 0 }\n```\n\n========================================\n\nComments:\n- Generally one should not need sizes that much, are you sure this could not be done in CSS? (On StackOverflow people tend to ask about an issue they are stuck with instead of asking how to do what they actually want to achieve. A fix to a bad solution still gives you a bad solution.)","metadata":{"transformedAt":"2026-08-18T18:33:40.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":186,"estimatedTokens":769}}625{"id":"stack-64534228","source":"stackoverflow","questionId":64534228,"title":"Svelte: make component reactive to variable (rerender)","tags":["javascript","node.js","svelte","svelte-3","svelte-component"],"text":"Title: Svelte: make component reactive to variable (rerender)\nTags: javascript, node.js, svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI want to rerender \"Body\" (my svelte component) whenever \"view.current\" changes so it renders the corresponding .svelte view/component:\n\n**App.svelte**\n\n```\n\n import Header from \"./components/Header.svelte\";\n import Footer from \"./components/Footer.svelte\";\n import Body from \"./components/Body.svelte\";\n\n import Login from \"./views/Login.svelte\";\n import Dashboard from \"./views/Dashboard.svelte\";\n\n import { view } from \"./store\";\n\n \n {#if view.current === view.login}\n \n {:else if view.current === view.dashboard}\n \n {/if}\n \n\n```\n\nIn \"Body.svelte\" i just have a slot that gets styled\n\n**Body.svelte**\n\n```\n\n \n \n \n\n .container {\n padding: 1em;\n display: flex;\n }\n .content {\n margin: auto;\n }\n\n```\n\nIn Login.svelte (and other svelte components) i want to change \"view.current\":\n\n**Login.svelte**\n\n```\n\n import { view } from \"../store\";\n\n function handleLoginClick() {\n view.current = view.dashboard;\n }\n\nLogin\n\n .login-btn {\n display: block;\n margin: auto;\n }\n\n```\n\n**store.js**\n\n```\nconst user = {\n username: \"\",\n fullname: \"\",\n role: null,\n isLoggedIn: false\n};\n\nconst view = {\n login: 1,\n dashboard: 2,\n current: 1\n};\n\nexport {\n user,\n view\n}\n```\n\nThe value of \"view.current\" changes as expected, however \"Body\" does not update/rerender. So it always shows the login.svelte no matter to what \"view.current\" has been set.\nIs there a quick and easy way to make \"Body\" reactive to \"view.current\" so that it rerenders so that the if/else-block in \"App.svelte\" get's reevaluated?\n\n========================================\n\nCode:\n```text\n<script>\n import Header from \"./components/Header.svelte\";\n import Footer from \"./components/Footer.svelte\";\n import Body from \"./components/Body.svelte\";\n\n import Login from \"./views/Login.svelte\";\n import Dashboard from \"./views/Dashboard.svelte\";\n\n import { view } from \"./store\";\n</script>\n\n<Header />\n <Body>\n {#if view.current === view.login}\n <Login />\n {:else if view.current === view.dashboard}\n <Dashboard />\n {/if}\n </Body>\n<Footer />\n```\n\n```text\n<div class=\"container\">\n <div class=\"content\">\n <slot></slot>\n </div>\n</div>\n\n<style>\n .container {\n padding: 1em;\n display: flex;\n }\n .content {\n margin: auto;\n }\n</style>\n```\n\n```text\n<script>\n import { view } from \"../store\";\n\n function handleLoginClick() {\n view.current = view.dashboard;\n }\n</script>\n\n\n<button type=\"button\" on:click={handleLoginClick} class=\"btn btn-primary btn-lg login-btn\">Login</button>\n\n<style>\n .login-btn {\n display: block;\n margin: auto;\n }\n</style>\n```\n\n```text\nconst user = {\n username: \"\",\n fullname: \"\",\n role: null,\n isLoggedIn: false\n};\n\nconst view = {\n login: 1,\n dashboard: 2,\n current: 1\n};\n\nexport {\n user,\n view\n}\n```\n\n```js\nimport { writable } from 'svelte/store'\n\nconst view = writable({\n login: 1,\n dashboard: 2,\n current: 1\n});\n```\n\n```html\n<script>\n function handleLoginClick() {\n $view.current = $view.dashboard;\n }\n</script>\n```\n\n```html\n{#if $view.current === $view.login}\n <Login />\n{:else if $view.current === $view.dashboard}\n <Dashboard />\n{/if}\n```\n\n```text\nview\n```\n\n```text\n$\n```\n\n========================================\n\nComments:\n- Why do you want your `Body` component to re-render?\n- When view.current is set to lets say \"login\" i want to render the stuff in login.svelte, when it is set to \"dashboard\" i want to render \"dashboard.svelte\" and so on.\n- is this `view` a svelte store ?\n- No, it's just a js file. I also tried to make \"view\" to a svelte.store, but it behaves the same way. I have edited the post and added the contents of store.js.\n- Try `$: currentView = view.current;` and use `currentView` in the markup? Note: I might be completely wrong, I'm not yet 100% comfortable with Svelte.\n- Unfortunately this does not work - same behavior. :/\n- Thank you, this does the trick. Did not know it creates a local copy of it.","metadata":{"transformedAt":"2026-08-18T18:33:40.706Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":224,"estimatedTokens":1038}}626{"id":"stack-58597422","source":"stackoverflow","questionId":58597422,"title":"Where to store user session in Sapper app","tags":["javascript","firebase","server-side-rendering","svelte","sapper"],"text":"Title: Where to store user session in Sapper app\nTags: javascript, firebase, server-side-rendering, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI have started moving an app from React to Sapper. I am new to SSR architecture and want to know what the best way is to store the user session and data. \n\nI am using Firebase for my auth and database. After using the client side firebase API to get the session keys and other user data how would I store the data? I have seen some tutorials making a user.js store, but in the Sapper docs I see it recommends using the *session* *store*. So which is better? And what would be the flow from client side to the server side session store?\n\nE.g. If I were to make a login folder under which I have the svelte component and the server side route. Would there be a post \"endpoint\" that would set the session.user?\n\n========================================\n\nTop Answer:\nIt's a bit tricky. I managed to get this working with both client and server using a authentication middleware\n\nhttps://github.com/itswadesh/sapper-ecommerce/blob/master/src/server.js\n\n========================================\n\nCode:\n```text\nexpress()\n .use(\n compression({\n threshold: 0\n }),\n sirv('static', {\n dev\n }),\n cookieParser(),\n bodyParser.json({strict: false}),\n bodyParser.urlencoded({ extended: false }),\n async (req, res, next) => {\n const token = req.cookies['AUTH']\n const profile = token && !dev ? await getBasicUserInfo(token) : false\n\n return sapper.middleware({\n session: () => {\n return {\n authenticated: !!profile,\n profile\n }\n }\n })(req, res, next)\n }\n )\n```\n\n```text\n'credentials':'include\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":52,"estimatedTokens":470}}627{"id":"stack-79138648","source":"stackoverflow","questionId":79138648,"title":"Type for Components Passed as Props in Svelte 5","tags":["svelte","svelte-5"],"text":"Title: Type for Components Passed as Props in Svelte 5\nTags: svelte, svelte-5\nSource: Stack Overflow\n\nQuestion:\nLet's say I have a parent component called `SplitView.svelte`:\n\n```\n\n import type { Snippet } from 'svelte'\n \n type Props = {\n master: Snippet\n detail: Snippet\n }\n let { master, detail }: Props = $props()\n\n \n {@render master()}\n \n \n {@render detail()}\n \n\n```\n\nWhich I use elsewhere like this:\n\n```\n\n import SplitView from '$lib/components/shared/SplitView.svelte'\n import Master from './master/PricingMaster.svelte'\n import Detail from './detail/PricingDetail.svelte'\n\n I'm getting a linter error on the `master` and `detail` attributes:\n\n```\nType '__sveltets_2_IsomorphicComponent, \n{ [evt: string]: CustomEvent; }, {}, {}, string>' is not assignable to type 'Snippet'.\n\nTarget signature provides too few arguments. Expected 2 or more, but got 0.ts(2322)\n```\n\nAre components sent as props not of type `Snippet`? What am I doing wrong?\n\n========================================\n\nCode:\n```js\n<script lang=\"ts\">\n import type { Snippet } from 'svelte'\n \n type Props = {\n master: Snippet\n detail: Snippet\n }\n let { master, detail }: Props = $props()\n</script>\n\n<div class=\"split\">\n <div id=\"master\">\n {@render master()}\n </div>\n <div id=\"detail\">\n {@render detail()}\n </div>\n</div>\n```\n\n```js\n<script lang=\"ts\">\n import SplitView from '$lib/components/shared/SplitView.svelte'\n import Master from './master/PricingMaster.svelte'\n import Detail from './detail/PricingDetail.svelte'\n</script>\n\n<SplitView master={Master} detail={Detail} /> <-- ESLint error\n```\n\n```text\nType '__sveltets_2_IsomorphicComponent<Record<string, never>, \n{ [evt: string]: CustomEvent<any>; }, {}, {}, string>' is not assignable to type 'Snippet<[]>'.\n\nTarget signature provides too few arguments. Expected 2 or more, but got 0.ts(2322)\n```\n\n```text\nSplitView.svelte\n```\n\n```text\nmaster\n```\n\n```text\ndetail\n```\n\n```text\nSnippet\n```\n\n```html\n//SplitView.svelte\n<script lang=\"ts\">\n import type { Component } from 'svelte'\n\n type Props = {\n Master: Component\n Detail: Component\n }\n \n let { Master, Detail }= $props()\n</script>\n\n<div class=\"split\">\n <div id=\"master\">\n <Master />\n </div>\n <div id=\"detail\">\n <Detail />\n </div>\n</div>\n```\n\n```html\n<script lang=\"ts\">\n import SplitView from './SplitView.svelte'\n import MyMaster from './PricingMaster.svelte'\n import Detail from './PricingDetail.svelte'\n\n // Name your components, Master and Detail to simplify the Props\n</script>\n <!-- or use Master={MasterName} Detail={DetailName} \n to pass components with different component names -->\n<SplitView Master={MyMaster} {Detail} />\n```\n\n```text\nComponent\n```\n\n========================================\n\nComments:\n- Excellent, thank you! I believe `master` and `detail` in the `type Props` also have to be capitalized so that they exactly match the destructured `$props()`.\n- You're correct, I have edited the answer to reflect. Thanks for pointing it out!","metadata":{"transformedAt":"2026-08-18T18:33:40.706Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":147,"estimatedTokens":748}}628{"id":"stack-58115156","source":"stackoverflow","questionId":58115156,"title":"Do dynamic props exist in Svelte 3","tags":["svelte"],"text":"Title: Do dynamic props exist in Svelte 3\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nWhen I iterate over a dynamic component like:\n\n```\n\n```\n\nIs it possible to use a set of dynamic props for each component. Each component having it's own set of prop names and prop values.\n\n**Solution example:**\n\n```\n\n import Info from './Info.svelte';\n\n const pkgs = [{\n name: 'svelte',\n version: 3,\n speed: 'blazing',\n website: 'https://svelte.dev'\n }, ];\n\n```\n\nMore in this Rich Harris answer here.\n\n========================================\n\nCode:\n```text\n<svelte:component collection={collection} uid={uid} this={upload_component} \n bind:action={restart}/>\n```\n\n```text\n<script>\n import Info from './Info.svelte';\n\n const pkgs = [{\n name: 'svelte',\n version: 3,\n speed: 'blazing',\n website: 'https://svelte.dev'\n }, ];\n</script>\n\n<Info {...pkgs[0]}/>\n```\n\n```html\n<svelte:component this={upload_component} bind:action={restart} {...someprops}/>\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.706Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":56,"estimatedTokens":246}}629{"id":"stack-45638717","source":"stackoverflow","questionId":45638717,"title":"Using Rollup + Svelte with third party AMD libraries","tags":["javascript","node.js","amd","rollupjs","svelte"],"text":"Title: Using Rollup + Svelte with third party AMD libraries\nTags: javascript, node.js, amd, rollupjs, svelte\nSource: Stack Overflow\n\nQuestion:\nI understand that Svelte can produce AMD **output** and find some details on how to do this in the docs. I can also find some info on how to configure Rollup to **output** AMD modules. But what about **input**? What do I need to do when I have AMD modules as dependencies?\n\nFor example, suppose I have two different third party libraries that are both distributed as AMD libraries and I want to use those libraries in my Svelte project. How would I need to modify eg. this nested components demo to allow these AMD modules to be used as dependencies in my Svelte components? \n\nAlso, am I able to configure whether I bundle these libraries together with my Svelte components? If so, where would I need to do that?\n\n### Note\n\nI also raised this issue on Github.\n\n========================================\n\nCode:\n```js\n// rollup.config.js\nexport default {\n // ...\n format: 'amd',\n external: ['an-external-amd-module'],\n paths: {\n 'an-external-amd-module': 'https://my-cdn.com/an-external-amd-module.js'\n }\n};\n```\n\n```text\nimport\n```\n\n```text\nimport\n```\n\n========================================\n\nComments:\n- Thanks, again, for your swift response! This'll do for now.","metadata":{"transformedAt":"2026-08-18T18:33:40.706Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":42,"estimatedTokens":329}}630{"id":"stack-71570368","source":"stackoverflow","questionId":71570368,"title":"Where should I add \"customElement:true\" in SvelteKit?","tags":["element","svelte","sveltekit"],"text":"Title: Where should I add \"customElement:true\" in SvelteKit?\nTags: element, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a custom element in SvelteKit like so\n\n```\n\n```\n\nin the docs there is a line saying that you have to add this line\n\n```\ncustomElement:true\n```\n\nbut where? SvelteKit doesn't have `rollup.config.js` with plugins but `svelte.config.js` without plugins.\n\nDo you know where to add it in SvelteKit?\n\n========================================\n\nCode:\n```html\n<svelte:options tag=\"my-element\" />\n```\n\n```text\ncustomElement:true\n```\n\n```text\nrollup.config.js\n```\n\n```text\nsvelte.config.js\n```\n\n```js\n// svelte.config.js\n\n// imports ...\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n compilerOptions: {\n customElement: true\n // other compiler options ...\n },\n\n kit: {\n adapter: adapter(),\n // other kit options ...\n },\n\n // other config options ...\n};\n\nexport default config;\n```\n\n```text\nsvelte.config.js\n```\n\n```text\ncompilerOptions\n```\n\n```text\nconfig\n```\n\n```text\ncustomElement\n```\n\n```text\ntrue\n```\n\n========================================\n\nComments:\n- Adding to make this easier to find: the error message you get if you use svelte:options without configuring customElement:true is options_missing_custom_element: \"The `customElement` option is used when generating a custom element. Did you forget the `customElement: true` compile option?\"\n- I am following a book (paid) and it said to add the compilerOptions statement in vite.config.js`and NOT in the correct file > *svelte.config.js* so thanks for pointing to the correct file!","metadata":{"transformedAt":"2026-08-18T18:33:40.706Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":88,"estimatedTokens":410}}631{"id":"stack-71221427","source":"stackoverflow","questionId":71221427,"title":"Web components with vaadin and rollup with svelte: Primary button ignores theme attribute","tags":["vaadin","web-component","svelte","rollup"],"text":"Title: Web components with vaadin and rollup with svelte: Primary button ignores theme attribute\nTags: vaadin, web-component, svelte, rollup\nSource: Stack Overflow\n\nQuestion:\nMaybe someone tried this before and is able to give me a hint.\nI have used normal svelte setup (mentioned in the main page) which scaffolds the app;\n\n`npx degit sveltejs/template my-svelte-project`\n\nI wanted to use vaadin web components in Svelte. I've installed it;\n\n`npm install @vaadin/vaadin`\n\nthe code of main.ts:\n\n```\n\n import '@vaadin/button/theme/material'\n\n Primary\n Sec\n\n main {\n text-align: center;\n padding: 1em;\n max-width: 240px;\n margin: 0 auto;\n }\n\n @media (min-width: 640px) {\n main {\n max-width: none;\n }\n }\n\n```\n\nAnd the thing is that it almost works :) The buttons are styled, I can click on them but... the theme is ignored;\n\nhttps://i.sstatic.net/ZQBjf.png\n\nThe primary should have a background color like stated in docs;\nhttps://vaadin.com/docs/latest/ds/components/button/#styles\n\nany idea???\n\n========================================\n\nTop Answer:\nYou seem to be importing the Material theme version of the Button component. The \"primary\" theme variant is only available if you use the default Lumo theme. To import that, use `import '@vaadin/button';`\n\nFor the Material theme, you can use the \"outlined\" and \"contained\" theme variants instead: https://cdn.vaadin.com/vaadin-material-styles/1.3.2/demo/buttons.html\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n import '@vaadin/button/theme/material'\n\n</script>\n\n<main>\n <vaadin-button theme=\"primary\">Primary</vaadin-button>\n <vaadin-button theme=\"secondary\">Sec</vaadin-button>\n</main>\n\n<style>\n main {\n text-align: center;\n padding: 1em;\n max-width: 240px;\n margin: 0 auto;\n }\n\n @media (min-width: 640px) {\n main {\n max-width: none;\n }\n }\n</style>\n```\n\n```text\nnpx degit sveltejs/template my-svelte-project\n```\n\n```text\nnpm install @vaadin/vaadin\n```\n\n```html\n<vaadin-button theme=\"primary\">Primary</vaadin-button>\n```\n\n```js\nbutton.theme = \"primary\";\n```\n\n```css\n:host([theme~=\"primary\"]) {\n background-color: var(--_lumo-button-primary-background-color, var(--lumo-primary-color));\n color: var(--_lumo-button-primary-color, var(--lumo-primary-contrast-color));\n font-weight: 600;\n min-width: calc(var(--lumo-button-size) * 2.5);\n}\n```\n\n```svelte\n<script>\n import \"@vaadin/button\";\n\n function setAttributes(node, attributes) {\n for (const [attr, value] of Object.entries(attributes))\n node.setAttribute(attr, value);\n }\n</script>\n\n<main>\n <vaadin-button use:setAttributes={{ theme: \"primary\" }}>Primary</vaadin-button>\n <vaadin-button>Normal</vaadin-button>\n</main>\n```\n\n```text\ntheme\n```\n\n```text\ntheme\n```\n\n```text\nimport '@vaadin/button';\n```\n\n========================================\n\nComments:\n- Reproduced in svelte.dev/repl/428d15b6186b493e8ce952842d3ccc08?version=3.4‌​6.4. Apparently the `theme` attribute is stripped in the final output. If you edit the HTML using dev-tools and add `theme=\"primary\"` manually to your first button, then the button appears styled as intended. I currently have no idea *why* the attribute is being stripped however. Looking at the generated AST output, I can see the attribute is still part of the tree, so the stripping occurs beyond that step. This has nothing to do with the particular theme being applied (my repro example uses the default theme).\n- We've just tried with Vue 3. Same happens. If we set the attribute using devtools as You've described it works for both Svelte and Vue....\n- I tried to use different attributes from other components. They work, except the only one; theme. For example; also has no effect.\n- This is very odd. Considering this happens both in Svelte & Vue, I'm afraid the answer lies directly within the vaadin implementation itself, and has nothing to do with either Svelte or Vue? Just an educated guess...\n- You are right, but the same happens if I set the theme=\"contained\". If I change the import to Lumo, primary still doesn't work. See the first comment to the question.\n- Right, thanks for pointing that out, I was too hasty and didn't read the comments. I see there’s now an open issue for this: github.com/vaadin/web-components/issues/3483","metadata":{"transformedAt":"2026-08-18T18:33:40.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":146,"estimatedTokens":1078}}632{"id":"stack-69057159","source":"stackoverflow","questionId":69057159,"title":"Sveltekit development with workers KV -- hot reloading","tags":["cloudflare","svelte","cloudflare-workers","sveltekit"],"text":"Title: Sveltekit development with workers KV -- hot reloading\nTags: cloudflare, svelte, cloudflare-workers, sveltekit\nSource: Stack Overflow\n\nQuestion:\nIs it possible to use CloudFlare's Workers KV when developing a Svelte/kit application?\n\nIt is possible to build the app then run `wrangler dev` when using the CloudFlare Workers adapter:\n\n```\nnpm build\nwrangler dev\n```\n\nHowever, I haven't gotten hot module reloading working:\n\n```\nnpm dev & wrangler dev\n```\n\n========================================\n\nTop Answer:\nRecent improvements in wrangler and sveltekit mean that the process is now so much easier. For background see the announcement at https://blog.cloudflare.com/blazing-fast-development-with-full-stack-frameworks-and-cloudflare\n\nFor more detail and a working example see this SO answer: https://stackoverflow.com/a/77194403/1129543\n\nThe corresponding example project is https://github.com/sdarnell/cf-svelte/\n\n========================================\n\nCode:\n```sh\nnpm build\nwrangler dev\n```\n\n```text\nnpm dev & wrangler dev\n```\n\n```text\nwrangler dev\n```\n\n```text\nimport { dev } from '$app/env'\nimport redis from 'redis'\n\nconst client = redis.createClient()\nconst get = promisify(client.get).bind(client)\n\nexport const getKvValue = async (key: string): Promise<string | null> => {\n return dev ? await get(key) : await KV.get(key)\n}\n```\n\n```text\nimport { dev } from '$app/env'\n\nconst devKvStore = {}\n\nconst devGetKvValue = (key: string) => {\n return new Promise((resolve) => {\n resolve(devKvStore[key] ?? null)\n })\n}\n\nconst devSetKvValue = (key: string, value: unknown) => {\n return new Promise((resolve) => {\n devKvStore[key] = JSON.stringify(value)\n resolve()\n })\n}\n\nexport const getKvValue = async (key: string): Promise<string | null> => {\n return dev ? await devGetKvValue(key) : await KV.get(key)\n}\n\nexport const setKvValue = async (key: string, value: unknown): Promise<void> => {\n return dev ? await devSetKvValue(key, value) : await KV.put(key, value)\n}\n```\n\n```text\nget\n```\n\n========================================\n\nComments:\n- Really smart workaround. Rich Harris confirmed on Twitter that there is currently no “real” solution for this, so I think this hack is as good as it gets in the interim. The tweet: twitter.com/Rich_Harris/status/1505539552508878849\n- Has someone find out a way to use miniflare instead?\n- @trenta3 Yes, see my answer for how to use miniflare with `npm run dev`","metadata":{"transformedAt":"2026-08-18T18:33:40.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":94,"estimatedTokens":613}}633{"id":"stack-43101214","source":"stackoverflow","questionId":43101214,"title":"Use getters/setters in Svelte Custom methods","tags":["javascript","svelte"],"text":"Title: Use getters/setters in Svelte Custom methods\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI am not able to compile my svelte component when using a get/set pair in custom methods. Is this not supported? Or am I doing something wrong?\n\nExample:\n\nSay I wanted to have a component that displays a name and I want to set the name using.\n`com.name = 'The new name';`\n\nHowever I only want the component to use the name if it has no spaces in the name.\n\n```\n\n### Hello {{name}}!\n\n export default {\n data () {\n return {\n name: 'The Name',\n }\n },\n methods: {\n get displayName() {\n return this.get('name'); \n },\n set displayName(val) {\n if (val.indexOf(' ') \n```\n\nThe Issue is that when I try to compile this, it says there is a duplicate key. \n\n```\nDuplicate property 'displayName'\n\n 49: return this.get('name');\n 50: },\n 51: set displayName(val) {\n```\n\nHere is a REPL - https://svelte.technology/repl?version=1.13.2&gist=0eeab5717526694139ba73eae766bb30\n\nI don't see anything in the documentation about this. I can just not use setters, but I would like to be able to.\n\n========================================\n\nTop Answer:\n**Edit:** As Rich Harris pointed out in the comments below, getters and setters won't work within `data` because Svelte copies the properties to a plain JS object internally (thus ignoring getters and setters). I think the next best thing you can do is make a method `name` that can be called like `name()` as a getter, and `name(value)` as a setter.\n\n### Svelte Code:\n\n```\n\n### Hello {{_name}}!\n\n export default {\n data() {\n return {\n _name: 'The Name'\n }\n },\n methods: {\n name(value) {\n if (value === void 0) return this.get('_name')\n this.set('_name', value)\n }\n }\n }\n\n```\n\n**Original Post:**\n\nYour getter and setter should be in your `data` rather than your `methods`, because they create a property in the end. This property conflicts with the `name` you defined as equal to `'The Name'` inside your original `data` method. I would suggest using a \"private\" property `_name` instead.\n\n### Svelte Code (REPL):\n\n```\n\n### Hello {{name}}!\n\n export default {\n data() {\n return {\n _name: 'The Name',\n get name() {\n return this._name\n },\n set name(value) {\n / /.test(this._name) || (this._name = value)\n }\n }\n }\n }\n\n```\n\n========================================\n\nCode:\n```text\n<h1>Hello {{name}}!</h1>\n\n<script>\n export default {\n data () {\n return {\n name: 'The Name',\n }\n },\n methods: {\n get displayName() {\n return this.get('name'); \n },\n set displayName(val) {\n if (val.indexOf(' ') < 0) {\n this.set('name', val);\n }\n }\n }\n }\n</script>\n```\n\n```text\nDuplicate property 'displayName'\n\n 49: return this.get('name');\n 50: },\n 51: set displayName(val) {\n```\n\n```text\ncom.name = 'The new name';\n```\n\n```js\nfunction wrap (component) {\n var wrapper = {};\n var data = component.get();\n\n Object.keys(data).forEach(key => {\n Object.defineProperty(wrapper, key, {\n get() {\n return component.get()[key];\n },\n set(value) {\n component.set({ obj[key]: value });\n }\n })\n });\n\n return wrapper;\n}\n\nvar component = new Component({...});\nvar wrapper = wrap(component);\n\nwrapper.name = 'Rich';\n```\n\n```text\nmethods\n```\n\n```text\ndata\n```\n\n```text\ndata\n```\n\n```text\ndata\n```\n\n```text\ncomponent.data = wrap(component)\n```\n\n```text\ncomponent.data.name\n```\n\n```text\n<h1>Hello {{_name}}!</h1>\n\n<script>\n export default {\n data() {\n return {\n _name: 'The Name'\n }\n },\n methods: {\n name(value) {\n if (value === void 0) return this.get('_name')\n this.set('_name', value)\n }\n }\n }\n</script>\n```\n\n```text\n<h1>Hello {{name}}!</h1>\n\n<script>\n export default {\n data() {\n return {\n _name: 'The Name',\n get name() {\n return this._name\n },\n set name(value) {\n / /.test(this._name) || (this._name = value)\n }\n }\n }\n }\n</script>\n```\n\n```text\ndata\n```\n\n```text\nname\n```\n\n```text\nname()\n```\n\n```text\nname(value)\n```\n\n```text\ndata\n```\n\n```text\nmethods\n```\n\n```text\nname\n```\n\n```text\n'The Name'\n```\n\n```text\ndata\n```\n\n```text\n_name\n```\n\n========================================\n\nComments:\n- It is still an issue event if you change the property name in the data section. It seems like it is conflicting with the getter. I changed the `name` in data to `displayName`. The same issue arises.\n- The problem is that you didn't move the getter and setter away from `methods` and into `data`. Try doing that, and let me know what happens.\n- Using accessors in the `data` function won't work, because the state object that Svelte components use internally are POJOs generated by combining the return value of the `data` function, any `data` supplied at instantiation, and a component's computed values (if it has any). In other words, the accessor will only be used once, at instantiation, then ignored.\n- Oh, yuck. That's unfortunate. Thank you for enlightening me about Svelte's internals. I guess OP will, unfortunately, have to use another approach.\n- @RichHarris So I suppose a get function is not needed since you can use `.get('name')` on the component. Would making a `setName` custom method be the way to go?\n- @Zac Just edited the post with an alternative. Let me know what you think; I think this is your next best option though it is hardly ideal.\n- @gyre I believe that in the methods section you would need to use `this.set('_name', value);`\n- This would also not be the same as a get/set property. A set would look like `com.name('new name')`, not `com.name = 'new name'`. Thanks for the suggestions.\n- Unfortunately, I don't think accessors will work based on what Rich Harris mentioned earlier. I thought this would be the second-best bet.\n- I have a solution involving a wrapper object — will post a new answer in a moment. Demo here: svelte-accessors-cmpbzhrlcp.now.sh\n- Impressive! Hopefully that will work and I can delete this post.\n- Thank you for investigating and prompting me to think about how to make this work! :)\n- I was very mislead by the error. Thanks for coming up with this solution, I think it will come in handy!","metadata":{"transformedAt":"2026-08-18T18:33:40.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":283,"estimatedTokens":1581}}634{"id":"stack-67760803","source":"stackoverflow","questionId":67760803,"title":"Write the content of a text file line by line with Svelte","tags":["svelte"],"text":"Title: Write the content of a text file line by line with Svelte\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\ni wrote this code in svelte that open a txt file, and write it in a html paragraph. This is the code:\n\n```\n\n{#if files}\n \n\n### Files selected:\n\n{#each Array.from(files) as file}\n IThe imported file is: {file.name}\n\n{#await file.text() then text}\n{text}\n\n{/await}\n{/each}\n{/if}\n```\n\nand the example file is like this:\n\n```\nbeans\nspam\ndonut\n```\n\nbut it gives me this:\n\n```\nbeans spam donut\n```\n\nhow can I create a new line (paragraph or `\n`) for each line in the text?\n\n========================================\n\nCode:\n```text\n<input type='file' multiple bind:files'>\n\n{#if files}\n <h2>Files selected: </h2>\n{#each Array.from(files) as file}\n<p> IThe imported file is: {file.name}</p>\n{#await file.text() then text}\n<p>{text}</p>\n{/await}\n{/each}\n{/if}\n```\n\n```text\nbeans\nspam\ndonut\n```\n\n```text\nbeans spam donut\n```\n\n```text\n<br>\n```\n\n```text\n<script>\n let files;\n</script>\n\n<input type='file' multiple bind:files />\n\n{#if files}\n <h2>Files selected: </h2>\n{#each Array.from(files) as file}\n<p> IThe imported file is: {file.name}</p>\n{#await file.text() then text}\n{#each text.split('\\n') as line }\n<p>{line}</p>\n{/each}\n{/await}\n{/each}\n{/if}\n```\n\n========================================\n\nComments:\n- Why not use CSS `white-space: pre-wrap;`?\n- It worked, thank you! I'm just learning svelte and yeah, i think i will study more\n- Same here. I am just getting to grips with it, but I am already loving it when compared to React Vue or Angular it seems to be way simpler and faster. BTW I recommend you checkout sveltekit (replacement for Sapper) as it comes with a nice template for larger projects.","metadata":{"transformedAt":"2026-08-18T18:33:40.706Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":99,"estimatedTokens":430}}635{"id":"stack-59142472","source":"stackoverflow","questionId":59142472,"title":"How can I force the svelte compiler to include a style rule?","tags":["svelte","sapper"],"text":"Title: How can I force the svelte compiler to include a style rule?\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI'm trying to pass an additional class to a component through a custom property but the compiler detects that the class is not in use and does not include it. Given this component:\n\n```\n\n import {createEventDispatcher} from 'svelte';\n\n const dispatch = createEventDispatcher();\n\n export let imageUrl = null;\n export let cssClass = '';\n export let data = null;\n\n function handleImageClick(e){\n dispatch('press', {element:this, event: e, props: $$props });\n }\n\n .image-button{\n width:100px;\n height: 72px;\n }\n\n```\n\nI create an instance like this and pass it my additional class through the cssClass prop:\n\n```\n\n import ImageButton from './components/ImageButton.svelte';\n\n let imgUrl = \"/images/test.png\";\n\n .my-image-button{\n border: 1px solid white;\n }\n\n```\n\nThe ImageButton instance is created and it has the additional \"my-image-button\" class but the style rule I declared in .my-image-button is not included. Is there a way to force the compiler to include a style rule or another workflow to enable this functionality?\n\n========================================\n\nCode:\n```text\n<script>\n import {createEventDispatcher} from 'svelte';\n\n const dispatch = createEventDispatcher();\n\n export let imageUrl = null;\n export let cssClass = '';\n export let data = null;\n\n function handleImageClick(e){\n dispatch('press', {element:this, event: e, props: $$props });\n }\n</script>\n<style>\n .image-button{\n width:100px;\n height: 72px;\n }\n</style>\n\n<div class=\"image-button {cssClass}\" on:click={handleImageClick} style=\"background:url({imageUrl});background-size: cover;\"></div>\n```\n\n```text\n<script>\n import ImageButton from './components/ImageButton.svelte';\n\n let imgUrl = \"/images/test.png\";\n</script>\n<style>\n .my-image-button{\n border: 1px solid white;\n }\n</style>\n<ImageButton imageUrl={imgUrl} cssClass=\"my-image-button\" />\n```\n\n```html\n<div>\n <ImageButton .../>\n</div>\n\n<style>\n div :global(.my-image-button) {\n /* ... */\n }\n</style>\n```\n\n```text\n.my-image-button\n```\n\n```text\n:global(.my-image-button)\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.706Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":104,"estimatedTokens":549}}636{"id":"stack-63006017","source":"stackoverflow","questionId":63006017,"title":"Svelte framework: environment variables not appearing in svelte app","tags":["javascript","environment-variables","svelte","rollupjs"],"text":"Title: Svelte framework: environment variables not appearing in svelte app\nTags: javascript, environment-variables, svelte, rollupjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use environment variables in my svelte app. I've installed `@Rollup/plugin-replace` and `dotenv`. I created a `.env` file to hold my `API_KEY` and added the following to `plugins` in `rollup.config.js` from this Medium article:\n\n```\nplugins: [\n replace({\n __myapp: JSON.stringify({\n env: {\n isProd: production,\n API_URL : process.env.API_URL\n }\n }),\n }),\n]\n```\n\nand in the svelte components of my app I would access my API key via\n\n```\nconst apiUrl = __myapp.env.API_URL\n```\n\nwhich worked. However, a few days later I was having authentication issues and after some debugging I found that `__myapp.env.API_URL` was returning `undefined` by trying to print it to the console.\n\nI then tried changing the `replace` call to just `replace({'API_KEY': process.env.API_KEY})` and `console.log(API_KEY)` was still displaying `undefined`. I tested `replace` by trying to use it replace some variable with some string and it worked so that confirms that rollup is working fine. So, I suspect the problem is in `process.env.API_KEY` but I'm not sure. What might I be doing wrong with my attempts to access my environment variables?\n\n(Some background: I am using sveltejs/template as a template to build my app)\n\n========================================\n\nCode:\n```text\nplugins: [\n replace({\n __myapp: JSON.stringify({\n env: {\n isProd: production,\n API_URL : process.env.API_URL\n }\n }),\n }),\n]\n```\n\n```text\nconst apiUrl = __myapp.env.API_URL\n```\n\n```text\n@Rollup/plugin-replace\n```\n\n```text\ndotenv\n```\n\n```text\n.env\n```\n\n```text\nAPI_KEY\n```\n\n```text\nplugins\n```\n\n```text\nrollup.config.js\n```\n\n```text\n__myapp.env.API_URL\n```\n\n```text\nundefined\n```\n\n```text\nreplace\n```\n\n```text\nreplace({'API_KEY': process.env.API_KEY})\n```\n\n```text\nconsole.log(API_KEY)\n```\n\n```text\nundefined\n```\n\n```text\nreplace\n```\n\n```text\nprocess.env.API_KEY\n```\n\n```text\nimport { config as configDotenv } from 'dotenv';\nimport replace from '@rollup/plugin-replace';\n\nconfigDotenv();\n\nexport default {\n input: 'src/main.js',\n ...\n plugins: [\n replace({\n __myapp: JSON.stringify({\n env: {\n isProd: production,\n API_URL: process.env.API_URL,\n },\n }),\n }),\n svelte({ ... })\n ]\n}\n```\n\n```text\ndotenv\n```\n\n```text\n.env\n```\n\n```text\nconfig\n```\n\n```text\nprocess.env.API_KEY\n```\n\n```text\nrollup.config.js\n```\n\n========================================\n\nComments:\n- i'm not familiar with svelte but gonna take a wild guess that maybe you only need to stringify the env variable values. so something like: `__myapp: { env: { isProd: JSON.stringify('production') } }`\n- @duxfox-- Hmm, just gave that a shot but did not work. Thank you for your response.\n- production is not defined in rollup.config.js","metadata":{"transformedAt":"2026-08-18T18:33:40.706Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":157,"estimatedTokens":730}}637{"id":"stack-66239213","source":"stackoverflow","questionId":66239213,"title":"svelte - reading json file from local folder","tags":["json","svelte","rollup"],"text":"Title: svelte - reading json file from local folder\nTags: json, svelte, rollup\nSource: Stack Overflow\n\nQuestion:\nMy `svelte` app is required to read `json` file from the public folder.\nI followed exactly the `rollup` setup from this link, then add `json` to my `app.svelte`:\n\n```\nimport * as port from '/port.json';\n```\n\n`port.json` is located at the public folder together with `index.html`.\nBut I keep getting this error:\n\nmain.js:11 Uncaught ReferenceError: port is not defined at main.js:11\n\nand I am getting this message from `Terminal` which I am not sure what it means:\n\n(!) Missing global variable name Use output.globals to specify browser\nglobal variable names corresponding to external modules /port.json\n(guessing 'port')\n\nHow can I resolve this?\n\n========================================\n\nTop Answer:\nExport the object and rename the file from `.json` to `.json.js`.\n\nport.json.js\n\n```\nexport let myJson = {\n name: \"hello world\"\n}\n```\n\nComponent:\n\n```\n\n import json from './port.json';\n\n \n {JSON.stringify(json)}\n\n```\n\n========================================\n\nCode:\n```text\nimport * as port from '/port.json';\n```\n\n```text\nsvelte\n```\n\n```text\njson\n```\n\n```text\nrollup\n```\n\n```text\njson\n```\n\n```text\napp.svelte\n```\n\n```text\nport.json\n```\n\n```text\nindex.html\n```\n\n```text\nTerminal\n```\n\n```text\n<script>\n import json from './port.json';\n</script>\n\n<p>{JSON.stringify(json)}</p>\n```\n\n```text\n<script>\n let fetchJson = fetch('port.json').then(res => res.json());\n</script>\n\n{#await fetchJson}\n <p>Loading JSON</p>\n{:then result}\n <p>{JSON.stringify(result)}</p>\n{/await}\n```\n\n```text\nsrc/\n```\n\n```text\n@rollup/plugin-json\n```\n\n```text\npublic/\n```\n\n```text\nexport let myJson = {\n name: \"hello world\"\n}\n```\n\n```text\n<script>\n import json from './port.json';\n</script>\n\n \n <p>{JSON.stringify(json)}</p>\n```\n\n```text\n.json\n```\n\n```text\n.json.js\n```\n\n========================================\n\nComments:\n- if the file is located in public, why not use fetch() with the relative path to the json file to read it then parse","metadata":{"transformedAt":"2026-08-18T18:33:40.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":147,"estimatedTokens":512}}638{"id":"stack-65664514","source":"stackoverflow","questionId":65664514,"title":"Svelte - how to wait for data that is being passed in from parent component?","tags":["javascript","svelte","svelte-component"],"text":"Title: Svelte - how to wait for data that is being passed in from parent component?\nTags: javascript, svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI'm learning Svelte and I want to use data from one JSON API in three components. The data looks like this:\n\n```\n{\n \"stats\": {\n \"currentYear\": {\n \"total\": 6,\n \"success\": 6\n },\n \"thirty\": {\n \"total\": 30,\n \"success\": 28\n },\n \"hundred\": {\n \"total\": 100,\n \"success\": 92\n },\n \"allTime\": {\n \"total\": 789,\n \"success\": 728\n }\n },\n \"heatmap\": {\n ...\n },\n \"other\": {\n ...\n }\n}\n```\n\nI retrieve the data via `onMount` in the `App.svelte` main component via async fetch, this works well. Then I want to pass each object to its corresponding component, so the `stats` object gets passed to `Stats.svelte`, the `heatmap` object to `Heatmap.svelte` etc.\n\nTo illustrate my issue, in `Stats.svelte` I am trying to display percentage values for each time period, for example:\n\n- current year: 100%\n\n- last thirty days: 93%\n\n- last 100 days: 92%\n\n- all time: 92%\n\nAlso, the CSS class for each will be based on some threshold values to change the colour (x >= 95: green, 95 > x >= 90: yellow, x So some basic computation is needed which I wanted to have in a generic function, like shown below.\n\nThe `stats` object does get passed in from the parent component `App.svelte`, and if all I wanted to do is to show its values in the HTML via the `{#await}` block, this would work fine. However, I want to do some calculations, so I wanted to call a function that would use the `stats` object's data, but I do not know how to call this function at the right moment. Calling it on `onMount` does not work, because it's too early, the data coming in from the parent component has not yet been received.\n\n```\n\n import { onMount } from \"svelte\"\n \n export let stats\n\n let currentYearClass, currentYearStat\n\n const calcPercentage = async (period) => {\n currentYearStat = stats[period].currentYearSuccess * 100 / stats[period].currentYearTotal\n currentYearClass = 'green'\n }\n\n onMount( async () => {\n calcPercentage('currentYear')\n })\n\n{#await stats}\n Waiting for stats ...\n{:then stats}\n {currentYearStat}\n ...\n ...\n{/await}\n\n```\n\n========================================\n\nTop Answer:\nYou didn't show how `stats` is passed down to this component, but we can extrapolate two problems from your original solution:\n\n- The `stats` prop isn't passed in right away, therefore `stats` is `undefined` during `onMount`.\n\n- `onMount` is only executed when a component is mounted to the DOM (see documentation). If `stats` changes during the lifetime of the component `calcPercentage` will not be rerun.\n\nYou're looking for a way to run `calcPercentage` *every time* `stats` changes. You should use a reactive statement for this:\n\n```\n$: if (stats) calcPercentage('currentYear')\n```\n\nThis reactive statement will run *every time* `stats` changes.\n\nThe `if` ensures that `calcPercentage` only runs if `stats` has a truthy value. `undefined` is *falsy*, so `calcPercentage` will not run as long as `stats` is `undefined`.\n\nA more elegant (but less resilient) approach would be to only render your `Stats` component after the data has been loaded using `{#await}`, as described by @Ayoub Fiad's answer.\n\nPlease note that the Svelte compiler does **not** know that `calcPercentage` depends on `stats`, only values which directly appear within the reactive statement will become dependencies. In this case it knows to rerun when `stats` changes because `stats` is used directly in the `if`-block. The alternative for situations where you don't need such an `if` is to make `calcPercentage` take `stats` as a parameter, as described in @Stephane Vanraes' answer.\n\n========================================\n\nCode:\n```json\n{\n \"stats\": {\n \"currentYear\": {\n \"total\": 6,\n \"success\": 6\n },\n \"thirty\": {\n \"total\": 30,\n \"success\": 28\n },\n \"hundred\": {\n \"total\": 100,\n \"success\": 92\n },\n \"allTime\": {\n \"total\": 789,\n \"success\": 728\n }\n },\n \"heatmap\": {\n ...\n },\n \"other\": {\n ...\n }\n}\n```\n\n```text\n<script>\n import { onMount } from \"svelte\"\n \n export let stats\n\n let currentYearClass, currentYearStat\n\n const calcPercentage = async (period) => {\n currentYearStat = stats[period].currentYearSuccess * 100 / stats[period].currentYearTotal\n currentYearClass = 'green'\n }\n\n onMount( async () => {\n calcPercentage('currentYear')\n })\n</script>\n<div id=\"stats\">\n{#await stats}\n <div>Waiting for stats ...</div>\n{:then stats}\n <div class=\"{currentYearClass}\" id=\"currentYear\">{currentYearStat}</div>\n ...\n ...\n{/await}\n</div>\n```\n\n```text\nonMount\n```\n\n```text\nApp.svelte\n```\n\n```text\nstats\n```\n\n```text\nStats.svelte\n```\n\n```text\nheatmap\n```\n\n```text\nHeatmap.svelte\n```\n\n```text\nStats.svelte\n```\n\n```text\nstats\n```\n\n```text\nApp.svelte\n```\n\n```text\n{#await}\n```\n\n```text\nstats\n```\n\n```text\nonMount\n```\n\n```js\nexport let stats\nlet currentYearClass, currentYearStat\n\nconst calcPercentage = (stats, period) => {\n currentYearStat = stats[persion}......\n currentYearClass = 'green'\n}\n\n$: stats && calcPercentage(stats, 'currentYear')\n```\n\n```js\n$: stats && calcPercentage(stats, 'currentYear')\n```\n\n```js\n$: myfunction(myvar)\n```\n\n```js\nimport heavyCalc from 'heavy/calc/function`\n\n$: value = heavyCalc(otherValue)\n```\n\n```text\ncalcPercentage\n```\n\n```text\nstats\n```\n\n```js\n$: if (stats) calcPercentage('currentYear')\n```\n\n```text\nstats\n```\n\n```text\nstats\n```\n\n```text\nstats\n```\n\n```text\nundefined\n```\n\n```text\nonMount\n```\n\n```text\nonMount\n```\n\n```text\nstats\n```\n\n```text\ncalcPercentage\n```\n\n```text\ncalcPercentage\n```\n\n```text\nstats\n```\n\n```text\nstats\n```\n\n```text\nif\n```\n\n```text\ncalcPercentage\n```\n\n```text\nstats\n```\n\n```text\nundefined\n```\n\n```text\ncalcPercentage\n```\n\n```text\nstats\n```\n\n```text\nundefined\n```\n\n```text\nStats\n```\n\n```text\n{#await}\n```\n\n```text\ncalcPercentage\n```\n\n```text\nstats\n```\n\n```text\nstats\n```\n\n```text\nstats\n```\n\n```text\nif\n```\n\n```text\nif\n```\n\n```text\ncalcPercentage\n```\n\n```text\nstats\n```\n\n```html\n{#await promise}\n\n <div>Loading...<div>\n\n{:then stats}\n\n <Stats {stats} />\n\n{/await}\n```\n\n```text\nStats.svelte\n```\n\n```text\n{#await}\n```\n\n```text\nApp.svelte\n```\n\n```text\nStats.svelte\n```\n\n========================================\n\nComments:\n- This approach makes a lot of sense! OP should also make sure that `calcPercentage` is called reactively (`$:`) as well to make sure things are recalculated when `stats` changes.","metadata":{"transformedAt":"2026-08-18T18:33:40.707Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":54,"totalLines":392,"estimatedTokens":1619}}639{"id":"stack-58768701","source":"stackoverflow","questionId":58768701,"title":"Sapper: How do I fix `parentNode is null` when navigating away from a page with kwes.io form?","tags":["svelte","sapper"],"text":"Title: Sapper: How do I fix `parentNode is null` when navigating away from a page with kwes.io form?\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI'm creating a contact form using kwes.io inside SapperJS. The form itself works.\n\nBut once I land on the contact page I cannot navigate away from it using Sapper links, but normal https links work. \n\nThe URL in browser changes, but the content doesn't load. Then to load the content I have to reload the page.\n\nI contacted the support team from Kwes, but they say it has something to do with the way Sapper handles routing and can't help.\n\nI created my form like this\n\n```\n\n \n\n \n Your Name\n \n Submit\n \n\n```\n\nOn Chrome browser console it prints \n\n`Uncaught (in promise) TypeError: Cannot read property 'removeChild' of null`\n\nand on Firefox console this\n\n`TypeError: t.parentNode is null`\n\n========================================\n\nCode:\n```html\n<svelte:head>\n <script src=\"https://kwes.io/js/kwes.js\"></script>\n</svelte:head>\n\n\n<div class=\"kwes-form\">\n <form method=\"POST\" action=\"https://kwes.io/api/foreign/forms/YOUR_FORM_KEY\">\n <label for=\"name\">Your Name</label>\n <input type=\"text\" name=\"name\">\n <button type=\"submit\">Submit</button>\n </form>\n</div>\n```\n\n```text\nUncaught (in promise) TypeError: Cannot read property 'removeChild' of null\n```\n\n```text\nTypeError: t.parentNode is null\n```\n\n```js\nfunction detach(node) {\n if (!node.parentNode) debugger; // added breakpoint\n node.parentNode.removeChild(node);\n}\n```\n\n```text\n{#if condition}\n <span class=\"fa fa-check\"/>\n{/if}\n```\n\n```text\n{#if condition}\n <span>\n <span class=\"fa fa-check\"/>\n </span>\n{/if}\n```\n\n```text\n<svg>\n```\n\n========================================\n\nComments:\n- I'm still getting this error with standalone Svelte 3.20.1, this allowed me to add a workaround, so thanks!","metadata":{"transformedAt":"2026-08-18T18:33:40.707Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":90,"estimatedTokens":461}}640{"id":"stack-58115225","source":"stackoverflow","questionId":58115225,"title":"How to stop Sapper from scrolling back to top in nested routes?","tags":["scroll","svelte","sapper"],"text":"Title: How to stop Sapper from scrolling back to top in nested routes?\nTags: scroll, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nThe thing is that I have two routes\n`/istifta` and `/istifta/edit`\n\nThe `/istifta` route displays istiftas (questions) while `/istifta/edit` route opens up a panel for editing questions on the same page due to same `_layout.svelte` file.\n\nThe only problem is that when I access `/istifta/edit` from `/istifta`. It not only opens up the editing panel but also scrolls to the top of page. How can I stop this behavior? I want to remain on the same scroll position upon this navigation. The istiftas is a long list. For editing it should remain on the same scroll position. Scrolling to bottom again and again and finding ids is overly complicated for the user.\n\nPlease solve this. Specially, **Rich Harris**, if you are reading this.\n\n========================================\n\nTop Answer:\n\"sapper\": \"^0.27.9\"\n\nsapper-noscroll not working for me\n\nblogs\nblogs/index.svelte\n\n```\nGo to Blog 1\nGo to Blog 2\nGo to Blog 3\nGo to Blog 4\n...\n...\nGo to Blog 100\n```\n\nblogs/[slug].svelte\n\n```\nGo Back to Blogs\n Blog details\n```\n\nstill it scrolls to the top when I go back to Blogs page from Blog Details page. Am I missing something?\n\n========================================\n\nCode:\n```text\n/istifta\n```\n\n```text\n/istifta/edit\n```\n\n```text\n/istifta\n```\n\n```text\n/istifta/edit\n```\n\n```text\n_layout.svelte\n```\n\n```text\n/istifta/edit\n```\n\n```text\n/istifta\n```\n\n```html\n<!-- in src/routes/istifta/index.svelte -->\n<a href=\"istifta/edit\" sapper-noscroll>edit</a>\n```\n\n```text\nsapper-noscroll\n```\n\n```text\n<a>\n```\n\n```text\n<a sapper-noscroll href=\"blogs/1\">Go to Blog 1</a>\n<a sapper-noscroll href=\"blogs/2\">Go to Blog 2</a>\n<a sapper-noscroll href=\"blogs/3\">Go to Blog 3</a>\n<a sapper-noscroll href=\"blogs/4\">Go to Blog 4</a>\n...\n...\n<a sapper-noscroll href=\"blogs/100\">Go to Blog 100</a>\n```\n\n```text\n<a href=\"blogs\">Go Back to Blogs </a>\n<h1> Blog details<h1>\n```\n\n```text\nsapper-noscroll\n```\n\n```text\nsapper:noscroll\n```\n\n```text\n<a href=\"path\" data-sveltekit-noscroll>Path</a>\n```\n\n========================================\n\nComments:\n- Extremely Helpful.\n- Hi, sapper-noscroll not working for me.. I have provided my usage below.. Am I missing something?","metadata":{"transformedAt":"2026-08-18T18:33:40.707Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":119,"estimatedTokens":569}}641{"id":"stack-49077362","source":"stackoverflow","questionId":49077362,"title":"I have some questions about Sapper/Svelte","tags":["javascript","node.js","angular","frameworks","svelte"],"text":"Title: I have some questions about Sapper/Svelte\nTags: javascript, node.js, angular, frameworks, svelte\nSource: Stack Overflow\n\nQuestion:\nI just started using Sapper (https://sapper.svelte.technology) for the first time. I really like it so far. One of the things I need it to do is show a list of the components available in my application and show information about them. Ideally have a way to change the way the component looks based on dynamic bindings on the page.\n\nI have a few questions about using the framework.\n\nFirst, I'll provide a snippet of my code, and then a screenshot:\n\n```\n[slug].html\n-----------\n\n{{info.title}}\n\n \n\n### {{info.title}}\n\n \n \n \n\n \n\n### Attributes\n\n {{#each Object.keys(info.attributes) as attribute}}\n {{info.attributes[attribute].description}} \n\n {{/each}}\n \n\nimport Layout from '../_components/components/Layout.html';\nimport TopBar from '../../_components/header/TopBar.html';\n\nlet COMPONENTS = require('../_config/components.json');\n\nexport default {\n components: {\n Layout, TopBar\n },\n\n methods: {\n updateComponent(value) {\n this.set({organization_name: value});\n }\n },\n\n data() {\n return {\n organization_name: 'Org Name'\n }\n },\n\n preload({ params, query }) {\n\n params['info'] = COMPONENTS.components[params.slug];\n\n return params;\n }\n\n};\n\n```\n\n### https://i.sstatic.net/iOGA9.png\n\n**Now my questions:**\n\nI notice I can't `#each` through my object. I have to loop through its keys. Would be nice if I could do something like this:\n\n{{#each info.attributes as attribute }}\n\n`{{attribute.description}}`\n\n{{/each}}\n\nBefore Sapper, I would use Angular-translate module that could do translations on strings based on a given JSON file. Does anyone know if a Sapper/Svelte equivalent exists, or is that something I might need to come up with on my own?\n\nI'm not used to doing imports. I'm more use to dependency injection in Angular which looks a bit cleaner (no paths). Is there some way I can create a `COMPONENTS` constant that could be used throughout my files, or will I need to import a JSON file in every occurence that I need access to its data?\n\nAs a -up to #3, I wonder if there is a way to better include files instead of having to rely on using `../..` to navigate through my folder structure? If I were to change the path of one of my files, my Terminal will complain and give errors which is nice, but still, I wonder if there is a better way to import my files.\n\nI know there has got to be a better way to implement what I implemented in my example. Basically, you see an input box beside an attribute, and if I make changes there, I am calling an `updateComponent` function which then does a `this.set()` in the current scope to override the binding. This works, but I was wondering if there was some way to avoid the function. I figured it's possible that you can bind the value of the input and have it automatically update my `` component binding... maybe?\n\nThe `preload` method gives me access to `params`. What I want to know if there is some way for me to get access to `params.slug` without the preload function.\n\nWhat would be really cool is to have some expert rewrite what I've done in the best possible way, possibly addressing some of my questions.\n\n========================================\n\nCode:\n```text\n[slug].html\n-----------\n\n<:Head>\n<title>{{info.title}}</title>\n</:Head>\n\n<Layout page=\"{{slug}}\">\n <h1>{{info.title}}</h1>\n\n <div class=\"content\">\n <TopBar :organization_name />\n <br>\n <h3>Attributes</h3>\n {{#each Object.keys(info.attributes) as attribute}}\n <p>{{info.attributes[attribute].description}} <input type=\"text\" on:keyup=\"updateComponent(this.value)\" value=\"Org Name\" /></p>\n {{/each}}\n </div>\n</Layout>\n\n<script>\nimport Layout from '../_components/components/Layout.html';\nimport TopBar from '../../_components/header/TopBar.html';\n\nlet COMPONENTS = require('../_config/components.json');\n\nexport default {\n components: {\n Layout, TopBar\n },\n\n methods: {\n updateComponent(value) {\n this.set({organization_name: value});\n }\n },\n\n data() {\n return {\n organization_name: 'Org Name'\n }\n },\n\n preload({ params, query }) {\n\n params['info'] = COMPONENTS.components[params.slug];\n\n return params;\n }\n\n};\n</script>\n```\n\n```text\n#each\n```\n\n```text\n{{attribute.description}}\n```\n\n```text\nCOMPONENTS\n```\n\n```text\n../..\n```\n\n```text\nupdateComponent\n```\n\n```text\nthis.set()\n```\n\n```text\n<TopBar>\n```\n\n```text\npreload\n```\n\n```text\nparams\n```\n\n```text\nparams.slug\n```\n\n```html\n{{#each Object.values(info.attributes) as attr}}\n <p>{{attr.description}} ...</p>\n{{/each}}\n\n<!-- or, if you need the key as well -->\n{{#each Object.entries(info.attributes) as [key, value]}}\n <p>{{attr.description}} ...</p>\n{{/each}}\n```\n\n```js\npreload({ params, query }) {\n return fetch(`/i18n/${locale}.json`)\n .then(r => r.json())\n .then(dict => {\n return { dict };\n });\n}\n```\n\n```js\n// app/client.js (assuming Sapper >= 0.7)\nimport COMPONENTS from './config/components.json';\nwindow.COMPONENTS = COMPONENTS;\n\n// app/server.js\nimport COMPONENTS from './config/components.json';\nglobal.COMPONENTS = COMPONENTS;\n```\n\n```js\n{{#each Object.values(info.attributes) as attr}}\n <p>{{attr.description}} <input bind:value=organization_name /></p>\n{{/each}}\n```\n\n```text\npreload\n```\n\n```text\n{{dict[\"hello\"]}}\n```\n\n```text\nresolve.modules\n```\n\n```text\nparams\n```\n\n```text\nroutes/whatever/[slug].html\n```\n\n```text\n{{params.slug}}\n```\n\n```text\nthis.get('params').slug\n```\n\n```text\npreload\n```\n\n========================================\n\nComments:\n- Thanks so much for your answer. Would you recommend github.com/sveltejs/svelte/issues as the place to go for any of my future questions?\n- Stack Overflow is the right place for questions like these - we prefer to keep the issue tracker focused on bugs and feature discussions\n- Hi, is point #6 still valid? For some reason, I'm getting error about `params` not being defined in my component.\n- It's not. Do `import { stores } from '@sapper/app'; const { page } = stores();` if you want to access params as `$page.params`, or grab them from the preload function","metadata":{"transformedAt":"2026-08-18T18:33:40.707Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":266,"estimatedTokens":1544}}642{"id":"stack-74053094","source":"stackoverflow","questionId":74053094,"title":"How To upload Sveltekit multiple files","tags":["javascript","svelte","sveltekit"],"text":"Title: How To upload Sveltekit multiple files\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nIn new svelteKit i cant upload multiple files with form multipart/form-data and multiple attribute\n\n+page.svelte\n\n```\n\n```\n\n+page.server.js\n\n```\nexport const actions = {\n add: async ({ request, files }) => {\n const data = await request.formData()\n \n const file = data.get('file')\n\n let filename\n\n try {\n\n if (file) {\n\n const ext = file.name.split('.').pop()\n filename = userName + '-' +Date.now().toString() + '.' + ext\n \n let ab = await file.arrayBuffer()\n console.log(Array.from(ab));\n\n writeFileSync(`static/img/${filename}`, Buffer.from(ab, (e) => {\n console.log(e)\n }))\n }\n\n return { success: true }\n\n } catch (e) {\n console.log(e);\n return { success: false };\n\n }\n }\n}\n```\n\nThis code upload only one file. How can I get an array of files?\n\n========================================\n\nCode:\n```text\n<form\n action=\"?/add\"\n method=\"post\"\n enctype=\"multipart/form-data\"\n >\n<input\n multiple\n type=\"file\"\n name=\"file\"\n id=\"file\"\n accept=\"image/*\"\n />\n```\n\n```text\nexport const actions = {\n add: async ({ request, files }) => {\n const data = await request.formData()\n \n const file = data.get('file')\n\n let filename\n\n try {\n\n if (file) {\n\n const ext = file.name.split('.').pop()\n filename = userName + '-' +Date.now().toString() + '.' + ext\n \n let ab = await file.arrayBuffer()\n console.log(Array.from(ab));\n\n writeFileSync(`static/img/${filename}`, Buffer.from(ab, (e) => {\n console.log(e)\n }))\n }\n\n\n return { success: true }\n\n\n } catch (e) {\n console.log(e);\n return { success: false };\n\n }\n }\n}\n```\n\n```js\nconst data = await request.formData();\nconst files = data.getAll('file');\n```\n\n```text\ngetAll\n```\n\n========================================\n\nComments:\n- Hi @pgs, I am trying something similar. However, I get `file.arrayBuffer is not a function` with `formData = await request.formData(); const file = formData.get(`csvFile`)`. The file object does not have an array buffer method.\n- @sryscad `const data = await request.formData()` > `const file = data.get('file')` > `if (file instanceof Blob && file.size) {}` > `const imageData = new Uint8Array(await file.arrayBuffer())` > `await fs.promises.writeFile(`src/images/test.jpg`, imageData)` nodejs.org/api/all.html#all_buffer_blobarraybuffer","metadata":{"transformedAt":"2026-08-18T18:33:40.707Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":121,"estimatedTokens":614}}643{"id":"stack-79317063","source":"stackoverflow","questionId":79317063,"title":"$state object could not be cloned","tags":["javascript","state","svelte","reactive","svelte-5"],"text":"Title: $state object could not be cloned\nTags: javascript, state, svelte, reactive, svelte-5\nSource: Stack Overflow\n\nQuestion:\nAfter I switched to Svelte 5 syntax I am getting this error when I pass a reactive variable to a function\n\n```\nlet details = $state({\n user: '',\n pass: ''\n})\n\n// ...\nawait login(details) // but works if I spread the state variable:\n\n```\nawait login({ ...details })\n```\n\nWhy is spreading needed in Svelte 5 but not 4, and why is it not mentioned in the migration guide?\n\n========================================\n\nCode:\n```js\nlet details = $state({\n user: '',\n pass: ''\n})\n\n// ...\nawait login(details) // <- error\n```\n\n```js\nawait login({ ...details })\n```\n\n```text\nProxy\n```\n\n```text\n$state.snapshot\n```\n\n========================================\n\nComments:\n- What does the login function look like? I'm not able to reproduce this\n- it just calls `ipcRenderer.invoke(\"login\", data)`. It seems related to this ipcRenderer issue, but this doesn't explain why I get this error before it reaches invoke, I get it in the auth wrapper function which simply calls `window.request()`. `window.request` is a function exposed in the preload script that calls `ipcRenderer.invoke`\n- I think from what i'm seeing you shouldn't pass variables created with $state to anything outside svelte. your svelte 5 code results in `let details = $.proxy({ user: '', pass: '' });`. whereas your svelte 4 code resulted in `let details = { user: '', pass: '' };`. Destructuring retrieves the raw object out of the Proxy. Either it should be mentioned in the migration docs, or it just isn't good practice, i'm not too familiar with electron\n- `await login({...details})` is not destructuring. It's taking a shallow copy of `details`.\n- I think this was a bad arch decision by svelte. It's very common you need to pass things outside of svelte, like to utility functions. So now we have to wrap everything inside snapshot...\n- In many contexts the proxy should be interchangeable with a regular object, unfortunately there are exceptions.","metadata":{"transformedAt":"2026-08-18T18:33:40.707Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":56,"estimatedTokens":510}}644{"id":"stack-74584450","source":"stackoverflow","questionId":74584450,"title":"How to get Svelte reactivity to display changes to array","tags":["svelte"],"text":"Title: How to get Svelte reactivity to display changes to array\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI am attempting to get Svelte to react to changes in an array. In my example REPL the array is changed, but the html output does not reflect this. What should I do?\n\n```\n\n $: objs = [] || getObjects(objs);\n\n function update(){\n getObjects(objs);\n }\n\n function getObjects(objs) {\n objs.push('a');\n objs = objs\n console.log(objs);\n return objs;\n }\n\n### Lists\n\n{#each objs || [] as obj}\n \n { obj }\n \n{/each}\nUpdate\n```\n\n========================================\n\nCode:\n```text\n<script>\n $: objs = [] || getObjects(objs);\n\n function update(){\n getObjects(objs);\n }\n\n function getObjects(objs) {\n objs.push('a');\n objs = objs\n console.log(objs);\n return objs;\n }\n</script>\n\n<h1>Lists</h1>\n{#each objs || [] as obj}\n <div>\n { obj }\n </div>\n{/each}\n<button on:click={update}>Update</button>\n```\n\n```js\nobjs.push(\"a\");\nobjs = objs;\n```\n\n```js\nobjs = [...objs, \"a\"];\n```\n\n```html\n<script>\n let objs = []\n\n function update() {\n objs = [...objs, \"a\"];\n }\n</script>\n\n<h1>Lists</h1>\n\n{#each objs as obj}\n <div>{obj}</div>\n{/each}\n\n<button on:click={update}>Update</button>\n```\n\n```text\n= []\n```\n\n```text\n||\n```\n\n```text\n$:\n```\n\n```text\nlet\n```\n\n========================================\n\nComments:\n- svelte don't react to `.push()` but only to `=` so you can use spread syntax `...` instead, I hope it can be useful to you\n- Included an assignment - still doesn't work","metadata":{"transformedAt":"2026-08-18T18:33:40.707Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":108,"estimatedTokens":384}}645{"id":"stack-75784414","source":"stackoverflow","questionId":75784414,"title":"SvelteKit iFrame load event not firing","tags":["typescript","iframe","svelte","sveltekit","svelte-3"],"text":"Title: SvelteKit iFrame load event not firing\nTags: typescript, iframe, svelte, sveltekit, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI have an `iframe` which is loading a local `index.html` file and it does loads the page without any problems, but what I want is to capture an `onload` event of the `iframe` and it is not doing so. Here is the code:\n\n```\n\n import { onMount } from 'svelte';\n\n onMount(() => {\n const iFrame = document.getElementById('frame');\n\n iFrame.addEventListener('load', () => {\n console.log('loaded!'); // it should print this!\n });\n });\n\n```\n\nAs you can see, there is nothing on the console:\n\nhttps://i.sstatic.net/L2sNH.png\n\nHowever, if I write something or just update the code & hit `Ctrl` + `S`, then due to **hmr** it actually triggers the onload function!\n\nhttps://i.sstatic.net/rEcCu.png\n\nI don't know why is this happening. This seems so strange to me. Here is the file structure, if you want to know:\n\nhttps://i.sstatic.net/nur3s.png\n\nHowever, the same code works on Svelte, so I suppose it is something related to SvelteKit...\n\n### Edit:\n\nIt really seems something is there with SvelteKit only. I created two new svelte and sveltekit apps forked from the official repos on codesandbox and there too onload on iframe is working on svelte only and not with the sveltekit. Here's the link:\n\nCheck the console -> Svelte | SvelteKit\n\n========================================\n\nTop Answer:\nI cannot reproduce this behavior with vanilla Svelte, that is without using SvelteKit. Thus I suspect it's a side effect of SvelteKit's server-side rendering.\n\nMy guess is, your first access to this route is delivered as a readily rendered HTML page, iframe included. This implies component's hydration script could be loaded after iframe's `onload` event, eventually delays the `onMount` callback's firing time.\n\nBut even with vanilla Svelte, I believe the firing order is not guaranteed, if you only attach `onload` handler after iframe is mounted. I would suggest you attach at DOM creation, using ``\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n import { onMount } from 'svelte';\n\n onMount(() => {\n const iFrame = <HTMLIFrameElement>document.getElementById('frame');\n\n iFrame.addEventListener('load', () => {\n console.log('loaded!'); // it should print this!\n });\n });\n</script>\n\n<iframe\n src=\"userFiles/index.html\"\n class=\"bg-[#ececec] w-full h-full\"\n frameborder=\"0\"\n title=\"Project\"\n id=\"frame\"\n style=\"color-scheme: dark;\"\n/>\n```\n\n```text\niframe\n```\n\n```text\nindex.html\n```\n\n```text\nonload\n```\n\n```text\niframe\n```\n\n```text\nCtrl\n```\n\n```text\nS\n```\n\n```text\nonload\n```\n\n```text\nonMount\n```\n\n```text\nonload\n```\n\n```text\n<iframe on:load={handleOnLoad} >\n```\n\n========================================\n\nComments:\n- A couple things: Is the onMount function running as expected? Also instead of `getElementById`, try binding the element.\n- using `` isn't triggering the onload event either.\n- It really seems something is there with SvelteKit only. I created two new svelte and sveltekit apps forked from the official repos on codesandbox and there too onload on iframe is working on svelte only and not with the sveltekit. Here's the link: Svelte SvelteKit","metadata":{"transformedAt":"2026-08-18T18:33:40.707Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":122,"estimatedTokens":811}}646{"id":"stack-77992577","source":"stackoverflow","questionId":77992577,"title":"Svelte 5 - using $state for class field in TypeScript","tags":["typescript","svelte","svelte-5"],"text":"Title: Svelte 5 - using $state for class field in TypeScript\nTags: typescript, svelte, svelte-5\nSource: Stack Overflow\n\nQuestion:\nI have a class:\n\n```\nclass TestClass {\n prop = $state('test');\n}\n```\n\nIt works in `.svelte.js` and `.svelte` files with ``, but doesn't work in `.svelte.ts` and `.svelte` files with ``.\nGetting this error:\n\nCompileError: $state(...) can only be used as a variable declaration initializer or a class field\n\nAm I doing anything wrong or Svelte 5 just doesn't support TS class field states yet?\n\nMy `tsconfig.json` file content:\n\n```\n{\n \"extends\": \"./.svelte-kit/tsconfig.json\",\n \"compilerOptions\": {\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"moduleResolution\": \"node\",\n \"module\": \"es2020\",\n \"lib\": [\"es2020\", \"dom\"],\n \"target\": \"es2019\",\n \"importsNotUsedAsValues\": \"error\",\n \"isolatedModules\": true,\n \"resolveJsonModule\": true,\n \"sourceMap\": true,\n \"esModuleInterop\": true,\n \"skipLibCheck\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"baseUrl\": \".\",\n \"allowJs\": true,\n \"checkJs\": true,\n \"paths\": {\n ....\n }\n },\n \"include\": [\n ....\n ],\n \"exclude\": [\"node_modules/*\"]\n}\n```\n\n========================================\n\nCode:\n```js\nclass TestClass {\n prop = $state('test');\n}\n```\n\n```text\n{\n \"extends\": \"./.svelte-kit/tsconfig.json\",\n \"compilerOptions\": {\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"moduleResolution\": \"node\",\n \"module\": \"es2020\",\n \"lib\": [\"es2020\", \"dom\"],\n \"target\": \"es2019\",\n \"importsNotUsedAsValues\": \"error\",\n \"isolatedModules\": true,\n \"resolveJsonModule\": true,\n \"sourceMap\": true,\n \"esModuleInterop\": true,\n \"skipLibCheck\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"baseUrl\": \".\",\n \"allowJs\": true,\n \"checkJs\": true,\n \"paths\": {\n ....\n }\n },\n \"include\": [\n ....\n ],\n \"exclude\": [\"node_modules/*\"]\n}\n```\n\n```text\n.svelte.js\n```\n\n```text\n.svelte\n```\n\n```text\n<script lang=\"js\">\n```\n\n```text\n.svelte.ts\n```\n\n```text\n.svelte\n```\n\n```text\n<script lang=\"ts\">\n```\n\n```text\ntsconfig.json\n```\n\n```text\ntarget\n```\n\n```text\n\"es6\"\n```\n\n```text\n\"es2015\"\n```\n\n```text\n\"es2022\"\n```\n\n```text\nuseDefineForClassFields\n```\n\n```text\ntrue\n```\n\n========================================\n\nComments:\n- thank you for your answer. I have `\"target\": \"es2019\"` in the tsconfig. Added almost full config to the question\n- How is the TS built and pre-processed in the components?\n- in svelte.config.js `preprocess: [vitePreprocess()],` from `@sveltejs/vite-plugin-svelte`; in vite.config.ts `plugins: [sveltekit()]` that's it I guess, nothing special anymore\n- @StanislauListratsenka The assignment gets moved to the constructor, see amended answer.\n- I got the same error again, googled it and opened my own question I forgot about, lool. And your answer helped! thank you!","metadata":{"transformedAt":"2026-08-18T18:33:40.707Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":153,"estimatedTokens":708}}647{"id":"stack-73943654","source":"stackoverflow","questionId":73943654,"title":"Sveltekit not running JavaScript on iOS","tags":["svelte","sveltekit"],"text":"Title: Sveltekit not running JavaScript on iOS\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have sveltekit website, (on opening the site \"Collecting logs...\" must change to \"👍 Copy Logs 📋\" in 5sec, if not then JavaScript must not be running).\n\nFor some reason svelte is not running my website correctly on iOS, after some feedback (from users), I concluded JavaScript is not running at all in iOS browsers. I don't have \"mac\" or \"iPhone\", so can't show you the console. Site runs perfectly on Android & Windows. Am I missing some configuration here?\n\nI did lot of research, and everything I found so far was a dead end. Is this how it will be with sveltekit, if so then should I will use Next.js then?\n\nsrc/routes/debug/+page.svelte\n\n```\n\n // ... code\n\n{#await new Promise((res) => setTimeout(res, 5000))}\n \n Collecting logs...\n \n{:then _}\n 👍 Copy Logs 📋 \n{/await}\n -->\n```\n\npackage.json\n\n```\n{\n \"name\": \"survey-site\",\n \"version\": \"0.0.1\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"vite dev\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\",\n \"check\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json\",\n \"check:watch\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch\",\n \"lint\": \"prettier --check . && eslint .\",\n \"format\": \"prettier --write .\"\n },\n \"devDependencies\": {\n \"@fontsource/merriweather\": \"^4.5.14\",\n \"@sveltejs/adapter-auto\": \"next\",\n \"@sveltejs/kit\": \"next\",\n \"@types/chart.js\": \"^2.9.37\",\n \"@typescript-eslint/eslint-plugin\": \"^5.27.0\",\n \"@typescript-eslint/parser\": \"^5.27.0\",\n \"autoprefixer\": \"^10.4.8\",\n \"chart.js\": \"^3.9.1\",\n \"eslint\": \"^8.16.0\",\n \"eslint-config-prettier\": \"^8.3.0\",\n \"eslint-plugin-svelte3\": \"^4.0.0\",\n \"postcss\": \"^8.4.16\",\n \"prettier\": \"^2.6.2\",\n \"prettier-plugin-svelte\": \"^2.7.0\",\n \"svelte\": \"^3.44.0\",\n \"svelte-check\": \"^2.7.1\",\n \"svelte-preprocess\": \"^4.10.7\",\n \"tailwindcss\": \"^3.1.8\",\n \"tslib\": \"^2.3.1\",\n \"typescript\": \"^4.7.4\",\n \"vite\": \"^3.0.4\"\n },\n \"type\": \"module\",\n \"dependencies\": {\n \"firebase\": \"^9.9.4\",\n \"svelte-drawer-component\": \"^1.2.2\"\n }\n}\n```\n\nsvelte.config.js\n\n```\nimport adapter from '@sveltejs/adapter-auto';\nimport preprocess from 'svelte-preprocess';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: preprocess({ postcss: true }),\n\n kit: {\n adapter: adapter()\n }\n};\n\nexport default config;\n```\n\nvite.config.ts\n\n```\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport type { UserConfig } from 'vite';\n\nconst config: UserConfig = {\n plugins: [sveltekit()]\n};\n\nexport default config;\n```\n\n========================================\n\nCode:\n```html\n<script lang=\"ts\">\n // ... code\n</script>\n{#await new Promise((res) => setTimeout(res, 5000))}\n <button disabled class=\"-bg-base2 bg-opacity-50 px-2 py-1 w-full mt-3\">\n Collecting logs...\n </button>\n{:then _}\n <button class=\"-bg-base2 px-2 py-1 w-full mt-3\" on:click={copyLogs}> 👍 Copy Logs 📋 </button>\n{/await}\n<!-- <MyUI /> -->\n```\n\n```json\n{\n \"name\": \"survey-site\",\n \"version\": \"0.0.1\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"vite dev\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\",\n \"check\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json\",\n \"check:watch\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch\",\n \"lint\": \"prettier --check . && eslint .\",\n \"format\": \"prettier --write .\"\n },\n \"devDependencies\": {\n \"@fontsource/merriweather\": \"^4.5.14\",\n \"@sveltejs/adapter-auto\": \"next\",\n \"@sveltejs/kit\": \"next\",\n \"@types/chart.js\": \"^2.9.37\",\n \"@typescript-eslint/eslint-plugin\": \"^5.27.0\",\n \"@typescript-eslint/parser\": \"^5.27.0\",\n \"autoprefixer\": \"^10.4.8\",\n \"chart.js\": \"^3.9.1\",\n \"eslint\": \"^8.16.0\",\n \"eslint-config-prettier\": \"^8.3.0\",\n \"eslint-plugin-svelte3\": \"^4.0.0\",\n \"postcss\": \"^8.4.16\",\n \"prettier\": \"^2.6.2\",\n \"prettier-plugin-svelte\": \"^2.7.0\",\n \"svelte\": \"^3.44.0\",\n \"svelte-check\": \"^2.7.1\",\n \"svelte-preprocess\": \"^4.10.7\",\n \"tailwindcss\": \"^3.1.8\",\n \"tslib\": \"^2.3.1\",\n \"typescript\": \"^4.7.4\",\n \"vite\": \"^3.0.4\"\n },\n \"type\": \"module\",\n \"dependencies\": {\n \"firebase\": \"^9.9.4\",\n \"svelte-drawer-component\": \"^1.2.2\"\n }\n}\n```\n\n```js\nimport adapter from '@sveltejs/adapter-auto';\nimport preprocess from 'svelte-preprocess';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: preprocess({ postcss: true }),\n\n kit: {\n adapter: adapter()\n }\n};\n\nexport default config;\n```\n\n```js\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport type { UserConfig } from 'vite';\n\nconst config: UserConfig = {\n plugins: [sveltekit()]\n};\n\nexport default config;\n```\n\n```js\nnew Date(new Date().toString() + ' UTC'); // returns \"Invalid Date\"\nnew Date(new Date().toString() + ' UTC').toISOString().substring(0, 16); // throws \"RangeError: Invalid Date\"\n```\n\n========================================\n\nComments:\n- does safari block alert? I seem to recall that it does somewhere.\n- for me it looks like it is running js but there are some issues with API that you are using: (`Fetch API cannot load https://firestore.googleapis.com/google.firestore.v1.Firesto‌​re/Listen/channel?da‌​tabase=projects%2Fhu‌​ddle-and-score%2Fdat‌​abases%2F(default)&g‌​sessionid=73F7w7KaKw‌​lXFXEZhGarv897bSa2DE‌​Jz&VER=8&RID=rpc&SID‌​=X1tqejTOkoI0C9tKkgj‌​z9A&CI=0&AID=9&TYPE=‌​xmlhttp&zx=i25itnlu6‌​f1q&t=1 due to access control checks.`) Maybe this will give you some hint where to look :D\n- @chovy even if alert is not supported in safari, the buttons just don't work.\n- alert is blocking....that's why its blocked. I'm on linux so I'm afraid I'm of no help.\n- @PawełWąsowski I can't see this error on Windows Chrome. Besides, fetch is an async call, why will that affect buttons and rest UI based JavaScript\n- @chovy alright I have removed alert dialog from my site. Could you check if it buttons works on your machine?\n- If you have Apple users, you should invest in either such devices or a test service that allows you to test on these devices.\n- @H.B. you are right but man our product is not that big yet. I just want a solution/insight, no lectures.\n- @Panth now I can see some data after the change (Safari). Before there was additional error after the fetch but I cannot remember it content. It looked like some out of range exception - maybe iteration over data that was not returned by the API? Maybe you can try to use: browserstack.com/test-on-safari-browser I can see that they have some kind of free trial.\n- @PawełWąsowski I tried that here is the output\n- @Panth yeah, I'm reciving same output. The issue is this unhandled promise rejection that blocks rest of the js, but I cannot help you with that - I don't know what the issue is :/ That promise that you've included in question works correctly on Safari, so issue is probably somewhere else. My bet is some quirk that needs to be handled differently on Safari.\n- u would't belive but i did resolve the problem, and yes this was the problem. just 5 min ago. turns out UTC dosent work in safari.. 😂. Man problem is resolved. TYSM","metadata":{"transformedAt":"2026-08-18T18:33:40.707Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":218,"estimatedTokens":1893}}648{"id":"stack-75048529","source":"stackoverflow","questionId":75048529,"title":"Is there anything missing to use Chart.js on a Svelte app?","tags":["javascript","charts","svelte","sveltekit"],"text":"Title: Is there anything missing to use Chart.js on a Svelte app?\nTags: javascript, charts, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am new to Svelte and having trouble displaying a graph using Chart.js on a SvelteKit page.\n\nFirst, I tried to put a canvas and confirmed that it worked, as the code below shows a black canvas on a page if you comment out the onMount function. However, it doesn't show anything after adding the onMount part. There is no error indication in the browser and terminal console, so I am stuck with it.\n\nI use the latest version of Sveltekit and Chart.js. Is there anything missing?\n\n```\n\n import { onMount } from 'svelte';\n import Chart from 'chart.js/auto';\n\n let data = [20, 100, 50, 12, 20, 130, 45];\n let labels = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];\n let ctx;\n let canvas;\n\n onMount(() => {\n ctx = canvas.getContext('2d');\n var chart = new Chart(ctx, {\n type: 'bar',\n data: {\n labels: labels,\n datasets: [\n {\n label: 'Unit Sales',\n data: data\n }\n ]\n }\n });\n });\n\n canvas {\n width: 100%;\n height: 100%;\n background-color: #666;\n }\n\n```\n\n========================================\n\nTop Answer:\nYour code, copied directly into a Svelte REPL without modification seems to work fine:\n\nhttps://i.sstatic.net/aKAnp.png\n\nSo the issue is probably somewhere else.\n\n- Are there any errors in the browser dev console?\n\n- Errors in the terminal? (Where you started SvelteKit.)\n\nMy guess is there is a JS error, probably related to importing Chart.js.\n\n- Your page would render a blank canvas even if there were JS errors.\n\n- Did you actually install the Chart.js modules? (`npm install ...`)\n\nHere is a similar problem I solved: https://stackoverflow.com/a/71035686/117030\n\n========================================\n\nCode:\n```text\n<script>\n import { onMount } from 'svelte';\n import Chart from 'chart.js/auto';\n\n let data = [20, 100, 50, 12, 20, 130, 45];\n let labels = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];\n let ctx;\n let canvas;\n\n onMount(() => {\n ctx = canvas.getContext('2d');\n var chart = new Chart(ctx, {\n type: 'bar',\n data: {\n labels: labels,\n datasets: [\n {\n label: 'Unit Sales',\n data: data\n }\n ]\n }\n });\n });\n</script>\n\n<canvas bind:this={canvas} width={32} height={32} />\n\n<style>\n canvas {\n width: 100%;\n height: 100%;\n background-color: #666;\n }\n</style>\n```\n\n```css\ndiv { width: 50vw; height: 50vh; }\n```\n\n```text\ncanvas\n```\n\n```text\ndiv\n```\n\n```text\nwidth\n```\n\n```text\nheight\n```\n\n```text\ncanvas\n```\n\n```text\nnpm install ...\n```\n\n========================================\n\nComments:\n- That exact code works for me without issue.\n- @H.B. Really? That sounds weird to me because the page shows just a white background in my browser (Chrome)\n- Have you inspected the `canvas` element, how big is it? Not sure how Chart.js's sizing works, maybe the element is just not visible.\n- Thank you very much. Reading the docs, I found that this caused the problem, and now I can see a graph on the canvas!","metadata":{"transformedAt":"2026-08-18T18:33:40.707Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":142,"estimatedTokens":815}}649{"id":"stack-72631722","source":"stackoverflow","questionId":72631722,"title":"How to get a unique index for nested loops in Svelte Kit","tags":["javascript","svelte","sveltekit"],"text":"Title: How to get a unique index for nested loops in Svelte Kit\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm creating a website for uploading images. You can create albums, and each album can contain a number of posts. There are numerous photos in each post (a array of images).\n\nIt looks like the following:\n\n```\nconst albums = [\n {\n id: 1,\n title: 'Album 1',\n }\n]\n\nconst posts = [\n {\n \"album\": 1,\n \"images\": [\n \"https://picsum.photos/200/300\",\n \"https://picsum.photos/200/300\",\n ],\n \"author\": 1,\n },\n {\n \"album\": 1,\n \"images\": [\n \"https://picsum.photos/200/300\",\n ],\n \"author\": 2,\n },\n {\n \"album\": 1,\n \"images\": [\n \"https://picsum.photos/200/300\",\n \"https://picsum.photos/200/300\",\n \"https://picsum.photos/200/300\",\n \"https://picsum.photos/200/300\",\n \"https://picsum.photos/200/300\",\n ],\n \"author\": 4,\n }\n]\n```\n\nFor each post image in the array, I need to obtain a distinct index number.\nHow I'm trying to obtain it in Svelte is as following:\n\n```\n{#each posts as post}\n {#each post.images as image, index}\n {index}: {image}\n {/each}\n{/each}\n```\n\nHowever, this won't give me an unique index for every image. It will result in the following:\n\n```\n0: https://picsum.photos/200/300\n1: https://picsum.photos/200/300\n0: https://picsum.photos/200/300\n0: https://picsum.photos/200/300\n1: https://picsum.photos/200/300\n2: https://picsum.photos/200/300\n3: https://picsum.photos/200/300\n4: https://picsum.photos/200/300\n```\n\nExcept, I need it like this:\n\n```\n0: https://picsum.photos/200/300\n1: https://picsum.photos/200/300\n2: https://picsum.photos/200/300\n3: https://picsum.photos/200/300\n4: https://picsum.photos/200/300\n5: https://picsum.photos/200/300\n6: https://picsum.photos/200/300\n7: https://picsum.photos/200/300\n```\n\nHow would I be possible to achieve the above one?\n\nOne thought of mine would be reducing/mapping the array and creating a post object for each single image. However, I'm unsure how to achieve this.\n\n========================================\n\nTop Answer:\nGenerate a nested array containing the desired numbers:\n\n```\n\n // const posts = ...\n\n $: numbers = buildNumbers(posts)\n\n function buildNumbers(posts) {\n let nr = 1\n const result = []\n posts.forEach((post, postIndex) => {\n post.images.forEach((image, imageIndex) => {\n result[postIndex] = result[postIndex] || []\n result[postIndex][imageIndex] = nr\n nr++\n })\n })\n return result\n }\n\n{#each posts as post, postIndex}\n {#each post.images as image, imageIndex}\n \n- {numbers[postIndex][imageIndex]}: {image}\n {/each}\n{/each}\n\n```\n\nREPL\n\n========================================\n\nCode:\n```text\nconst albums = [\n {\n id: 1,\n title: 'Album 1',\n }\n]\n\nconst posts = [\n {\n \"album\": 1,\n \"images\": [\n \"https://picsum.photos/200/300\",\n \"https://picsum.photos/200/300\",\n ],\n \"author\": 1,\n },\n {\n \"album\": 1,\n \"images\": [\n \"https://picsum.photos/200/300\",\n ],\n \"author\": 2,\n },\n {\n \"album\": 1,\n \"images\": [\n \"https://picsum.photos/200/300\",\n \"https://picsum.photos/200/300\",\n \"https://picsum.photos/200/300\",\n \"https://picsum.photos/200/300\",\n \"https://picsum.photos/200/300\",\n ],\n \"author\": 4,\n }\n]\n```\n\n```text\n{#each posts as post}\n {#each post.images as image, index}\n {index}: {image}\n {/each}\n{/each}\n```\n\n```text\n0: https://picsum.photos/200/300\n1: https://picsum.photos/200/300\n0: https://picsum.photos/200/300\n0: https://picsum.photos/200/300\n1: https://picsum.photos/200/300\n2: https://picsum.photos/200/300\n3: https://picsum.photos/200/300\n4: https://picsum.photos/200/300\n```\n\n```text\n0: https://picsum.photos/200/300\n1: https://picsum.photos/200/300\n2: https://picsum.photos/200/300\n3: https://picsum.photos/200/300\n4: https://picsum.photos/200/300\n5: https://picsum.photos/200/300\n6: https://picsum.photos/200/300\n7: https://picsum.photos/200/300\n```\n\n```js\nfunction getImages() {\n return posts.map(post => post.images).flat()\n}\n```\n\n```html\n{#each getImages() as image, index}\n {index}: {image}\n{/each}\n```\n\n```text\neach\n```\n\n```html\n<script>\n // const posts = ...\n\n $: numbers = buildNumbers(posts)\n\n function buildNumbers(posts) {\n let nr = 1\n const result = []\n posts.forEach((post, postIndex) => {\n post.images.forEach((image, imageIndex) => {\n result[postIndex] = result[postIndex] || []\n result[postIndex][imageIndex] = nr\n nr++\n })\n })\n return result\n }\n</script>\n\n<ul>\n{#each posts as post, postIndex}\n {#each post.images as image, imageIndex}\n <li>{numbers[postIndex][imageIndex]}: {image}</li>\n {/each}\n{/each}\n</ul>\n```\n\n```html\n<script>\n const posts = [\n {\n album: 1,\n images: ['https://picsum.photos/200/300', 'https://picsum.photos/200/300'],\n author: 1,\n },\n {\n album: 1,\n images: ['https://picsum.photos/200/300'],\n author: 2,\n },\n {\n album: 1,\n images: ['https://picsum.photos/200/300', 'https://picsum.photos/200/300'],\n author: 4,\n },\n ];\n</script>\n\n<ul>\n {#each posts as post, index}\n {@const postIndex = index}\n {#each post.images as _, index}\n {@const imageIndex = index}\n {@const uniqueId = `${postIndex}:${imageIndex}`}\n <li>{uniqueId}</li>\n {/each}\n {/each}\n</ul>\n\n<!--\n0:0\n0:1\n1:0\n2:0\n2:1\n-->\n```\n\n========================================\n\nComments:\n- `Please don't hate on me for posting this.` - apols if misinterpreting, but please don't assume the worst in us, we want to help you fix issues in your code, we'd never hate anyone for asking for help :)\n- (If you want to thank people, upvote answers and accept the one that was the most helpful to you.)\n- @H.B. Sadly I can't upvote yet since I need at least 15 reputation to cast a vote. :[\n- I appreciate you responding. I later added this, however since a post can have an unique author, who I want to display, this wouldn't be working right..\n- @Wolf You just need to include the author in the mapping then, probably something like `posts.flatMap(p => p.images.map(i => ({ author: p.author, image: i })))` (REPL)\n- @H.B. Thank you for your response! The code on your REPL worked perfectly!","metadata":{"transformedAt":"2026-08-18T18:33:40.707Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":289,"estimatedTokens":1562}}650{"id":"stack-69872304","source":"stackoverflow","questionId":69872304,"title":"SvelteKit Unused CSS selector warning in VS Code","tags":["css","visual-studio-code","sass","svelte","sveltekit"],"text":"Title: SvelteKit Unused CSS selector warning in VS Code\nTags: css, visual-studio-code, sass, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nHow can I remove VS Code Unused CSS selector warning? This warning is in all files where i use ``. I know that I don't use `.btn` class in some components, but I want this class as global css.\n\nhttps://i.sstatic.net/YX2Dd.png\n\nmy `svelte.config.js`:\n\n```\nconst config = {\n onwarn: (warning, handler) => {\n const { code, frame } = warning;\n if (code === \"css-unused-selector\")\n return;\n\n handler(warning);\n },\n preprocess: [\n preprocess({\n defaults: {\n style: 'scss'\n },\n postcss: true,\n scss: {\n prependData: `@import 'src/scss/global.scss';`\n }\n })\n ],\n};\n```\n\nPlease can someone help me?\n\n========================================\n\nCode:\n```js\nconst config = {\n onwarn: (warning, handler) => {\n const { code, frame } = warning;\n if (code === \"css-unused-selector\")\n return;\n\n handler(warning);\n },\n preprocess: [\n preprocess({\n defaults: {\n style: 'scss'\n },\n postcss: true,\n scss: {\n prependData: `@import 'src/scss/global.scss';`\n }\n })\n ],\n};\n```\n\n```text\n<style lang=\"scss\">\n```\n\n```text\n.btn\n```\n\n```text\nsvelte.config.js\n```\n\n```html\n<script>\n import 'path/to/your/global.scss';\n</script>\n```\n\n```text\nprependData\n```\n\n```text\n__layout.svelte\n```\n\n========================================\n\nComments:\n- If you are defining globals either import a global style sheet at the appropriate parent, or define them using `:global(.some-selector)`.\n- But i want separate global.scss file. My global.scss: ` @import './variables'; @import './font'; @import './typography'; @import './components/button'; `","metadata":{"transformedAt":"2026-08-18T18:33:40.707Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":93,"estimatedTokens":449}}651{"id":"stack-69543569","source":"stackoverflow","questionId":69543569,"title":"Detect when svelte store is not used anymore","tags":["javascript","javascript-objects","svelte","svelte-component","svelte-store"],"text":"Title: Detect when svelte store is not used anymore\nTags: javascript, javascript-objects, svelte, svelte-component, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI'm making a custom svelte store by wrapping around a svelte writable store.\n\nI want to detect when that store is not subscribed by any component; when the subscription count is 0\n\nMy objective is to clear some heavy external resources (websockets) that were tied to the custom store when no one is using it.\n\nCurrently, I'm counting the subscriptions and unsubscriptions by wrapping around subscribe( ) method. **It works as expected**. But It looks like a nasty hack to me.\n\n**My question: Is there a standard / clean way to achieve this behavior in Svelte?**\n\nIf not, can someone with more experience in Javascipt and svelte confirm whether this is legit?\n\nDemo on : https://svelte.dev/repl/f4e24fb5c56f457a94bf9cf645955b9f?version=3.43.1\n\n```\nimport { writable } from 'svelte/store';\n\n// Instanciate the store\nexport let store = MakeStore();\n\n// By design, I want a function that returns a custom svelte store\nexport function MakeStore(initialValue = null) {\n\n const { subscribe, set, update } = writable(initialValue);\n\n let subscribercount = 0;\n\n let wsubscribe = function (run, callback) {\n subscribercount++;\n console.log(\"subscribercount++\", subscribercount);\n\n let wunsubscribe = subscribe(run, callback);\n return () => {\n subscribercount--;\n console.log(\"subscribercount--\", subscribercount);\n\n if (subscribercount == 0) {\n\n // -------------------------------\n // Free up resources\n // I want a clean way to get here\n // -------------------------------\n console.log(\"Cleaning up...\");\n }\n return wunsubscribe();\n }\n }\n\n // Some external calls here\n\n let store = {\n subscribe: wsubscribe,\n set: newvalue => {\n set(newvalue);\n // Some external calls here\n },\n update: update\n };\n\n // Some external calls here\n\n return store;\n }\n```\n\n========================================\n\nCode:\n```text\nimport { writable } from 'svelte/store';\n\n// Instanciate the store\nexport let store = MakeStore();\n\n// By design, I want a function that returns a custom svelte store\nexport function MakeStore(initialValue = null) {\n\n const { subscribe, set, update } = writable(initialValue);\n\n let subscribercount = 0;\n\n let wsubscribe = function (run, callback) {\n subscribercount++;\n console.log(\"subscribercount++\", subscribercount);\n\n let wunsubscribe = subscribe(run, callback);\n return () => {\n subscribercount--;\n console.log(\"subscribercount--\", subscribercount);\n\n if (subscribercount == 0) {\n\n // -------------------------------\n // Free up resources\n // I want a clean way to get here\n // -------------------------------\n console.log(\"Cleaning up...\");\n }\n return wunsubscribe();\n }\n }\n\n // Some external calls here\n\n let store = {\n subscribe: wsubscribe,\n set: newvalue => {\n set(newvalue);\n // Some external calls here\n },\n update: update\n };\n\n // Some external calls here\n\n return store;\n }\n```\n\n```js\nconst count = writable(0, () => {\n console.log('got a subscriber');\n return () => console.log('no more subscribers');\n});\n```\n\n```js\nconst count = derived(items, ($items, set) => {\n console.log('got a subscriber to a derived store');\n return () => console.log('no more subscribers to derived store');\n});\n```\n\n```text\nno more subscribers to derived store\n```\n\n```text\n($items, set) => {...}\n```\n\n========================================\n\nComments:\n- Thanks a lot. Tested on svelte.dev/repl/69ced8a1093b47d1b8d1eb819fb70ace?version=3.4‌​3.1 and it works 😆\n- That's not the case anymore. In accordance with new documentation: If you return a function from the callback, it will be called when a) the callback runs again, or b) the last subscriber unsubscribes.\n- @PavelBlagodov did you ever figure out a way to have a function run only in the case of (b)? Seems like an odd decision for it to be called when the callback runs again. We could just... call it within the callback in that case.\n- @PavelBlagodov where do you find that ? I tried the above code with the latest version of Svelte (3.55.1) and it still works as expected svelte.dev/repl/c1df816783084b4f8fa1d38954a8ec25?version=3.5‌​5.1 not sure what you mean with 'when the callback runs again'\n- nvm, found it, that is for **derived** stores though, which is a bit of a specialized use case, it does not apply to regular writable or readable stores","metadata":{"transformedAt":"2026-08-18T18:33:40.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":154,"estimatedTokens":1192}}652{"id":"stack-69601626","source":"stackoverflow","questionId":69601626,"title":"Windi CSS HMR not working for Svelte + vite app","tags":["yarnpkg","svelte","vite","windicss"],"text":"Title: Windi CSS HMR not working for Svelte + vite app\nTags: yarnpkg, svelte, vite, windicss\nSource: Stack Overflow\n\nQuestion:\nI created a Svelte project with Vite and added windicss. I am using Yarn as build tool. I added WindiCSS to vite using https://windicss.org/integrations/vite.html#install. It works fine when I start the project using,\n\n```\nyarn dev\n```\n\nBut HMR (Hot Module Reload) for Windi CSS does not work. But when I kill the server and restart it picks up the Windi CSS changes. Even the Devtool changes are working fine, only HMR is not working.\n\n`package.json` file,\n\n```\n{\n \"name\": \"svelte-in\",\n \"version\": \"0.0.0\",\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"serve\": \"vite preview\"\n },\n \"devDependencies\": {\n \"@sveltejs/vite-plugin-svelte\": \"^1.0.0-next.11\",\n \"svelte\": \"^3.37.0\",\n \"vite\": \"^2.6.4\",\n \"vite-plugin-windicss\": \"^1.4.11\",\n \"windicss\": \"^3.1.9\"\n }\n}\n```\n\n`vite.config.js` file,\n\n```\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\nimport WindiCSS from 'vite-plugin-windicss'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n svelte(), \n WindiCSS()\n ]\n})\n```\n\nAnd `main.js` is,\n\n```\nimport App from './App.svelte'\nimport 'virtual:windi.css'\nimport 'virtual:windi-devtools' // To enable windi in dev tools\n\nconst app = new App({\n target: document.getElementById('app')\n})\n\nexport default app\n```\n\nNot sure if I am missing anything else.\n\n========================================\n\nCode:\n```text\nyarn dev\n```\n\n```text\n{\n \"name\": \"svelte-in\",\n \"version\": \"0.0.0\",\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"serve\": \"vite preview\"\n },\n \"devDependencies\": {\n \"@sveltejs/vite-plugin-svelte\": \"^1.0.0-next.11\",\n \"svelte\": \"^3.37.0\",\n \"vite\": \"^2.6.4\",\n \"vite-plugin-windicss\": \"^1.4.11\",\n \"windicss\": \"^3.1.9\"\n }\n}\n```\n\n```text\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\nimport WindiCSS from 'vite-plugin-windicss'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n svelte(), \n WindiCSS()\n ]\n})\n```\n\n```text\nimport App from './App.svelte'\nimport 'virtual:windi.css'\nimport 'virtual:windi-devtools' // To enable windi in dev tools\n\nconst app = new App({\n target: document.getElementById('app')\n})\n\nexport default app\n```\n\n```text\npackage.json\n```\n\n```text\nvite.config.js\n```\n\n```text\nmain.js\n```\n\n```text\nWindiCSS()\n```\n\n```text\nsvelte()\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":139,"estimatedTokens":627}}653{"id":"stack-71801939","source":"stackoverflow","questionId":71801939,"title":"Disable spaces in input field on svelte","tags":["svelte","svelte-3","sveltekit"],"text":"Title: Disable spaces in input field on svelte\nTags: svelte, svelte-3, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am trying to disable spaces in the Username text field\n\nAs Disable spaces in Input, AND allow back arrow?, this should be like this:\n\n```\n e.which !== 32} />\n```\n\nBut I still able to input space\n\n========================================\n\nTop Answer:\n`which` is not a valid event property anymore. For keyboard events, you'll want to use KeyboardEvent.code or KeyboardEvent.key.\n\nIn your use case, using the former:\n\n```\n code !== \"Space\"} />\n```\n\nthis will only disallow the spacebar, however, so you'd likely have to add handling for other whitespace keys like `Tab`, etc.\n\nAlternatively, you could turn your input into a controlled input and `trim` the content whenever it changes (in effect disallowing whitespace input of any kind).\n\n========================================\n\nCode:\n```html\n<input on:keydown={(e) => e.which !== 32} />\n```\n\n```text\n<script>\n let value\n \n function handleKeydown(event) {\n // prevent that a space is typed\n if(event.code === 'Space') event.preventDefault()\n }\n \n function handleInput(event) {\n // remove spaces from pasted text\n value = value.replaceAll(' ', '') \n } \n</script>\n\n<input type=\"text\"\n bind:value\n on:keydown={handleKeydown}\n on:input={handleInput}>\n```\n\n```text\n<input on:keydown={({ code }) => code !== \"Space\"} />\n```\n\n```text\nwhich\n```\n\n```text\nTab\n```\n\n```text\ntrim\n```\n\n```html\nBroken:\n<input type=\"text\" on:keypress=\"{e => e.charCode != 32}\"/> <br/>\n\nWorks (not recommended):\n<input type=\"text\" onkeypress=\"return event.charCode != 32\"/> <br/>\n\nWorks with \"on:\"\n<input type=\"text\"\n on:keypress={e => { if (e.charCode == 32) e.preventDefault(); }} />\n```\n\n```text\npreventDefault\n```\n\n```text\nkeypress\n```\n\n```text\n<a href=\"#{HtmlLibrary.title}\"></a>\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.708Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":97,"estimatedTokens":481}}654{"id":"stack-70970397","source":"stackoverflow","questionId":70970397,"title":"Slow button response time with Capacitor x Svelte on Ios","tags":["ionic-framework","tailwind-css","svelte","capacitor","vite"],"text":"Title: Slow button response time with Capacitor x Svelte on Ios\nTags: ionic-framework, tailwind-css, svelte, capacitor, vite\nSource: Stack Overflow\n\nQuestion:\nI try to create a starter app with Capacitor and Svelte. Everything works fine except one thing, when I use native html anchor ( with svelte-routing) for navigate the there is a slow respond time to user interaction, maybe 400ms before app react on my Iphone 13 pro (real device) Ios 15. Same issue for native html buttons across my starter.\n\ncan you tell me if i did something wrong please ?\n\nthe starter repos -> https://github.com/flameapp-io/svelte-capacitor-tailwind-starter\n\nMy navigation component :\n\n```\n\n import ThemeSwitch from '$lib/ThemeSwitch.svelte';\n import { Link } from 'svelte-routing';\n\n type NavLink = {\n name: string;\n url: string;\n };\n\n const navLinks: Array = [\n {\n name: 'Home',\n url: '/'\n },\n {\n name: 'Example',\n url: 'example'\n }\n ];\n\n {#each navLinks as link}\n {link.name}\n {/each}\n\n \n\n```\n\n========================================\n\nCode:\n```js\n<script lang=\"ts\">\n import ThemeSwitch from '$lib/ThemeSwitch.svelte';\n import { Link } from 'svelte-routing';\n\n type NavLink = {\n name: string;\n url: string;\n };\n\n const navLinks: Array<NavLink> = [\n {\n name: 'Home',\n url: '/'\n },\n {\n name: 'Example',\n url: 'example'\n }\n ];\n</script>\n\n<nav class=\"flex items-center\">\n {#each navLinks as link}\n <Link to={link.url} class=\"mx-5\">{link.name}</Link>\n {/each}\n\n <ThemeSwitch />\n</nav>\n```\n\n```html\n<meta name=\"viewport\" content=\"viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"/>\n```\n\n```html\n<meta name=\"viewport\" content=\"viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"/>\n```\n\n========================================\n\nComments:\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:40.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":88,"estimatedTokens":561}}655{"id":"stack-69064635","source":"stackoverflow","questionId":69064635,"title":"Exporting props from SvelteKit load() function","tags":["javascript","svelte","svelte-component","sveltekit"],"text":"Title: Exporting props from SvelteKit load() function\nTags: javascript, svelte, svelte-component, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a dynamically updating navbar in SvelteKit, with the currently open section formatted accordingly. I am attempting to identify the page based on the first part of the path, as below:\n\n`__layout.svelte`:\n\n```\n\n export const load = ({ page }) => {\n return {\n props: {\n currentSection: `${page.path}`.split('/')[0],\n sections: ['home', 'dashboard', 'settings']\n }\n };\n }\n\n \n \n\n```\n\n`Header.svelte`\n\n```\n\n import Menu from \"$lib/nav/menu.svelte\"\n\n```\n\n`Menu.svelte`\n\n```\n\n export let sections;\n export let currentSection;\n\n{#each sections as { section }}\n {section}\n{/each}\n```\n\nThis is resulting in a `props is not defined` error, but I would have expected props to be defined since I've defined it in the return from the `load()` fundtion on the primary layout (based on the docs).\n\nDo I somehow need to explicitly declare the props rather than expecting them to be available from the return of the `load()` function?\n\n========================================\n\nCode:\n```text\n<script context=\"module\">\n export const load = ({ page }) => {\n return {\n props: {\n currentSection: `${page.path}`.split('/')[0],\n sections: ['home', 'dashboard', 'settings']\n }\n };\n }\n</script>\n\n<div class=\"min-h-screen bg-gray-100\">\n <Header {...props} />\n <slot />\n</div>\n```\n\n```text\n<script>\n import Menu from \"$lib/nav/menu.svelte\"\n</script>\n\n<Menu {...props}></Menu>\n```\n\n```text\n<script>\n export let sections;\n export let currentSection;\n</script>\n\n{#each sections as { section }}\n <a\n href=\"/{section}\"\n class=\"{section == currentSection\n ? 'bg-gray-900 text-white'\n : 'text-gray-300 hover:bg-gray-700'} other-classes\"\n >{section}</a\n >\n{/each}\n```\n\n```text\n__layout.svelte\n```\n\n```text\nHeader.svelte\n```\n\n```text\nMenu.svelte\n```\n\n```text\nprops is not defined\n```\n\n```text\nload()\n```\n\n```text\nload()\n```\n\n```html\n<script context=\"module\">\n export const load = () => {\n return {\n props: {\n test: 123\n }\n }\n }\n</script>\n\n<script>\n export let test; //\n</script>\n```\n\n```text\nprops\n```\n\n```text\nexport let props\n```\n\n```text\nexport let props\n```\n\n```text\n$$props\n```\n\n========================================\n\nComments:\n- The `props is not defined` error is in `__layout.svelte` so the props never get to the component - do the props need to be explicitly declared in the layout too, even though they are being returned by the load function? That's the basis of the question.\n- Yes, it still has to do so, `__layout` is a component (almost) like any other\n- Perhaps you could update your answer to show how that is done?","metadata":{"transformedAt":"2026-08-18T18:33:40.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":157,"estimatedTokens":706}}656{"id":"stack-70321016","source":"stackoverflow","questionId":70321016,"title":"How to do a reactive assignment across multiple lines in Svelte?","tags":["svelte"],"text":"Title: How to do a reactive assignment across multiple lines in Svelte?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nIn Svelte, it's common to assign variables that are reactively computed from some props or state like so:\n\n```\nexport let x: number\n export let y: number\n $: sum = x + y\n```\n\nWhat does the multi-line form of this look like, when I have a reaction significantly more complicated than `x + y`?\n\n========================================\n\nTop Answer:\nThe extended version of this is\n\n```\n$: if (valesChanged) {\n // do whatever you want\n}\n```\n\nAnd the condition could be a change of one or more of the reactive values.\n\nor more elegant solution if there any change in all props\n\n```\n$: if($$props) {\n console.log($$props)\n}\n```\n\n========================================\n\nCode:\n```js\nexport let x: number\n export let y: number\n $: sum = x + y\n```\n\n```text\nx + y\n```\n\n```js\n$: {\n ...multi-line complex operation on x and y setting value z...\n}\n```\n\n```js\nfunction complexOperation(a, b) {\n ...multi-line complex operation on a and b setting value c...\n return c\n}\n\n$: z = complexOperation(x, y)\n```\n\n```text\n$: if (valesChanged) {\n // do whatever you want\n}\n```\n\n```text\n$: if($$props) {\n console.log($$props)\n}\n```\n\n========================================\n\nComments:\n- Thanks! I've ended up mostly doing them as anonymous function invocations like `$: pattern = ((allPatterns) => { return allPatterns.find(p => p.id === patternId) })(allPatterns)`. It's not quite as nice as reactive getters in Vue or Mobx, but I think it's alright.\n- You're welcome! Although in the example you give, an anonymous function is not necessary, you could simply do `$: pattern = allPatterns.find(p => p.id === patternId)` which I think is clearer?\n- Yep, sorry, bad example; I do mean specifically for the case when multiple statements are needed.","metadata":{"transformedAt":"2026-08-18T18:33:40.708Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":82,"estimatedTokens":465}}657{"id":"stack-72487135","source":"stackoverflow","questionId":72487135,"title":"How to use enviroment variables in Svelte @ index.html","tags":["svelte","vite","sveltekit"],"text":"Title: How to use enviroment variables in Svelte @ index.html\nTags: svelte, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI would like to use a environmental variable in `svelte-kit` project but unfornutaely I'm not being able to.\n\nI have tried to:\n\n*app.html*\n\n```\n\n\">\n\">\n```\n\nIn my `.env` I have the variable defined:\n\n```\nVITE_GOOGLE_TAG=xxxxx\n```\n\nBut the substitution doesn't happen when I re-start my server.\n\nI'm looking to have a different `Google tag manager id` for each enviroment. Something like\n\n```\nstaging -> xxxxx\nproduction -> yyyyy\n```\n\nHow can I access enviromental variables in `svelte-kit` in my `app.html`?\n\n========================================\n\nCode:\n```html\n<meta name=\"TESTING\" value=\"%VITE_GOOGLE_TAG%\">\n<meta name=\"TESTING\" value=\"<% VITE_GOOGLE_TAG %>\">\n<meta name=\"TESTING\" value=\"<% process.env.VITE_GOOGLE_TAG %>\">\n```\n\n```text\nVITE_GOOGLE_TAG=xxxxx\n```\n\n```text\nstaging -> xxxxx\nproduction -> yyyyy\n```\n\n```text\nsvelte-kit\n```\n\n```text\n.env\n```\n\n```text\nGoogle tag manager id\n```\n\n```text\nsvelte-kit\n```\n\n```text\napp.html\n```\n\n```html\n<!-- src/routes/__layout.svelte -->\n<svelte:head>\n <meta name=\"TESTING\" value={import.meta.env.VITE_GOOGLE_TAG}>\n</svelte:head>\n```\n\n```text\n<meta>\n```\n\n```text\n<head>\n```\n\n```text\n<svelte:head>\n```\n\n```text\n<meta>\n```\n\n```text\nsrc/routes/__layout.svelte\n```\n\n```text\nimport.meta.env.VARNAME\n```\n\n```text\n<meta>.value\n```\n\n========================================\n\nComments:\n- Did you tried to just use the svelte's `` component that makes it possible to insert elements into `document.head`? Read more about it here svelte.dev/docs#template-syntax-svelte-head\n- @johannchopin yeah. I was overly complicating things. Thank you","metadata":{"transformedAt":"2026-08-18T18:33:40.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":112,"estimatedTokens":426}}658{"id":"stack-51522539","source":"stackoverflow","questionId":51522539,"title":"Svelte - how to use methods in template?","tags":["svelte"],"text":"Title: Svelte - how to use methods in template?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nWith vue I was usually extractiog any complex logic into methods eg\n\n```\n\n {{ todo }}\n\n```\n\nBut when I'm trying the same approach with svelte:\n\n```\n{#each todos as todo}\n \n- {todo}\n{/each}\n...\nmethods: { isComplete (todo) { ... } }\n```\n\nI'm getting error `TypeError: ctx.isComplete is not a function`.\n\nAm I doing something wrong? How to do such things sveltes way?\n\n========================================\n\nCode:\n```text\n<li v-for=\"todo in todos\" v-show=\"!isTodoComplete(todo)\">\n {{ todo }}\n</li>\n```\n\n```text\n{#each todos as todo}\n <li hidden={isComplete(todo)}>{todo}</li>\n{/each}\n...\nmethods: { isComplete (todo) { ... } }\n```\n\n```text\nTypeError: ctx.isComplete is not a function\n```\n\n```text\ntodo\n```\n\n```text\nisComplete\n```\n\n========================================\n\nComments:\n- Thanks Rich, helpers looks more like vues filters for me. Was it intentional decision to make them stateless or it was hard to get them access to state? Maybe there is any doc / article I can read?\n- It's intentional. Unlike with methods, you have no control over *when* the function gets run — it just runs as often as necessary to stay up to date — and so it's important that those functions don't have side effects. Docs here svelte.technology/guide#helpers","metadata":{"transformedAt":"2026-08-18T18:33:40.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":62,"estimatedTokens":337}}659{"id":"stack-57158433","source":"stackoverflow","questionId":57158433,"title":"Accessing Store's value inside loop in SvelteJS v3","tags":["svelte","svelte-store"],"text":"Title: Accessing Store's value inside loop in SvelteJS v3\nTags: svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\ni am building a dashboard from an array of objects that have `store` as some of its property. each store are updated independently from different source.\n\nmy problem is i am unable to read the `store` value inside `each` loop.\n\nto simplify the following code sample, i use `tweened` instead of `store`\n\nthe following code also available in Svlete REPL\nhttps://svelte.dev/repl/9a17102e7d32471a940ba007e5b56db0?version=3.6.7\n\n```\n\n import { tweened } from 'svelte/motion';\n\n const data = [{\n label: 'one',\n value: tweened(0)\n }, {\n label: 'two',\n value: tweened(0)\n }]\n\n {#each data as item}\n \n- {item.label} ({item.$value})\n {/each}\n\n```\n\nthe `{item.$value}` part returns `undefined`\n\n========================================\n\nCode:\n```html\n<script>\n import { tweened } from 'svelte/motion';\n\n const data = [{\n label: 'one',\n value: tweened(0)\n }, {\n label: 'two',\n value: tweened(0)\n }]\n\n</script>\n\n<ul>\n {#each data as item}\n <li>{item.label} ({item.$value})</li>\n {/each}\n</ul>\n```\n\n```text\nstore\n```\n\n```text\nstore\n```\n\n```text\neach\n```\n\n```text\ntweened\n```\n\n```text\nstore\n```\n\n```text\n{item.$value}\n```\n\n```text\nundefined\n```\n\n```html\n<ul>\n {#each data as { label, value }}\n <li>{label} ({$value})</li>\n {/each}\n</ul>\n```\n\n```html\n<ul>\n {#each data as item}\n <ListItem label={item.label} value={item.value}/>\n {/each}\n</ul>\n```\n\n```text\nexport let label, value\n```\n\n```text\n$value\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":110,"estimatedTokens":393}}660{"id":"stack-49723148","source":"stackoverflow","questionId":49723148,"title":"Svelte global styles not working as expected","tags":["svelte"],"text":"Title: Svelte global styles not working as expected\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nSo I have a Svelte component that looks like this:\n\n```\n\n \n\n### Page Title\n\n Some text\n\n Some more text\n\n div :global(p) {\n color: red;\n }\n\n```\n\nMy expectation is that the p tags should be red, but that's not what's happening. I'm using webpack to build the app and the relevant config for Svelte is:\n\n```\n{\n test: /\\.html$/,\n exclude: /node_modules/,\n use: 'svelte-loader'\n}\n```\n\nThe styles that are generated are:\n\n```\ndiv.svelte-f5mkpg :global(p),\n .svelte-f5mkpg div :global(p){color:red}\n```\n\nI'm using Svelte 1.59.0 and svelte-loader 2.5.1. Any idea what's wrong here? I also see this behavior in the default Sapper app. The global CSS is actually in a `global.css` file and the `:global` styles don't seem to take.\n\n========================================\n\nCode:\n```text\n<div id=\"app\">\n <h1>Page Title</h1>\n <p>Some text</p>\n <div><p>Some more text</p></div>\n</div>\n\n\n<style>\n div :global(p) {\n color: red;\n }\n</style>\n```\n\n```text\n{\n test: /\\.html$/,\n exclude: /node_modules/,\n use: 'svelte-loader'\n}\n```\n\n```text\ndiv.svelte-f5mkpg :global(p),\n .svelte-f5mkpg div :global(p){color:red}\n```\n\n```text\nglobal.css\n```\n\n```text\n:global\n```\n\n```js\n{\n test: /\\.html$/,\n exclude: /node_modules/,\n use: {\n loader: 'svelte-loader',\n options: {\n cascade: false\n }\n }\n}\n```\n\n```text\n:global(...)\n```\n\n```text\n:global(...)\n```\n\n```text\noptions.cascade !== false\n```\n\n========================================\n\nComments:\n- Thank you, Rich! That sorted it out for me.","metadata":{"transformedAt":"2026-08-18T18:33:40.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":110,"estimatedTokens":398}}661{"id":"stack-69728630","source":"stackoverflow","questionId":69728630,"title":"Svelte input field text length check","tags":["svelte"],"text":"Title: Svelte input field text length check\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nLearning Svelte.js library and cant seem to be able to solve below issue.\n\nFor some reason value of `l` is evaluated incorrectly, which can be seen in console.\n\nI'm thinking that maybe the `on:input` is incorretly used `` or `check()` function is incorrectly built.\n\n```\n\nlet t = ''\n$: l=t.length\n \n function check() {\n if (l > 5) {\n console.log(l)\n }\n console.log(l)\n }\n\n### Am I a good Svelt dev?\n\nMy code:\n\n{l} chars. {l>240?'NOPE':'I ❤️ Svelte'}.\n\n```\n\nSeems I am not able to figure it out - hence I am unable to do proper text length validation check.\n\nCode can be copied and run on the web:\nhttps://svelte.dev/repl/b0fd6b152bb54383beab850f0feb5e0e?version=3.44.0\n\n========================================\n\nTop Answer:\nI suppose your problem is that the `length` that is logged seems incorrect\n\n```\na -> 0\nab -> 1\nabc -> 2\n```\n\nThis is due to `on:input` being evaluated *before* the `bind:`\n\nSo what happens is:\n\n- the length is 0 because the string is empty\n\n- user presses `a`\n\n- the `on:input` triggers\n\n- the `check` function evaluates the length, but this is still empty and therefore 0\n\n- the `bind:` triggers and the string is updated\n\n- user presses `b`\n\n- `on:input` triggers\n\n- `check` now sees a length of 1 because the string is `a`\n\n- `bind:` set the string the `ab`\n\nIf you want to check the length of the *current* string in your input event you will have to take it from the event parameters\n\n```\nfunction check(ev) {\n const length = ev.target.value.length\n // other stuff here\n}\n```\n\n========================================\n\nCode:\n```text\n<script>\nlet t = ''\n$: l=t.length\n \n function check() {\n if (l > 5) {\n console.log(l)\n }\n console.log(l)\n }\n</script>\n\n<h1>Am I a good Svelt dev?</h1>\n<p>My code:</p>\n<textarea on:input={check} bind:value={t} />\n<p>{l} chars. {l>240?'NOPE':'I ❤️ Svelte'}.</p>\n```\n\n```text\nl\n```\n\n```text\non:input\n```\n\n```text\n<textarea>\n```\n\n```text\ncheck()\n```\n\n```text\ncheck()\n```\n\n```text\non:keyup\n```\n\n```text\non:input\n```\n\n```text\na -> 0\nab -> 1\nabc -> 2\n```\n\n```js\nfunction check(ev) {\n const length = ev.target.value.length\n // other stuff here\n}\n```\n\n```text\nlength\n```\n\n```text\non:input\n```\n\n```text\nbind:\n```\n\n```text\na\n```\n\n```text\non:input\n```\n\n```text\ncheck\n```\n\n```text\nbind:\n```\n\n```text\nb\n```\n\n```text\non:input\n```\n\n```text\ncheck\n```\n\n```text\na\n```\n\n```text\nbind:\n```\n\n```text\nab\n```\n\n```js\n$: l=t.length\n \n$: l && check() // check() is run when l changes and is true\n\n// or\n\n$: l, check() // check() is run every time l changes\n```\n\n```html\n<script>\n \nlet t = ''\n\n$: l=t.length\n \n// $: l, check() // triggers every time l changes\n\n$: l && check() // triggers every time l changes and is true\n \nfunction check() {\n if (l > 5) {\n console.log(l)\n }\n console.log(l)\n}\n \n</script>\n\n<h1>Am I a good Svelt dev?</h1>\n<p>My code:</p>\n<textarea bind:value={t} />\n<p>{l} chars. {l>240?'NOPE':'I ❤️ Svelte'}.</p>\n```\n\n========================================\n\nComments:\n- Whats the problem. Code seems to work fine and no console messages.\n- The code you posted here is not the code in the REPL. Both seem to do what they are supposed to. With the check function you are logging the length always once and twice if its length is greater than 5. What's your exact goal or where do you see the problem?\n- Why change to on:keyup - on:input works fine? With on:keyup more event than necessary (like pressing Shift) are triggered\n- This solved the problem - `on:keyup` instead of `on:input` evaulates `l` correctly. To be more precise for others who posted - if you copy and execute my code - and watch numbers closely in console you will see that `l` evaluates incorrectly.\n- Sure, I was blind... but it's harder to understand a problem if the problem is 'incorrect output' instead of 'logging 0 when it should be 1' - precise description helps :-)","metadata":{"transformedAt":"2026-08-18T18:33:40.708Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":237,"estimatedTokens":988}}662{"id":"stack-62656655","source":"stackoverflow","questionId":62656655,"title":"How to pass the rest of the props to an HTML element using svelte?","tags":["javascript","svelte"],"text":"Title: How to pass the rest of the props to an HTML element using svelte?\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI stuck a bit with a problem:\n\nI have a svelte component, which works with a number of props:\n\n```\n\n export let foo;\n export let bar;\n\n```\n\nBut also, I'd like to pass some props to my HTML element directly.\nSo my solution is:\n\n```\n\n export let foo;\n export let bar;\n\n const {\n foo,\n bar,\n ...other\n } = $$props;\n\n Some action\n\n```\n\nThis one has a huge problem:\nWhen I change some props like \"class\", the component wouldn't be updated.\n\n```\n\n```\n\nWhat is a better way to solve this case? I mean, I have to support different props, not only \"class\" one.\nHow could I pass the rest of the props to an HTML-element\n\n========================================\n\nCode:\n```text\n<script>\n export let foo;\n export let bar;\n\n</script>\n```\n\n```text\n<script>\n export let foo;\n export let bar;\n\n const {\n foo,\n bar,\n ...other\n } = $$props;\n</script>\n\n<button {...other}>\n Some action\n</button>\n```\n\n```text\n<MyComponent {foo} {bar} class={condition ? 'one' : 'two'} />\n```\n\n```text\n<script>\n import MyComponent from './MyComponent.svelte'\n \n let checked\n</script>\n\n<label>\n <input type=checkbox bind:checked />\n Blue?\n</label>\n\n<MyComponent class={checked ? 'blue' : 'red'} />\n```\n\n```text\n<script>\n export let foo\n export let bar\n</script>\n\n<pre>foo={foo} bar={bar}</pre>\n\n<button {...$$restProps}>\n Some button\n</button>\n\n<style>\n :global(.red) {\n color: red;\n }\n :global(.blue) {\n color: blue;\n }\n</style>\n```\n\n```js\nconst {\n foo,\n bar,\n ...other\n } = $$props;\n```\n\n```text\n$: ({ foo, bar, ...other } = $$props)\n```\n\n```text\nlet foo\nlet bar\n$: {\n foo = $$props.foo\n bar = $$props.bar\n}\n```\n\n```text\nApp.svelte\n```\n\n```text\nMyComponent.svelte\n```\n\n```text\n$$restProps\n```\n\n```text\nclass={condition ? 'one' : 'two'}\n```\n\n```text\n$$restProps\n```\n\n```text\n$:\n```\n\n========================================\n\nComments:\n- Oh, that's nice! I didn't know $$restProps exists.","metadata":{"transformedAt":"2026-08-18T18:33:40.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":162,"estimatedTokens":524}}663{"id":"stack-63835251","source":"stackoverflow","questionId":63835251,"title":"Firebase modules cause 'registerComponent' error in Svelte","tags":["javascript","firebase","svelte"],"text":"Title: Firebase modules cause 'registerComponent' error in Svelte\nTags: javascript, firebase, svelte\nSource: Stack Overflow\n\nQuestion:\nIn my svelte project there is a `firebase.js` file that manages the firebase services. The file looks like this:\n\n```\nimport firebase from \"firebase/app\"; // rollup bundle issue with ESM import\nimport \"firebase/firestore\";\nimport \"firebase/auth\";\n\nconst firebaseConfig = {\n // firebase config\n};\n\nconsole.log(firebase);\n\nfirebase.initializeApp(firebaseConfig);\n\nexport const auth = firebase.auth();\nexport const googleProvider = new firebase.auth.GoogleAuthProvider();\n\nexport const db = firebase.firestore();\n```\n\nThis works perfectly fine, however adding firebase modules seems to cause issues.\ne.g. adding `import \"firebase/analytics\";` after the firebase auth an error appears in the browser console\n\n```\nindex.esm.js:1301 Uncaught TypeError: Cannot read property 'registerComponent' of undefined\n at registerInstallations (index.esm.js:1301)\n at index.esm.js:1325\n at main.js:6\n```\n\nthe `index.esm.js` file in question is the `@firebase/installations` file, it appears that the object being passed into `registerInstallations(firebase)` isn't a firebase app object but is instead an object containing 2 firebase app objects, one named `default` and one named `firebase`.\n\nThe only way I've found to fix this is by replacing the calls to `registerInstallations(firebase)` with `registerInstallations(firebase.firebase)` in multiple places throughout node_modules, which does not seem like a good solution.\n\nEdit: I managed to fix this by rebuilding the entire project, including the rollup config and the package.json. Looking through the git changes there are no differences that should have effected this.\n\n========================================\n\nTop Answer:\nHere is my HTML. I use RxFire / RxJs to access firestore.\n\n```\n\n \n \n \n my-project\n \n \n\n \n \n \n \n\n```\n\nAnd the firebase.js (No need for firebase imports now);\n\n```\nvar firebaseConfig = {\n // firebase config\n};\nfirebase.initializeApp(firebaseConfig);\n \nexport const auth = firebase.auth();\nexport const googleProvider = new firebase.auth.GoogleAuthProvider();\nexport const db = firebase.firestore();\n```\n\n========================================\n\nCode:\n```text\nimport firebase from \"firebase/app\"; // rollup bundle issue with ESM import\nimport \"firebase/firestore\";\nimport \"firebase/auth\";\n\nconst firebaseConfig = {\n // firebase config\n};\n\nconsole.log(firebase);\n\nfirebase.initializeApp(firebaseConfig);\n\nexport const auth = firebase.auth();\nexport const googleProvider = new firebase.auth.GoogleAuthProvider();\n\nexport const db = firebase.firestore();\n```\n\n```text\nindex.esm.js:1301 Uncaught TypeError: Cannot read property 'registerComponent' of undefined\n at registerInstallations (index.esm.js:1301)\n at index.esm.js:1325\n at main.js:6\n```\n\n```text\nfirebase.js\n```\n\n```text\nimport \"firebase/analytics\";\n```\n\n```text\nindex.esm.js\n```\n\n```text\n@firebase/installations\n```\n\n```text\nregisterInstallations(firebase)\n```\n\n```text\ndefault\n```\n\n```text\nfirebase\n```\n\n```text\nregisterInstallations(firebase)\n```\n\n```text\nregisterInstallations(firebase.firebase)\n```\n\n```text\nresolve({\n browser: true,\n dedupe: (importee) =>\n importee === \"svelte\" || importee.startsWith(\"svelte/\"),\n mainFields: [\"main\", \"module\"],\n}),\n```\n\n```text\nrollup.config.js\n```\n\n```text\n@rollup/plugin-node-resolve\n```\n\n```text\n./frontend\n```\n\n```text\n./frontend/src/services/firebase.js\n```\n\n```text\n<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"author\" content=\"voscausa\">\n <meta name=\"viewport\" content=\"width=device-width, , initial-scale=1.0\">\n <title>my-project</title>\n <link rel='stylesheet' href='global.css'>\n <link rel='stylesheet' href='/build/bundle.css'>\n</head>\n<body>\n <script src=\"https://www.gstatic.com/firebasejs/7.18.0/firebase-app.js\" defer></script>\n <script src=\"https://www.gstatic.com/firebasejs/7.18.0/firebase-auth.js\" defer></script>\n <script src=\"https://www.gstatic.com/firebasejs/7.18.0/firebase-firestore.js\" defer></script>\n <script src='/build/bundle.js' defer></script>\n</body>\n</html>\n```\n\n```text\nvar firebaseConfig = {\n // firebase config\n};\nfirebase.initializeApp(firebaseConfig);\n \nexport const auth = firebase.auth();\nexport const googleProvider = new firebase.auth.GoogleAuthProvider();\nexport const db = firebase.firestore();\n```\n\n========================================\n\nComments:\n- I had some problem too with firebase modules. Now I'am using hosting URLs. Works fine and limits the project build.\n- how were you able to get svelte to load the firebase URLs before the bundle? or did you use a bunch of callbacks?\n- not the solution i hope for... want a own bundle...","metadata":{"transformedAt":"2026-08-18T18:33:40.708Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":203,"estimatedTokens":1186}}664{"id":"stack-67175956","source":"stackoverflow","questionId":67175956,"title":"\"npm run dev\" Command Doesn't Work - Giving \"missing script: dev\" error","tags":["javascript","node.js","npm","svelte"],"text":"Title: \"npm run dev\" Command Doesn't Work - Giving \"missing script: dev\" error\nTags: javascript, node.js, npm, svelte\nSource: Stack Overflow\n\nQuestion:\nI was trying to run this SVELT GitHub repo on local server:\n\nhttps://github.com/fusioncharts/svelte-fusioncharts\n\nI tried to launch it with \"npm run dev\" command. But I am seeing this error:\n\n`npm ERR! missing script: dev`\n\nI have tried to fix the issue by setting 'ignore-scripts' to false with this command:\n\n`npm config set ignore-scripts false`\n\nBut it doesn't work.\n\nHow can I fix the issue?\n\n========================================\n\nTop Answer:\n`npm ERR! missing script: dev` means it cannot find a script called `dev` inside `package.json`.\n\nThat makes sense!\n\nIt looks at the `package.json` inside the svelte-fusioncharts repo. In that file, there is a `scripts` property.\n\nNotice how that property looks as follows:\n\n```\n\"scripts\": {\n \"build\": \"rollup -c\",\n \"prepublishOnly\": \"npm run build\"\n}\n```\n\nIt does not contain a `dev` script. That’s why it says there’s a missing script. Other commands will work, like `npm run build` or `npm run prepublishOnly`.\n\n========================================\n\nCode:\n```text\nnpm ERR! missing script: dev\n```\n\n```text\nnpm config set ignore-scripts false\n```\n\n```text\nnpm ERR! missing script: dev\n```\n\n```text\ndev\n```\n\n```text\n\"scripts\": {\n \"build\": \"rollup -c\",\n \"prepublishOnly\": \"npm run build\"\n}\n```\n\n```text\nnpm ERR! missing script: dev\n```\n\n```text\ndev\n```\n\n```text\npackage.json\n```\n\n```text\npackage.json\n```\n\n```text\nscripts\n```\n\n```text\ndev\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm run prepublishOnly\n```\n\n```text\n\"scripts\": {\n\"build\": \"cross-env NODE_ENV=production webpack\",\n\"dev\": \"webpack-dev-server --content-base public\" }\n```\n\n```text\nnpm install\nnpm run dev\n```\n\n```text\n\"devDependencies\": {\n \"nodemon\":\"^2.0.15\"\n }\n```\n\n```text\nstart\n```\n\n```text\ndev\n```\n\n```text\ndevDependencies\n```\n\n```text\npackage.json\n```\n\n```text\npackage-lock.json\n```\n\n```text\ndevDependencies\n```\n\n```text\ndependencies\n```\n\n========================================\n\nComments:\n- Did you run `npm i` after you cloned it, like they state in the docs?\n- The `package.json` does not have a script named `dev`\n- If you look on repo package.json under scripts, you can see that script name is \"prepublishOnly\" and its property are npm run dev, you can do npm prepublishOnly\n- There is no `dev` script in the `package.json`. At this point you should open an issue to ping maintainers to clarify the README.\n- @ASDFGerte yes.\n- @johannchopin OK\n- @dev Yes, I noticed it.\n- Yes, that's right. I have to go inside \"examples\" folder. I fixed the issue even before getting your answer. Nonetheless, thank you very much for taking your time looking at my issue.\n- I’ve added an answer below. If that doesn’t help, someone else ran into a similar problem on the GitHub repository: github.com/fusioncharts/svelte-fusioncharts/issues/11 — If you’re still stuck getting in touch with them via GitHub may help","metadata":{"transformedAt":"2026-08-18T18:33:40.708Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":156,"estimatedTokens":747}}665{"id":"stack-76335938","source":"stackoverflow","questionId":76335938,"title":"How to use reactive statements to fetch data from a +server.js handler in SvelteKit?","tags":["svelte","sveltekit"],"text":"Title: How to use reactive statements to fetch data from a +server.js handler in SvelteKit?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am trying to fetch data from a `+server.js` handler like this:\n\n```\n\n let subject = \"Svelte\";\n\n let message = \"\";\n\n // Why does this produce an error?\n $: fetch(`/api/?subject=${subject}`)\n .then((response) => response.json())\n .then((data) => (message = data.message));\n\n{message}\n```\n\nbut I receive this error:\n\nError: Cannot call `fetch` eagerly during server side rendering with relative URL (/api/?subject=Svelte) — put your `fetch` calls inside `onMount` or a `load` function instead\n\nI modeled that page after this REPL example which *does* work, but uses an absolute URL to a remote endpoint. I need to fetch data from a `+server.js` endpoint.\n\nI don't think the `+server.js` code matters in this case, but here it is just in case:\n\n```\nimport { json } from '@sveltejs/kit';\n\nexport async function GET({ url }) {\n const subject = url.searchParams.get(\"subject\");\n return json({ message: `Hello, ${subject}!` });\n}\n```\n\nAccording to the error message, I must put the `fetch` call inside `onMount` or a `load` function.\n\nPutting the code inside `onMount` eliminates the error, but the `fetch` is not reactive. Instead, the `fetch` only executes once and never updates. In addition, I get the following warning:\n\n$: has no effect outside of the top-level\n\nSo if `fetch` calls must be inside `onMount` or `load`, and `$` must be top-level, how do I fetch data from the `+server.js` endpoint in a reactive way?\n\nI create a GitHub repository with the reproducible example.\n\n========================================\n\nCode:\n```text\n<script>\n let subject = \"Svelte\";\n\n let message = \"\";\n\n // Why does this produce an error?\n $: fetch(`/api/?subject=${subject}`)\n .then((response) => response.json())\n .then((data) => (message = data.message));\n</script>\n\n<input bind:value={subject} />\n\n{message}\n```\n\n```text\nimport { json } from '@sveltejs/kit';\n\nexport async function GET({ url }) {\n const subject = url.searchParams.get(\"subject\");\n return json({ message: `Hello, ${subject}!` });\n}\n```\n\n```text\n+server.js\n```\n\n```text\nfetch\n```\n\n```text\nfetch\n```\n\n```text\nonMount\n```\n\n```text\nload\n```\n\n```text\n+server.js\n```\n\n```text\n+server.js\n```\n\n```text\nfetch\n```\n\n```text\nonMount\n```\n\n```text\nload\n```\n\n```text\nonMount\n```\n\n```text\nfetch\n```\n\n```text\nfetch\n```\n\n```text\nfetch\n```\n\n```text\nonMount\n```\n\n```text\nload\n```\n\n```text\n$\n```\n\n```text\n+server.js\n```\n\n```text\n/api/?subject=${subject}\n```\n\n========================================\n\nComments:\n- Thanks! While this technique doesn't fully capture the behavior of reactive statements, it does work great for small projects like this. In a large app where `subject` could be modified in several places, I just have to remember to trigger `load()` in each case.\n- btw, the browser come's from: import { browser } from \"$app/environment\"; and here the same issues from github svelte: github.com/sveltejs/kit/issues/8536","metadata":{"transformedAt":"2026-08-18T18:33:40.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":158,"estimatedTokens":758}}666{"id":"stack-72511903","source":"stackoverflow","questionId":72511903,"title":"Currying Params, or, Component Factories in Svelte","tags":["svelte","svelte-3","svelte-component"],"text":"Title: Currying Params, or, Component Factories in Svelte\nTags: svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI have a simple Svelte component ** which takes two params:\n\n```\n\n export let greeting: string;\n export let name: string;\n\n**{greeting}, {name}!**\n```\n\nHow do I create a **function** which takes a single parameter, *name*, and returns a new component which takes one param, *greeting*, and renders **? Like so:\n\n```\n\n import { greetFactory } from './greetFactory';\n\n const GreetMike = greetFactory('Mike');\n\n// renders \n// which in turn renders **Hello, Mike!**\n```\n\nIn other words: **How do I curry a param of a component?**\n\n========================================\n\nTop Answer:\nThe answer provided by brunnerh does not work in Svelte 5 because components are functions. Because of this, you can't write `new Greet(...)`.\n\nHow can this problem be solved with Svelte 5?\n\nEdit: I found a workaround: Create a new Component called GreetMike.\n\n```\n\n import Greet from './Greet.svelte'\n let {greeting} = $props();\n\n```\n\nfull example\n\nDisadvantage of this workaround: I have to create a new file for every invocation of greetFactory.\n\n========================================\n\nCode:\n```html\n<script lang=ts>\n export let greeting: string;\n export let name: string;\n</script>\n\n<strong>{greeting}, {name}!</strong>\n```\n\n```html\n<script lang=ts>\n import { greetFactory } from './greetFactory';\n\n const GreetMike = greetFactory('Mike');\n</script>\n\n<GreetMike greeting=\"Hello\" />\n// renders <Greet greeting=\"Hello\" name=\"Mike\" />\n// which in turn renders <strong>Hello, Mike!</strong>\n```\n\n```js\nfunction greetFactory(name) {\n return function({ props, ...rest }) {\n return new Greet({\n props: {\n name,\n ...props,\n },\n ...rest\n });\n }\n }\n```\n\n```html\n<script>\n import Greet from './Greet.svelte'\n let {greeting} = $props();\n</script>\n\n<Greet greeting={greeting} name=\"Mike\"/>\n```\n\n```text\nnew Greet(...)\n```\n\n========================================\n\nComments:\n- Thank you so much for asking this question :)\n- If it still works in Svelte 5, I would instead use https://svelte.dev/examples/svelte-component with the spread operator to pass the props.\n- The spread operator also works without : example","metadata":{"transformedAt":"2026-08-18T18:33:40.708Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":106,"estimatedTokens":589}}667{"id":"stack-56520104","source":"stackoverflow","questionId":56520104,"title":"Svelte Each function in Nested Json","tags":["svelte"],"text":"Title: Svelte Each function in Nested Json\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI have nested JSON Array\n\n```\nlet car = [\n{\n name: \"BMW\",\n detail: [\n {name: headlight, type: flame},\n {name: taillight, type: spark},\n ],\n},\n{\n name: \"Merced Benz\",\n detail: [\n {name: headlight, type: spark},\n {name: taillight, type: flame},\n ],\n},]\n```\n\nit's show cars name when i call\n`{#each car as cars}`\n`{cars.name}\n\n`\n`{/each}`\n\nbut \nwhen i call `{cars.detail}` its show `[object Object]` \nand\nwhen i call `{cars.detail.name}` its show `Undefined`\n\ni wanna call each name of detail\n\nplease help me to use this each function at svelte thank you before\n\n========================================\n\nTop Answer:\nAnother approach is to use the map method:\n\n```\n{#each cars as car}\n{car.name}\n \n {car.map((detail)=>{\n return detail.name + \" \" + detail.type\n )}\n \n{/each}\n```\n\n========================================\n\nCode:\n```text\nlet car = [\n{\n name: \"BMW\",\n detail: [\n {name: headlight, type: flame},\n {name: taillight, type: spark},\n ],\n},\n{\n name: \"Merced Benz\",\n detail: [\n {name: headlight, type: spark},\n {name: taillight, type: flame},\n ],\n},]\n```\n\n```text\n{#each car as cars}\n```\n\n```text\n<p>{cars.name}</p>\n```\n\n```text\n{/each}\n```\n\n```text\n{cars.detail}\n```\n\n```text\n[object Object]\n```\n\n```text\n{cars.detail.name}\n```\n\n```text\nUndefined\n```\n\n```html\n<script>\n let cars = [\n {\n name: \"BMW\",\n detail: [\n { name: \"headlight\", type: \"flame\" },\n { name: \"taillight\", type: \"spark\" }\n ]\n },\n {\n name: \"Mercedes-Benz\",\n detail: [\n { name: \"headlight\", type: \"spark\" },\n { name: \"taillight\", type: \"flame\" }\n ]\n }\n ];\n</script>\n\n{#each cars as car}\n <div>{car.name}</div>\n {#each car.detail as detail}\n <div>{detail.name}: {detail.type}</div>\n {/each}\n{/each}\n```\n\n```text\ndetail\n```\n\n```text\n{#each cars as car}\n<div>{car.name}</div>\n <div>\n {car.map((detail)=>{\n return detail.name + \" \" + detail.type\n )}\n </div>\n{/each}\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.708Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":148,"estimatedTokens":515}}668{"id":"stack-73341205","source":"stackoverflow","questionId":73341205,"title":"Why does the icon in this Astro/Svelte component flicker on refresh?","tags":["svelte","astrojs"],"text":"Title: Why does the icon in this Astro/Svelte component flicker on refresh?\nTags: svelte, astrojs\nSource: Stack Overflow\n\nQuestion:\n```\n\n import { onMount } from \"svelte\"; \n let theme = localStorage.getItem('theme') ?? 'light';\n let flag = false;\n onMount(()=>{ \n flag = true\n })\n $: if (flag) {\n if ( theme === 'dark') {\n document.documentElement.classList.add(\"dark\");\n } else {\n document.documentElement.classList.remove(\"dark\");\n } \n localStorage.setItem(\"theme\", theme);\n }\n \n const handleClick = () => { \n theme = (theme === \"light\" ? \"dark\" : \"light\"); \n }; \n\n{theme === \"dark\" ? \"🌕\" : \"🌑\"}\n```\n\nthe icon flickers when dark mode is enabled, in light mode this doesnt happen, I'm assuming this happens because its defaulting to lightmode when it initially renders, how can i fix this?\n\n========================================\n\nTop Answer:\nI faced the same problem: **a brief flash of the \"default\" theme icon** after each page load.\n\nThe theme itself was loaded properly (no flash of light background in dark theme and vice versa) using this short render-blocking script in the `` element that was setting the \"dark\" class on the `` element if found in `localStorage`:\n\n```\n\n \n \n \n const theme = (() => {\n if (\n typeof localStorage !== \"undefined\" &&\n localStorage.getItem(\"theme\")\n ) {\n return localStorage.getItem(\"theme\");\n }\n if (window.matchMedia(\"(prefers-color-scheme: dark)\").matches) {\n return \"dark\";\n }\n return \"light\";\n })();\n \n if (theme === \"light\") {\n document.documentElement.classList.remove(\"dark\");\n } else {\n document.documentElement.classList.add(\"dark\");\n }\n \n \n \n \n \n\n```\n\nAs a toggler, I was using a simple Preact component, used like this:\n\n```\n\n \n\n```\n\n**It was this element that was flickering**. I would not put the whole code here, just the important parts:\n\n```\n// ThemeToggle.tsx\nexport default function ThemeToggle() {\n const theme = signal(localStorage.getItem(\"theme\") ?? \"light\"); \n\n // event handler, etc. omitted…\n\n return (\n \n {theme.value === \"light\" ? : }\n \n );\n}\n```\n\nI suspected there was an issue in my code logic, but there wasn't—it was flickering even when I threw everything but the return block away.\n\nIt was the @wassfila's answer that helped me figured out what was happening. I was using SSG, so what I got from the server was a static HTML string. Since Astro's `client:load` directive implements hydration, it was lazily loaded only after the page was initially rendered. That's why it was flickering! I don't know in detail how Astro does the static render, but since it is done on the server, I only guess that `localStorage.getItem(\"theme\") ?? \"light\"` was resulting in the theme being set to \"light\", because there's no localStorage on server runtime.\n\nThe solution?\n\nI ditched the Preact component because, although Preact is a tiny lib, 3kb of JS is still too much for a simple little toggle. And since I already have the value of the theme on the page when it's being rendered (as a class on the `` element), I **just use CSS and set different visibility** (default/hidden) on the icons **according to the current theme**.\n\n```\n---\n// themeToggle.astro\n---\n\n \n \n \n \n \n \n\n document.getElementById(\"theme-toggle\")?.addEventListener(\n \"click\",\n () => { // theme switch logic, omitted for brevity …}\n );\n }\n\n```\n\nThis is using Tailwind and the \"dark\" class, but it would work the same with, e.g., vanilla CSS and a data attribute instead of class.\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n import { onMount } from \"svelte\"; \n let theme = localStorage.getItem('theme') ?? 'light';\n let flag = false;\n onMount(()=>{ \n flag = true\n })\n $: if (flag) {\n if ( theme === 'dark') {\n document.documentElement.classList.add(\"dark\");\n } else {\n document.documentElement.classList.remove(\"dark\");\n } \n localStorage.setItem(\"theme\", theme);\n }\n \n const handleClick = () => { \n theme = (theme === \"light\" ? \"dark\" : \"light\"); \n }; \n</script>\n\n<button on:click={handleClick}>{theme === \"dark\" ? \"🌕\" : \"🌑\"}</button>\n```\n\n```js\nlet counter = 0\nconst cookie = Astro.cookies.get(\"counter\")\nif(cookie?.value){\n counter = cookie.value\n}\n```\n\n```js\nfunction get_counter(){\n const entry = document.cookie.split(';').find(entry=>entry.replace(' ','').startsWith('counter='))\n if(entry){\n return parseInt(entry.split('=')[1])\n }else{\n return 0\n }\n }\n function set_counter(counter){\n document.cookie = `counter=${counter}`\n console.log(`new counter value = ${counter}`)\n }\n```\n\n```js\n...\nwindow.history.replaceState(null, null, `?session_id=${session_id}`);\n...\nlet session_id = sessionStorage.getItem(\"session_id\")\n...\nsessionStorage.setItem(\"counter\",counter)\n```\n\n```js\nlet session_id = suid()\nif(Astro.url.searchParams.has('session_id')){\n session_id = Astro.url.searchParams.get('session_id')\n console.log(`index.astro> retrieved session_id from url param '${session_id}'`)\n}else{\n console.log(`index.astro> assigned new session_id '${session_id}'`)\n}\n```\n\n```text\n<script>\n```\n\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <!-- etc. -->\n <script is:inline>\n const theme = (() => {\n if (\n typeof localStorage !== \"undefined\" &&\n localStorage.getItem(\"theme\")\n ) {\n return localStorage.getItem(\"theme\");\n }\n if (window.matchMedia(\"(prefers-color-scheme: dark)\").matches) {\n return \"dark\";\n }\n return \"light\";\n })();\n \n if (theme === \"light\") {\n document.documentElement.classList.remove(\"dark\");\n } else {\n document.documentElement.classList.add(\"dark\");\n }\n </script>\n </head>\n <body>\n <!-- etc. -->\n </body>\n</html>\n```\n\n```text\n<header>\n <ThemeToggle client:load/>\n</header>\n```\n\n```text\n// ThemeToggle.tsx\nexport default function ThemeToggle() {\n const theme = signal(localStorage.getItem(\"theme\") ?? \"light\"); \n\n // event handler, etc. omitted…\n\n return (\n <button>\n {theme.value === \"light\" ? <MoonIcon /> : <SunIcon />}\n </button>\n );\n}\n```\n\n```text\n---\n// themeToggle.astro\n---\n<button class=\"relative w-8 h-8\" id=\"theme-toggle\">\n <svg class=\"absolute inset-0 dark:invisible\">\n <!-- etc -->\n </svg>\n <svg class=\"absolute inset-0 invisible dark:visible\">\n <!-- etc -->\n </svg>\n</button>\n\n<script>\n document.getElementById(\"theme-toggle\")?.addEventListener(\n \"click\",\n () => { // theme switch logic, omitted for brevity …}\n );\n }\n</script>\n```\n\n```text\n<head>\n```\n\n```text\n<html>\n```\n\n```text\nlocalStorage\n```\n\n```text\nclient:load\n```\n\n```text\nlocalStorage.getItem(\"theme\") ?? \"light\"\n```\n\n```text\n<html>\n```\n\n========================================\n\nComments:\n- Is color theme / UI flickering bound to happen in multi-page apps at some point as the amount of content increases?\n- no, it should not happens at all if done right, and the flicker is only sensitive to the startup load, so usually rest of content is loaded later and should not influence.","metadata":{"transformedAt":"2026-08-18T18:33:40.708Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":302,"estimatedTokens":1765}}669{"id":"stack-78916095","source":"stackoverflow","questionId":78916095,"title":"Only fire set if object data has changed in Svelte store","tags":["javascript","svelte","svelte-store"],"text":"Title: Only fire set if object data has changed in Svelte store\nTags: javascript, svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\nIn Svelte, when using a `writable` store that takes a single primitive value (e.g. a string), when firing `set` multiple times for the same value, `subscribe` will only be called when the value changes. **Demo in Svelte REPL**\n\nHowever, when storing a complex object, every time `set` is called, even if the object has the same properties, subscribe will still be fired. **Demo in Svelte REPL**\n\nI'm running a fairly expensive external API call on updates (handled via subscribe), so I want to limit if the data hasn't changed. How best should I prevent firing set or listening to subscribe if the data is the same as the previous run?\n\nAn attempt at a solution would be to keep the previous value inside a closure and compare before calling set and then carefully expose which API methods are available for consumers of the store like this:\n\n```\nimport { writable, get } from \"svelte/store\";\n\nconst initialContentState = {\n title: \"\",\n body: \"\",\n};\n\nconst { subscribe, set } = writable(initialContentState);\n\nconst isQuestionEqual = (a,b) => {\n return a.title === b.title && a.body === b.body;\n}\n\nconst initQuestionContentStore = () => {\n let prevValue = initialContentState;\n\n return {\n subscribe,\n reset() {\n set(initialContentState)\n },\n setContent(content) {\n if (!isQuestionEqual(content, prevValue)) {\n set(content);\n prevValue = content;\n }\n }\n }\n}\n\nexport const questionContentStore = initQuestionContentStore()\n```\n\n### Demo in Svelte REPL\n\nHowever, feels weird to have to keep track of the state within the store which is supposed to be responsible for keeping track of state itself. I could also use `get` to fetch the value from the store inside of the `setContent` method, but docs suggest against it for perf reasons\n\n**Note**: This is similar to Why does my Svelte store subscribe() get fired when the value hasn't changed?, but I want a workaround, not a reason.\n\n========================================\n\nCode:\n```js\nimport { writable, get } from \"svelte/store\";\n\nconst initialContentState = {\n title: \"\",\n body: \"\",\n};\n\nconst { subscribe, set } = writable(initialContentState);\n\nconst isQuestionEqual = (a,b) => {\n return a.title === b.title && a.body === b.body;\n}\n\nconst initQuestionContentStore = () => {\n let prevValue = initialContentState;\n\n return {\n subscribe,\n reset() {\n set(initialContentState)\n },\n setContent(content) {\n if (!isQuestionEqual(content, prevValue)) {\n set(content);\n prevValue = content;\n }\n }\n }\n}\n\nexport const questionContentStore = initQuestionContentStore()\n```\n\n```text\nwritable\n```\n\n```text\nset\n```\n\n```text\nsubscribe\n```\n\n```text\nset\n```\n\n```text\nget\n```\n\n```text\nsetContent\n```\n\n```js\nexport function strictWritable(value, equalityComparer, start) {\n const { subscribe, set: originalSet } = writable(value, start);\n\n let previous = value;\n const set = v => {\n if (\n equalityComparer == null\n ? v != previous\n : equalityComparer(previous, v) == false\n ) {\n originalSet(v);\n previous = v;\n }\n };\n\n return {\n subscribe,\n update: cb => set(cb(previous)),\n set,\n }\n}\n```\n\n```text\nwritable\n```\n\n```text\nget\n```\n\n```text\nget\n```\n\n```text\nsubscribe\n```\n\n```text\nset\n```\n\n```text\n{ title, body }\n```\n\n========================================\n\nComments:\n- Thanks so much! Also, re: *\"In your example you actually set the value to a new object\"* - but am I correct in assuming there's not like an update API where I could just mutate the properties on a store rather than assign a brand new object?\n- There isn't an explicit API just for mutation, but you can e.g. do `store.update(x => { x.prop = value; return x; })`, or in a component any `$store.prop = value` mutates the object in the store and sets it to the same object.\n- (`update` exists for convenience on the built-in store, but you also could use `get` + `set` with any store that supports the writable interface. See also this answer.)","metadata":{"transformedAt":"2026-08-18T18:33:40.709Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":168,"estimatedTokens":1057}}670{"id":"stack-72986229","source":"stackoverflow","questionId":72986229,"title":"Type 'boolean' is not assignable to type 'string'.js(2322)","tags":["svelte"],"text":"Title: Type 'boolean' is not assignable to type 'string'.js(2322)\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nGreeting to whomever reads this.\n\nI want to preface this by saying that I'm very new to Svelte and to Component Frameworks as a whole.\n\nWhile working on a small project I needed to use fonts from Google Fonts. I've used these fonts before (in a vanilla JavaScript project) without issue, but this time I had a small problem.\n\nFirst, I didn't know where to put the link tags. After some searching I came across this stackoverflow post How do you load and use a custom font in Svelte, to which I used the second solution.\n\nIn my code, that looks like this\n\n### App.svelte\n\n```\n\n \n \n \n\n```\n\nHowever, I noticed that the was a red line under crossorigin and when I looked at it, it gave me the exception that you can see in the title of this post.\n\nI'd appreciate an explanation on why this is the case and what I can do to solve this. Thank you in advanced to whomever answers this.\n\n========================================\n\nCode:\n```text\n<svelte:head>\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n <link href=\"https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap\" rel=\"stylesheet\">\n</svelte:head>\n```\n\n```text\ncrossorigin=\"\"\n```\n\n```text\ncrossorigin=\"anonymous\"\n```\n\n```text\ncrossorigin\n```\n\n```text\nfalse\n```\n\n```text\ntrue\n```\n\n```text\n'anonymous'\n```\n\n```text\n'use-credentials'\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.709Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":67,"estimatedTokens":377}}671{"id":"stack-76590507","source":"stackoverflow","questionId":76590507,"title":"How to remove steps from being over the drawer","tags":["css","tailwind-css","svelte","sveltekit","daisyui"],"text":"Title: How to remove steps from being over the drawer\nTags: css, tailwind-css, svelte, sveltekit, daisyui\nSource: Stack Overflow\n\nQuestion:\nI'm using DaisyUI and TailwindCSS\n\nI'm using a drawer and steps.\n\n```\n\n \n \n \n Open drawer\n \n \n- Register\n \n- Choose plan\n \n- Purchase\n \n- Receive Product\n \n \n \n \n \n \n \n- Sidebar Item 1\n \n- Sidebar Item 2\n \n \n\n```\n\nThe code is the copy/paste from the first example of the drawer and steps component from DaisyUI.\n\nhttps://i.sstatic.net/GdPgP.png\n\nWhen I click on *\"OPEN DRAWER\"* to open the drawer, the circle of the steps remains above it:\n\nhttps://i.sstatic.net/ihjQ2.png\n\nHow to make the drawer be over the step circles?\n\n========================================\n\nTop Answer:\nConsider increasing the z-stack position of the `.drawer-side` element by applying `z-index: 10` to it via the `z-10` utility class:\n\n\r\n\r\n\n```\n\n \n \n \n Open drawer\n \n \n- Register\n \n- Choose plan\n \n- Purchase\n \n- Receive Product\n \n \n \n \n \n \n \n- Sidebar Item 1\n \n- Sidebar Item 2\n \n \n\n```\n\n========================================\n\nCode:\n```html\n<div class=\"drawer\">\n <input id=\"my-drawer\" type=\"checkbox\" class=\"drawer-toggle\" />\n <div class=\"drawer-content\">\n <!-- Page content here -->\n <label for=\"my-drawer\" class=\"btn btn-primary drawer-button\">Open drawer</label>\n <ul class=\"steps\">\n <li class=\"step step-primary\">Register</li>\n <li class=\"step step-primary\">Choose plan</li>\n <li class=\"step\">Purchase</li>\n <li class=\"step\">Receive Product</li>\n </ul>\n </div>\n <div class=\"drawer-side\">\n <label for=\"my-drawer\" class=\"drawer-overlay\" />\n <ul class=\"menu p-4 w-80 h-full bg-base-200 text-base-content\">\n <!-- Sidebar content here -->\n <li><a>Sidebar Item 1</a></li>\n <li><a>Sidebar Item 2</a></li>\n </ul>\n </div>\n</div>\n```\n\n```html\n<ul class=\"steps isolate\">\n```\n\n```html\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/daisyui/3.1.7/full.min.css\" integrity=\"sha512-XCyMGudVghtcrEkHUSNd/OvlbxUYXLeI0bYO4jm3Tn1olsupuMnMmRRecHPy0kY/AJI2gc6mTzzCPY5DCsPRCg==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\"\n/>\n<script src=\"https://cdn.tailwindcss.com/3.3.2\"></script>\n\n<div class=\"drawer\">\n <input id=\"my-drawer\" type=\"checkbox\" class=\"drawer-toggle\" />\n <div class=\"drawer-content\">\n <!-- Page content here -->\n <label for=\"my-drawer\" class=\"btn btn-primary drawer-button\">Open drawer</label>\n <ul class=\"steps isolate\">\n <li class=\"step step-primary\">Register</li>\n <li class=\"step step-primary\">Choose plan</li>\n <li class=\"step\">Purchase</li>\n <li class=\"step\">Receive Product</li>\n </ul>\n </div>\n <div class=\"drawer-side\">\n <label for=\"my-drawer\" class=\"drawer-overlay\"></label>\n <ul class=\"menu p-4 w-80 h-full bg-base-200 text-base-content\">\n <!-- Sidebar content here -->\n <li><a>Sidebar Item 1</a></li>\n <li><a>Sidebar Item 2</a></li>\n </ul>\n </div>\n</div>\n```\n\n```text\nisolation\n```\n\n```text\nsteps\n```\n\n```text\nsteps\n```\n\n```html\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/daisyui/3.1.7/full.min.css\" integrity=\"sha512-XCyMGudVghtcrEkHUSNd/OvlbxUYXLeI0bYO4jm3Tn1olsupuMnMmRRecHPy0kY/AJI2gc6mTzzCPY5DCsPRCg==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\"\n/>\n<script src=\"https://cdn.tailwindcss.com/3.3.2\"></script>\n\n<div class=\"drawer\">\n <input id=\"my-drawer\" type=\"checkbox\" class=\"drawer-toggle\" />\n <div class=\"drawer-content\">\n <!-- Page content here -->\n <label for=\"my-drawer\" class=\"btn btn-primary drawer-button\">Open drawer</label>\n <ul class=\"steps\">\n <li class=\"step step-primary\">Register</li>\n <li class=\"step step-primary\">Choose plan</li>\n <li class=\"step\">Purchase</li>\n <li class=\"step\">Receive Product</li>\n </ul>\n </div>\n <div class=\"drawer-side z-10\">\n <label for=\"my-drawer\" class=\"drawer-overlay\"></label>\n <ul class=\"menu p-4 w-80 h-full bg-base-200 text-base-content\">\n <!-- Sidebar content here -->\n <li><a>Sidebar Item 1</a></li>\n <li><a>Sidebar Item 2</a></li>\n </ul>\n </div>\n</div>\n```\n\n```text\n.drawer-side\n```\n\n```text\nz-index: 10\n```\n\n```text\nz-10\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.709Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":197,"estimatedTokens":1059}}672{"id":"stack-72241439","source":"stackoverflow","questionId":72241439,"title":"In SvelteKit, is there a way to cancel a popstate event if user state isn't saved?","tags":["javascript","svelte","sveltekit"],"text":"Title: In SvelteKit, is there a way to cancel a popstate event if user state isn't saved?\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a component that allows a user to edit their state. This triggers a `notSaved` variable. I have a `beforeunload` event handler to handle reload and exiting the page to remind the user to save their state, but using SvelteKit, using the back button in the browser doesn't seem to trigger the `beforeunload` event. I also have a `popstate` event handler, because that is triggered when the back button is clicked, but I can't figure out how to prevent the `window.history` from changing if the `notSaved` variable is true.\n\nIs there a way in SvelteKit to trigger a `Changes you made may not be saved.` popup similar to the one that is triggered on a `beforeunload` event when the back or forward button is pressed?\n\n========================================\n\nCode:\n```text\nnotSaved\n```\n\n```text\nbeforeunload\n```\n\n```text\nbeforeunload\n```\n\n```text\npopstate\n```\n\n```text\nwindow.history\n```\n\n```text\nnotSaved\n```\n\n```text\nChanges you made may not be saved.\n```\n\n```text\nbeforeunload\n```\n\n```html\n<script>\n import { beforeNavigate } from '$app/navigation';\n\n let unsavedWork = false;\n let value = 0;\n\n beforeNavigate(({ from, to, cancel }) => {\n if (unsaved) {\n cancel();\n showUnsavedWorkPopup();\n }\n });\n\n function onChange() {\n ...\n unsavedWork = true;\n }\n\n async function save() {\n await ...\n unsavedWork = false;\n }\n</script>\n\n<input type=\"number\" bind:value on:change={onChange}>\n```\n\n```text\nbeforeNavigate\n```\n\n========================================\n\nComments:\n- beforeNavigate/afterNavigate was added in version 227. If you're getting errors about not having a beforeNavigate function, look at your version and make sure you're not running an older version of SvelteKit.","metadata":{"transformedAt":"2026-08-18T18:33:40.709Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":80,"estimatedTokens":483}}673{"id":"stack-73748711","source":"stackoverflow","questionId":73748711,"title":"Sveltekit isn't respecting the ssr = false setting?","tags":["svelte","server-side-rendering","sveltekit"],"text":"Title: Sveltekit isn't respecting the ssr = false setting?\nTags: svelte, server-side-rendering, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm just starting with sveltekit so this is probably something I'm doing wrong, but I have a very basic page based on the SplitPane example in Svelte (https://svelte.dev/repl/5ab84358dd8b46ad9474884f2359ff9b?version=3.50.1) that isn't working because it's rendering on the server and not finding a window object:\n\n```\nwindow is not defined\n ReferenceError: window is not defined\n at HSplitPane.svelte:60:8\n```\n\nThe code lives under routes in \"+page.svelte\":\n\n```\n\n export const ssr = false;\n import { HSplitPane } from 'svelte-split-pane';\n\n \n \n\n \n\n### Welcome to SvelteKit\n\n Visit kit.svelte.dev to read the documentation\n\n \n \n\n \n \n\n main {\n text-align: center;\n margin: 0 auto;\n }\n div.wrapper {\n width: 95%;\n height: 400px;\n margin: auto;\n }\n left, right, top, down {\n width: 100%;\n height: 100%;\n display: block;\n text-align: center;\n }\n left, top {\n background-color:coral\n }\n right, down {\n background-color: cornflowerblue;\n }\n\n```\n\nI was under the impression that the first bit:\n\n```\nexport const ssr = false\n```\n\nwould take care of the error, but that doesn't seem to be doing it. Any help greatly appreciated.\n\n========================================\n\nTop Answer:\nTo disable SSR correctly project-wide, you need to put this in `+layout.js`:\n\n```\nexport const ssr = false;\n```\n\n========================================\n\nCode:\n```text\nwindow is not defined\n ReferenceError: window is not defined\n at HSplitPane.svelte:60:8\n```\n\n```text\n<script>\n export const ssr = false;\n import { HSplitPane } from 'svelte-split-pane';\n</script>\n\n\n<div class=\"wrapper\">\n <HSplitPane leftPaneSize=\"75%\" rightPaneSize=\"25%\" minLeftPaneSize=\"50px\" minRightPaneSize=\"50px\">\n <left slot=\"left\">\n\n <h1>Welcome to SvelteKit</h1>\n <p>Visit <a href=\"https://kit.svelte.dev\">kit.svelte.dev</a> to read the documentation</p>\n\n\n </left>\n <right slot=\"right\">\n\n </right>\n </HSplitPane>\n</div>\n\n\n<style>\n main {\n text-align: center;\n margin: 0 auto;\n }\n div.wrapper {\n width: 95%;\n height: 400px;\n margin: auto;\n }\n left, right, top, down {\n width: 100%;\n height: 100%;\n display: block;\n text-align: center;\n }\n left, top {\n background-color:coral\n }\n right, down {\n background-color: cornflowerblue;\n }\n</style>\n```\n\n```text\nexport const ssr = false\n```\n\n```text\n+page.js\n```\n\n```text\n+page.svelte\n```\n\n```text\nssr\n```\n\n```js\nexport const ssr = false;\n```\n\n```text\n+layout.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.709Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":156,"estimatedTokens":670}}674{"id":"stack-67617548","source":"stackoverflow","questionId":67617548,"title":"Does Svelte store's auto-subscription work in non-component files?","tags":["subscription","svelte","svelte-store"],"text":"Title: Does Svelte store's auto-subscription work in non-component files?\nTags: subscription, svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\nJust a basic question: Is the $-syntax for stores applicable in non-component JavaScript files?\n\nThe doc says:\n\nAny time you have a reference to a store, you can access its value\ninside a component by prefixing it with the $ character.\n\nHowever, this official example seems to use the $-syntax in a derived store which is not a component:\n\n```\nexport const elapsed = derived(\n time,\n $time => Math.round(($time - start) / 1000)\n);\n```\n\nIs this a special case for custom stores? Or is it possible because it gets imported into a component?\n\n========================================\n\nCode:\n```text\nexport const elapsed = derived(\n time,\n $time => Math.round(($time - start) / 1000)\n);\n```\n\n```text\nexport const elapsed = derived(\n time,\n _time => Math.round((_time - start) / 1000)\n);\n```\n\n========================================\n\nComments:\n- `$time` is just a function parameter name, no svelte magic happening here.\n- The import of a JS file into a component does not mean that it gets compiled as well?\n- No. But of course you can use store.subscribe() or use get(store) here to get the currenty store value. Or pass the $store as a function argument to an imported js function. Imported from a js file.","metadata":{"transformedAt":"2026-08-18T18:33:40.709Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":46,"estimatedTokens":342}}675{"id":"stack-71769084","source":"stackoverflow","questionId":71769084,"title":"Sveltekit unable to read data from POST formdata","tags":["svelte","sveltekit"],"text":"Title: Sveltekit unable to read data from POST formdata\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nJust trying the below in Sveltekit (3.44) but the console always outputs:\n\n```\nGot data FormData {}\n```\n\nThe request is simply (made via Postman):\n\n```\ncurl --request POST \\\n --url http://localhost:3000/todos.json \\\n --header 'Content-Type: multipart/form-data; boundary=---011000010111000001101001' \\\n --form test=hello\n```\n\nCode:\n**src/routes/todos/index.json.ts**\n\n```\nexport const post: RequestHandler = async (request) => {\n const data = await request.request.formData();\n console.log('Got data', data);\n return {\n status: 200,\n body: 'text'\n }\n}\n```\n\nOthen than destructuring and cleaning up this code - why is formData empty ?\n\nNB When setting the data line to await request.request.text() I receive (which shows I am receiving data):\n\n```\nGot data --X-INSOMNIA-BOUNDARY\nContent-Disposition: form-data; name=\"test\"\n\nhello\n--X-INSOMNIA-BOUNDARY--\n```\n\n========================================\n\nCode:\n```text\nGot data FormData {}\n```\n\n```text\ncurl --request POST \\\n --url http://localhost:3000/todos.json \\\n --header 'Content-Type: multipart/form-data; boundary=---011000010111000001101001' \\\n --form test=hello\n```\n\n```text\nexport const post: RequestHandler = async (request) => {\n const data = await request.request.formData();\n console.log('Got data', data);\n return {\n status: 200,\n body: 'text'\n }\n}\n```\n\n```text\nGot data --X-INSOMNIA-BOUNDARY\nContent-Disposition: form-data; name=\"test\"\n\nhello\n--X-INSOMNIA-BOUNDARY--\n```\n\n```js\nconst body = await event.request.formData();\n\n// to get everything\nconsole.log(...body); // [\"name\", \"Rich Harris\"] [\"hobbies\", \"svelte\"], [\"hobbies\", \"journalism\"]\n\n// if you know you don't have duplicates\nconsole.log(Object.fromEntries(body)); // { name: \"Rich Harris\", hobbies: \"journalism\" }\n```\n\n```text\nawait request.json()\n```\n\n========================================\n\nComments:\n- Thanks for the answer - shame the resulting code has a typescript error of: Type 'FormData' must have a '[Symbol.iterator]()' method that returns an iterator.ts(2488) for the spread operator and the Object.fromEntries shows a different TS error - Not to be discussed here though :) Thanks for the detailed response","metadata":{"transformedAt":"2026-08-18T18:33:40.709Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":97,"estimatedTokens":572}}676{"id":"stack-64514581","source":"stackoverflow","questionId":64514581,"title":"What is the order that reactive statements are executed in?","tags":["reactive-programming","timing","svelte"],"text":"Title: What is the order that reactive statements are executed in?\nTags: reactive-programming, timing, svelte\nSource: Stack Overflow\n\nQuestion:\nLet's say we have the following component script\n\n```\nlet x = 0;\n\nfunction increase() {\n x += 1;\n}\n\n$: console.log(x)\n\n$: if (x == 4) {\n x = 0;\n}\n```\n\nhttps://svelte.dev/repl/2bca979673114afea9fc6b37434653a3?version=3.29.0\n\nIntuitively I would expect from cotinually calling `increase`, is to have the values `0,1,2,3,4,1,2,3,4,...` logged to the console. But this is not the case. Instead, the second reactive statement runs first, and `4` is never logged; it is `0`. Switching the order of the reactive statements has no effect.\n\nHow do you make the logging statement execute before the other one and what is the reason that it runs second, in the first place?\n\n========================================\n\nCode:\n```js\nlet x = 0;\n\nfunction increase() {\n x += 1;\n}\n\n$: console.log(x)\n\n$: if (x == 4) {\n x = 0;\n}\n```\n\n```text\nincrease\n```\n\n```text\n0,1,2,3,4,1,2,3,4,...\n```\n\n```text\n4\n```\n\n```text\n0\n```\n\n```text\n$: {\n console.log(x) // op 1\n if (x == 4) x = 0 // op 2\n }\n```\n\n========================================\n\nComments:\n- You also postphone a reactive action using setTimeout.","metadata":{"transformedAt":"2026-08-18T18:33:40.709Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":71,"estimatedTokens":314}}677{"id":"stack-71601464","source":"stackoverflow","questionId":71601464,"title":"`Uncaught TypeError: Error resolving module specifier “.prisma/client/index-browser”","tags":["node.js","svelte","prisma","vite","sveltekit"],"text":"Title: `Uncaught TypeError: Error resolving module specifier “.prisma/client/index-browser”\nTags: node.js, svelte, prisma, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have the following error message in my browser upon using sveltekit and the command \"`npm run preview`\":\n\n`Uncaught TypeError: Error resolving module specifier “.prisma/client/index-browser”. Relative module specifiers must start with “./”, “../” or “/”.`\n\nIt references a piece of code that was compiled with \"`npm run build`\" in `localhost:3000/_app/start-b07b1607.js`:\n\n`...s-d1fb5791.js\";import\".prisma/client/index-browser\";let Be=\"\",et=\"\";function ...`\n\nI have tried reproducing this error with using older versions of Prisma, the adaptor and Svelte, switching from pnpm to npm, but nothing helps. I have a MWE repository that comes close to reproducing the error but doesn't actually reproduce it at https://github.com/wvhulle/prisma-sveltekit-bug-report.\n\nHow come the Svelte compiler emits “.prisma/client/index-browser” as a module specifier? Is this an error in Prisma, Vite or something else? The dev mode works without problem.\n\nThe question seems to be related, but is about Vue, not about Svelte.\n\nThanks!\n\n========================================\n\nTop Answer:\nYou need to copy prisma generated files as follows (`package.json`):\n\n```\n{\n \"prisma:inline\": \"cp ./node_modules/.prisma/client/*.js ./node_modules/@prisma/client\",\n \"prisma:generate\": \"prisma generate && npm run prisma:inline\"\n}\n```\n\n========================================\n\nCode:\n```text\nnpm run preview\n```\n\n```text\nUncaught TypeError: Error resolving module specifier “.prisma/client/index-browser”. Relative module specifiers must start with “./”, “../” or “/”.\n```\n\n```text\nnpm run build\n```\n\n```text\nlocalhost:3000/_app/start-b07b1607.js\n```\n\n```text\n...s-d1fb5791.js\";import\".prisma/client/index-browser\";let Be=\"\",et=\"\";function ...\n```\n\n```text\nimport { Enum } from '@prisma/client';\n```\n\n```text\n{\n \"prisma:inline\": \"cp ./node_modules/.prisma/client/*.js ./node_modules/@prisma/client\",\n \"prisma:generate\": \"prisma generate && npm run prisma:inline\"\n}\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- > \"It references a piece of code that was compiled\" < Your code or prisma's?\n- @ClemensTolboom I don't recognize my own code in the Svelte compiled (built) file, so I assume it is Prisma's?\n- You code exists twice `prisma-client/index-browser.js:1:const prisma = require('.prisma/client/index-browser')` and `prisma-client/scripts/backup-index-browser.js:1:const prisma = require('.prisma/client/index-browser')` Not sure but ... you can try to change those into `require('./.prisma/client/index-browser')` to check it fixes it? I learned the existance of hidden dirs :-p\n- @ClemensTolboom Maybe i confused you with the repository and you thought something is wrong with the repository. It works in the repository, since I couldn't reproduce the issue. So I am not sure what you mean with the comment.\n- Your code (not the MWE) has a wrong path which you can edit to see if there's a workaround.\n- I think a better solution is: \\ `resolve: { alias: { \".prisma/client/index-browser\": \"./node_modules/.prisma/client/index-browser.js\" } }` \\ from github.com/prisma/prisma/issues/12504#issuecomment-128588308‌​3 \\ (if that doesnt work, maybe use `@` instead of `.`, `'.prisma/client/index-browser': './node_modules/@prisma/client/index-browser.js',`)","metadata":{"transformedAt":"2026-08-18T18:33:40.709Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":80,"estimatedTokens":887}}678{"id":"stack-74831314","source":"stackoverflow","questionId":74831314,"title":"Simple reactivity experiment in Svelte fails in unexpected ways. Vue equivalent doesn't","tags":["vue.js","svelte","svelte-component","svelte-store"],"text":"Title: Simple reactivity experiment in Svelte fails in unexpected ways. Vue equivalent doesn't\nTags: vue.js, svelte, svelte-component, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI'm learning Svelte after having used Vue for a while, but am a bit confused by some strange reactivity issues with Svelte.\n\nI have this simple code:\n\n### Svelte Snippet\n\n```\n\nlet count = 0\n$: tripleCount = count * 3\nconst increaseCount = () => count++\n\n$: if (tripleCount > 6) count = 0\n\n Clicked {count} {count === 1 ? 'time' : 'times'}\n\n Triple count is: {tripleCount}\n\n```\n\nBut, when I try to run it on Svelte's playground, I get an error message alerting me that there is a `Cyclical dependency detected: tripleCount → count → tripleCount`.\n\nI've found a few ways to fix that issue and get the Svelte component to work as intended. But, I'm curious about why I get that issue, given that there isn't any logical loop that'd be impossible to close. The equivalent code in Vue works perfectly fine.\n\n### Vue Equivalent Snippet\n\n```\n\nimport { computed, ref, watchEffect } from 'vue'\n\nconst count = ref(0)\nconst tripleCount = computed(() => count.value * 3)\nconst incrementCount = () => count.value++\n\nwatchEffect(() => {\n if (tripleCount.value > 6) count.value = 0\n})\n\n Clicked {{ count }} {{ count === 1 ? 'time' : 'times' }}\n\nTriple count is: {{ tripleCount }}\n\n```\n\n### Live Demo of Expected Behavior\n\nYou can ignore the code in the snippet below since it's not too relevant to my question and is already described more simply above.\n\n*Just run the snippet below to see what I'm trying to get my Svelte component to do.*\n\n\r\n\r\n\n```\n\n const { createApp, ref, computed, watchEffect } = Vue\n\n createApp({\n setup() {\n const count = ref(0)\n const tripleCount = computed(() => count.value * 3)\n const incrementCount = () => count.value++\n\n watchEffect(() => {\n if (tripleCount.value > 6) count.value = 0\n })\n\n return {\n count,\n tripleCount,\n incrementCount,\n }\n },\n template: `\n \n Clicked {{ count }} {{ count === 1 ? 'time' : 'times' }}\n \n Triple count is: {{ tripleCount }}\n\n `,\n }).mount('#app')\n\n```\n\n\r\n\r\n\r\n\n### Possible Solutions and New Issues\n\n### Approach A: Indirect Update\n\nAn interesting workaround to avoid getting the `Cyclical dependency` error is to change count indirectly, through an intermediary `resetCount` function.\n\n```\n\n// $: if (tripleCount > 6) count = 0\n\nconst resetCount = () => count = 0\n\n$: if ($tripleCount > 6) resetCount()\n\n```\n\nLogically, this implementation is no different from the original, but somehow the `Cyclical dependency` error goes away.\n\nHowever, some new unexpected behavior arises. When `tripleCount` is greater than `6` and `count` is therefore reset to `0`, `tripleCount` **does not update**. It retains its last value (`9` in this case), and its reactivity doesn't reactivate until the next click of the button.\n\nWhy does `tripleCount` not react to the change of `count` when `count` is reset?\n\n### Approach B: Indirect Update + Delay\n\nIf I add a delay before the reset helper sets count to 0, the code will work as its Vue equivalent, with the correct behavior.\n\n```\n\nconst resetCount = () => {\n setTimeout(() => count = 0, 0) // zero ms delay\n}\n\n$: if ($tripleCount > 6) resetCount()\n\n```\n\nWhy does this delay help `tripleCount` react to the change in `count`? I guess using `setTimeout` is helping Svelte exit that event loop and only then handle the reactivity of the change. But, it seems quite error-prone to me that I have to be mindful of not forgetting to add these delays for a supposedly computed value to be able to pick up on all the changes of the value it's dependent on.\n\nIs there a better way of making sure `tripleCount` reacts to the resetting of `count`?\n\nAs can be seen in the Vue implementation, I didn't need to use any indirect `resetCount` auxiliary function nor `setTimeout` hack to get the expected behavior.\n\n### Approach C: Stores\n\nAfter further experimentation, I managed to get my Svelte component to work as intended by using stores like this:\n\n```\n\n import { writable, derived } from 'svelte/store';\n\n const count = writable(0);\n const tripleCount = derived(count, $count => $count * 3);\n\n function incrementCount() {\n count.update(n => n + 1);\n }\n\n $: if ($tripleCount > 6) {\n count.set(0);\n }\n\n Clicked {$count} {$count === 1 ? 'time' : 'times'}\n\nTriple count is: {$tripleCount}\n\n```\n\nWould this be the recommended way to work with reactivity in Svelte? I am a bit sad because it takes away much of the simplicity that made me want to learn Svelte. I know all frameworks rely on stores for state management at some point, but it seems overkill that I need to use them to implement logic as basic as the one I was trying to implement.\n\n**I'd be extremely grateful for any guidance or feedback on the issues I presented here. Thank you so much for reading and for any help \n\n- Why does the intuitive way (`$: if (tripleCount > 6) count = 0`) not work?\n\n- Why does the indirect reset trick (`$: if (tripleCount > 6) resetCount()` avoid the `Cyclical dependency` error?\n\n- Why does the immediate delay trick (`setTimeout(() => count = 0, 0)`) ensure `tripleCount` does update after `count` is reset?\n\n- Is there a way to get the expected behavior in Svelte without an auxiliary `resetCount` function, nor a `setTimeout` hack, nor by resorting to using Svelte Stores yet?\n\n========================================\n\nTop Answer:\nAs Bob clearly pointed out in his answer, a single variable cannot be updated twice in a single update cycle (a `tick` in Svelte lingo).\n\nThat double update requirement becomes obvious when you try to pack your update code into the smallest possible function:\n\n```\nfunction processUpdate(_count) {\n tripleCount = count * 3\n if (tripleCount > 6) {\n count = 0\n tripleCount = 0 // this is the second time tripleCount is updated\n } \n}\n```\n\nIn truth, the only way around your issue is to eliminate the cyclic dependency (as pointed out by Svelte's error message, incidentally) altogether.\n\nThis means reducing the reactive statements that cause this cyclical dependency to a single reactive statement based on one of the variables.\n\nWe can do this by reusing the minimal update function stated above:\n\n```\n\nlet count = 0\nlet tripleCount = 0\n\n$: processUpdate(count)\n\nconst processUpdate = (_count) => {\n tripleCount = count * 3\n if (tripleCount > 6) {\n count = 0\n tripleCount = 0\n } \n}\n\nconst increaseCount = () => {\n count++;\n} \n\n Clicked {count} {count === 1 ? 'time' : 'times'}\n\n Triple count is: {tripleCount}\n\n```\n\nAnd this works as you would expect: REPL\n\n========================================\n\nCode:\n```svelte\n<script>\nlet count = 0\n$: tripleCount = count * 3\nconst increaseCount = () => count++\n\n$: if (tripleCount > 6) count = 0\n</script>\n\n<button on:click={increaseCount}>\n Clicked {count} {count === 1 ? 'time' : 'times'}\n</button>\n\n<p>\n Triple count is: {tripleCount}\n</p>\n```\n\n```vue\n<script setup>\nimport { computed, ref, watchEffect } from 'vue'\n\nconst count = ref(0)\nconst tripleCount = computed(() => count.value * 3)\nconst incrementCount = () => count.value++\n\nwatchEffect(() => {\n if (tripleCount.value > 6) count.value = 0\n})\n\n</script>\n\n<template>\n<button @click=\"incrementCount\">\n Clicked {{ count }} {{ count === 1 ? 'time' : 'times' }}\n</button>\n\n<p>Triple count is: {{ tripleCount }}</p>\n</template>\n```\n\n```html\n<script src=\"https://unpkg.com/vue@3/dist/vue.global.prod.js\"></script>\n\n<div id=\"app\"></div>\n\n<script>\n const { createApp, ref, computed, watchEffect } = Vue\n\n createApp({\n setup() {\n const count = ref(0)\n const tripleCount = computed(() => count.value * 3)\n const incrementCount = () => count.value++\n\n watchEffect(() => {\n if (tripleCount.value > 6) count.value = 0\n })\n\n return {\n count,\n tripleCount,\n incrementCount,\n }\n },\n template: `\n <button @click=\"incrementCount\">\n Clicked {{ count }} {{ count === 1 ? 'time' : 'times' }}\n </button>\n <p>Triple count is: {{ tripleCount }}</p>\n `,\n }).mount('#app')\n</script>\n```\n\n```svelte\n<script>\n// $: if (tripleCount > 6) count = 0\n\nconst resetCount = () => count = 0\n\n$: if ($tripleCount > 6) resetCount()\n</script>\n```\n\n```svelte\n<script>\nconst resetCount = () => {\n setTimeout(() => count = 0, 0) // zero ms delay\n}\n\n$: if ($tripleCount > 6) resetCount()\n</script>\n```\n\n```svelte\n<script>\n import { writable, derived } from 'svelte/store';\n\n const count = writable(0);\n const tripleCount = derived(count, $count => $count * 3);\n\n function incrementCount() {\n count.update(n => n + 1);\n }\n\n $: if ($tripleCount > 6) {\n count.set(0);\n }\n</script>\n\n<button on:click={incrementCount}>\n Clicked {$count} {$count === 1 ? 'time' : 'times'}\n</button>\n\n<p>Triple count is: {$tripleCount}</p>\n```\n\n```text\nCyclical dependency detected: tripleCount → count → tripleCount\n```\n\n```text\nCyclical dependency\n```\n\n```text\nresetCount\n```\n\n```text\nCyclical dependency\n```\n\n```text\ntripleCount\n```\n\n```text\n6\n```\n\n```text\ncount\n```\n\n```text\n0\n```\n\n```text\ntripleCount\n```\n\n```text\n9\n```\n\n```text\ntripleCount\n```\n\n```text\ncount\n```\n\n```text\ncount\n```\n\n```text\ntripleCount\n```\n\n```text\ncount\n```\n\n```text\nsetTimeout\n```\n\n```text\ntripleCount\n```\n\n```text\ncount\n```\n\n```text\nresetCount\n```\n\n```text\nsetTimeout\n```\n\n```text\n$: if (tripleCount > 6) count = 0\n```\n\n```text\n$: if (tripleCount > 6) resetCount()\n```\n\n```text\nCyclical dependency\n```\n\n```text\nsetTimeout(() => count = 0, 0)\n```\n\n```text\ntripleCount\n```\n\n```text\ncount\n```\n\n```text\nresetCount\n```\n\n```text\nsetTimeout\n```\n\n```html\n<script>\nlet count = 0\n\n$: tripleCount = count * 3\n\nconst increaseCount = () => {\n count++;\n if (count * 3 > 6) count = 0;\n} \n\n</script>\n\n<button on:click={increaseCount}>\n Clicked {count} {count === 1 ? 'time' : 'times'}\n</button>\n\n<p>\n Triple count is: {tripleCount}\n</p>\n```\n\n```text\nimport { tick } from \"svelte\";\n\nconst increaseCount = async () => {\n count++;\n await tick();\n if (tripleCount > 6) count = 0\n}\n```\n\n```js\nconst resetCount = () => tick().then(() => count = 0)\n```\n\n```js\n$: tripleCount = count * 3\n\n<div>{count === 1 ? 'time' : 'times'}</div>\n```\n\n```js\nfunction updateData(changes) {\n if (hasCountChanged(changes)) {\n tripleCount = count * 3\n }\n}\nfunction updateView(changes) {\n if (hasTripleCountChanged(changes)) {\n updateTheText(count === 1 ? 'time' : 'times')\n }\n}\n```\n\n```text\nfunction resetCount() {\n count = 0\n invalidate('count')\n}\nfunction updateData(changes) {\n if (hasCountChanged(changes)) {\n tripleCount = count * 3\n }\n if (hasTripleCountChanged(changes)) {\n if (tripleCount > 6) {\n resetCount()\n }\n }\n}\n```\n\n```text\ninvalide()\n```\n\n```text\nresetCount()\n```\n\n```js\nfunction processUpdate(_count) {\n tripleCount = count * 3\n if (tripleCount > 6) {\n count = 0\n tripleCount = 0 // this is the second time tripleCount is updated\n } \n}\n```\n\n```html\n<script>\nlet count = 0\nlet tripleCount = 0\n\n$: processUpdate(count)\n\nconst processUpdate = (_count) => {\n tripleCount = count * 3\n if (tripleCount > 6) {\n count = 0\n tripleCount = 0\n } \n}\n\nconst increaseCount = () => {\n count++;\n} \n</script>\n\n<button on:click={increaseCount}>\n Clicked {count} {count === 1 ? 'time' : 'times'}\n</button>\n\n<p>\n Triple count is: {tripleCount}\n</p>\n```\n\n```text\ntick\n```\n\n========================================\n\nComments:\n- Your 4th option won't work as the OP expects it to do, see this REPL. The underlying issue is the OP expects one variable, `count`, to update *twice* in a single tick cycle, which simply isn't possible as you correctly stated.\n- Of course, i've updated the 4th option with a inline and tick() options","metadata":{"transformedAt":"2026-08-18T18:33:40.709Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":45,"totalLines":583,"estimatedTokens":2913}}679{"id":"stack-67577252","source":"stackoverflow","questionId":67577252,"title":"What causes the \"ctx[1] is not a function\" error in this small Svelte app?","tags":["javascript","svelte"],"text":"Title: What causes the \"ctx[1] is not a function\" error in this small Svelte app?\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI am working on a small to-do app with Svelte. I list 10 todos from jsonplaceholder.\n\nI have this in App.svelte:\n\n```\n\n import { onMount } from \"svelte\";\n import Header from './Header.svelte';\n import ToDoList from './ToDoList.svelte';\n import Footer from './Footer.svelte';\n const apiURL = \"https://jsonplaceholder.typicode.com/todos\";\n const limit = 10;\n let todos = [];\n export let unsolvedTodos = [];\n \n onMount(() => {\n getTodos();\n });\n \n const getTodos = () => {\n fetch(`${apiURL}?&_limit=${limit}`)\n .then(res => res.json())\n .then((data) => todos = data)\n .then(getUnsolvedTodos);\n }\n \n const getUnsolvedTodos = () => {\n unsolvedTodos = todos.filter(todo => {\n return todo.completed === false;\n })\n }\n\n const deleteTodo = (todo) => {\n let itemIdx = todos.findIndex(x => x == todo);\n todos.splice(itemIdx, 1);\n todos = todos;\n }\n\n \n \n \n \n \n\n```\n\nIn ToDoList.app:\n\n```\n\n import TodoItem from './TodoItem.svelte';\n export let todos;\n let deleteTodo;\n\n{#if todos.length > 0}\n \n {#each todos as todo, index}\n \n {/each}\n \n{/if}\n```\n\nIn TodoItem.svelte:\n\n```\n\n import {createEventDispatcher} from 'svelte';\n import { fade, fly } from 'svelte/transition';\n import { flip } from 'svelte/animate';\n export let todo;\n \n const dispatch = createEventDispatcher();\n const Delete = () => dispatch(\"deleteTodo\", todo);\n\n \n {todo.title}\n **\n\n```\n\nI must be missing something because I get the error `ctx[1] is not a function` as can be seen in this **REPL**.\n\nWhat am I doing wrong?\n\n========================================\n\nCode:\n```text\n<script>\n import { onMount } from \"svelte\";\n import Header from './Header.svelte';\n import ToDoList from './ToDoList.svelte';\n import Footer from './Footer.svelte';\n const apiURL = \"https://jsonplaceholder.typicode.com/todos\";\n const limit = 10;\n let todos = [];\n export let unsolvedTodos = [];\n \n onMount(() => {\n getTodos();\n });\n \n const getTodos = () => {\n fetch(`${apiURL}?&_limit=${limit}`)\n .then(res => res.json())\n .then((data) => todos = data)\n .then(getUnsolvedTodos);\n }\n \n const getUnsolvedTodos = () => {\n unsolvedTodos = todos.filter(todo => {\n return todo.completed === false;\n })\n }\n\n const deleteTodo = (todo) => {\n let itemIdx = todos.findIndex(x => x == todo);\n todos.splice(itemIdx, 1);\n todos = todos;\n }\n</script>\n\n<div class=\"app-wrapper\">\n <div id=\"toDoApp\">\n <Header />\n <ToDoList todos={todos} />\n <Footer />\n </div>\n</div>\n```\n\n```text\n<script>\n import TodoItem from './TodoItem.svelte';\n export let todos;\n let deleteTodo;\n</script>\n\n{#if todos.length > 0}\n <ul class=\"todo-list\">\n {#each todos as todo, index}\n <TodoItem {todo} on:deleteTodo = {deleteTodo(todo)} />\n {/each}\n </ul>\n{/if}\n```\n\n```text\n<script>\n import {createEventDispatcher} from 'svelte';\n import { fade, fly } from 'svelte/transition';\n import { flip } from 'svelte/animate';\n export let todo;\n \n const dispatch = createEventDispatcher();\n const Delete = () => dispatch(\"deleteTodo\", todo);\n</script>\n\n<li transition:fly=\"{{x:-100, duration:200}}\">\n <input type=\"checkbox\" checked=\"{todo.completed}\" />\n <span class=\"title {todo.completed ? 'done' : ''}\">{todo.title}</span>\n <button on:click=\"{Delete}\"><i class=\"fa fa-trash\" aria-hidden=\"true\"></i></button>\n</li>\n```\n\n```text\nctx[1] is not a function\n```\n\n```text\nToDoList.svelte\n```\n\n```text\ndeleteTodo(todo)\n```\n\n```text\ndeleteTodo\n```\n\n```text\non:deleteTodo = {() => deleteTodo(todo)}\n```\n\n```text\non:deleteTodo = {deleteTodo}\n```\n\n========================================\n\nComments:\n- I have `let deleteTodo` in ToDoList.svelte, at the top. I also have ``. See **REPL**.\n- You have `let deleteTodo` but that is a variable not a function definition so nothing happens when you call it like a function. Also as Leander said you're calling it wrong if you want to pass an argument to the function using an event handler, it won't work as `{function(arg)}` you need `{()=> function(arg)}`. This answer is correct.\n- Maybe you want to pass the `deleteTodo` function which is declared in `App.svelte` to `ToDoList`. so `let deleteTodo;` has to become `export let deleteTodo;`and `` can become `` or the shorthand ``. It's not the best pattern to but it works","metadata":{"transformedAt":"2026-08-18T18:33:40.709Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":201,"estimatedTokens":1122}}680{"id":"stack-71562140","source":"stackoverflow","questionId":71562140,"title":"Is there any way how to pass component/html into string in Svelte?","tags":["javascript","string","components","svelte"],"text":"Title: Is there any way how to pass component/html into string in Svelte?\nTags: javascript, string, components, svelte\nSource: Stack Overflow\n\nQuestion:\nWhat I am trying to achieve is to pass component into a string of a variable or some similar solution. I have tried {@html someVariable} but it works for me only in one way it means text from string to HTML. But I need the text from HTML to string. I've tried document.elementById() but always get return 'document is not defined'. Here is an example of what I'm trying to achieve:\n\n```\nApp.svelte\n\nimport Component from './component.svelte';\nimport Description from './description .svelte';\n\n// How to declare component/html into variable?\n\nlet test = 'something like but acceptable by variable'\nlet lala = test;\n\n```\n\n```\nDescription.svelte\n\nexport let lala;\n\n{#if something}\n{@lala html}\n{:else if something }\nnope\n{/if}\n```\n\nI think that this question Rendering Svelte components from HTML string has kind of the answer but I failed to make it functional.\n\n========================================\n\nCode:\n```text\nApp.svelte\n\n<script>\nimport Component from './component.svelte';\nimport Description from './description .svelte';\n\n\n// How to declare component/html into variable?\n\nlet test = 'something like <Component /> but acceptable by variable'\nlet lala = test;\n\n</script>\n\n<Description {test} />\n```\n\n```text\nDescription.svelte\n\n<script>\nexport let lala;\n</script>\n\n{#if something}\n{@lala html}\n{:else if something }\nnope\n{/if}\n```\n\n```html\n<!-- App.svelte -->\n<script>\n import Component from './Component.svelte';\n import Description from './Description.svelte';\n</script>\n\n<Description component={Component} />\n```\n\n```html\n<!-- Description.svelte -->\n<script>\n export let component;\n</script>\n\n{#if component}\n <svelte:component this={component}></svelte:component>\n{:else}\n component isn't set\n{/if}\n```\n\n```text\n<svelte:component>\n```\n\n```text\n<svelte:component>\n```\n\n========================================\n\nComments:\n- What problem did you face when trying to implement the question you linked to?\n- @Smitop I don't know how to create a custom element from a web component. I am using Svelte.Kit and still have the error that customElement:true is missing since Svelte.kit doesn't have rollup.config.js but svelte.config.js without plugin section I am not sure where should I add that line.\n- Why you just don't import Component.svelte into Description.svelte and then use it in that if?\n- @Jardulino I'm trying to create a universal component that can be used multiple times through the app, only with differences in variables. In your scenario, I would have to copy the whole component many times and have a lot of duplicate code.\n- Thank you Antonio, for your time and solution to both my questions. Your solution with leads me to the other solution that can help me with this problem.","metadata":{"transformedAt":"2026-08-18T18:33:40.709Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":108,"estimatedTokens":719}}681{"id":"stack-64247315","source":"stackoverflow","questionId":64247315,"title":"Svelte get all properties on current svelte file","tags":["svelte","svelte-3"],"text":"Title: Svelte get all properties on current svelte file\nTags: svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nHow to get all properties on current svelte file?\n\nfor example this `Component1.svelte`\n\n```\n\n let x = '';\n let y = '';\n let z = '';\n\n onMount(function(){\n console.log( what? ); \n // need to print x, y, and z which set by other code\n // that using/importing this file\n // without defining one by one, was there such property?\n });\n\n{x}\n{y}\n{z}\n\n```\n\nUsed by `whatever.svelte`\n\n```\n\n import Foo from `./Component1.svelte`\n\ntest\n```\n\n========================================\n\nCode:\n```html\n<script>\n let x = '';\n let y = '';\n let z = '';\n\n onMount(function(){\n console.log( what? ); \n // need to print x, y, and z which set by other code\n // that using/importing this file\n // without defining one by one, was there such property?\n });\n</script>\n<span>{x}</span>\n<div>{y}</div>\n<p>{z}</p>\n```\n\n```html\n<script>\n import Foo from `./Component1.svelte`\n</script>\n<Foo x=\"1\" y=\"abc\">test</Foo>\n```\n\n```text\nComponent1.svelte\n```\n\n```text\nwhatever.svelte\n```\n\n```text\n$$props\n```\n\n========================================\n\nComments:\n- And you’ll have all properties without `export`declaration by `$$restProps`: svelte.dev/docs#Attributes_and_props","metadata":{"transformedAt":"2026-08-18T18:33:40.709Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":81,"estimatedTokens":319}}682{"id":"stack-56596998","source":"stackoverflow","questionId":56596998,"title":"How to use locally built Svelte 3 compiler in locally running Svelte REPL site?","tags":["svelte"],"text":"Title: How to use locally built Svelte 3 compiler in locally running Svelte REPL site?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI'm playing around with Svelte and cloned it from its Github repository. I can run the REPL from site directory, but it uses Svelte from unpkg url. I would like to try my locally built compiler and use it instead of the unpkg version. So far I could not find any steps/references. Please guide me with the steps to make it work.\n\n========================================\n\nCode:\n```text\n# Steps to build Svelte and use it in REPL site\n\ngit clone https://github.com/sveltejs/svelte.git\nexport PUBLISH=\"publish\" \ncd svelte\nnpm install\nnpm run dev\ncd site\nnpm install && npm run update\nnpm run dev\n\nPoint your browser to http://localhost:3000/repl?version=local\n```\n\n```text\nsvelte/site\n```\n\n```text\nREADME.md\n```\n\n```text\nREADME.md\n```\n\n========================================\n\nComments:\n- does not work any more :)","metadata":{"transformedAt":"2026-08-18T18:33:40.709Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":41,"estimatedTokens":237}}683{"id":"stack-59675433","source":"stackoverflow","questionId":59675433,"title":"Svelte store not updating on screen","tags":["svelte","svelte-3","svelte-store"],"text":"Title: Svelte store not updating on screen\nTags: svelte, svelte-3, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI'm new to Svelte, and I'm making a rookie mistake. I have a websocket connection to a server, and I am logging hundreds of messages and adding them to a store, but the page does not update at all.\n\n**App.svelte**\n\n```\n\n import Socket from \"./Socket.svelte\"\n import msgs from './stores'\n\n \n\n```\n\n**Socket.svelte**\n\n```\n\n export let items\n\n{items.length}\n{#if items}\n {#each items as msg, i}\n {i} {msg}\n\n {/each}\n{:else}\n waiting...\n\n{/if}\n```\n\n**socket.js**\n\n```\nimport { readable, writable } from 'svelte/store';\n\nlet msgs = []\nconst msgStore = readable(msgs)\nexport default msgStore\n\nconst socket = new WebSocket(\"ws://localhost:8080/socket\");\n\nsocket.binaryType = \"arraybuffer\";\n\nsocket.onopen = function (event) {\n msgs = [...msgs, \"Connected\"];\n};\n\nsocket.onmessage = function (event) {\n msgs = [...msgs, event];\n console.log(msgs.length)\n\n const msg = JSON.parse(event.data)\n const msgType = msg.messageType\n console.log(msgType)\n};\n```\n\nIn the browser, I get the `0` for the initial length of the items array, but it never updates, even though messages are flowing.\n\n========================================\n\nCode:\n```text\n<script>\n import Socket from \"./Socket.svelte\"\n import msgs from './stores'\n</script>\n\n<main>\n <Socket items=\"{$msgs}\"/>\n</main>\n```\n\n```text\n<script>\n export let items\n</script>\n\n{items.length}\n{#if items}\n {#each items as msg, i}\n <p>{i} {msg}</p>\n {/each}\n{:else}\n <p class=\"loading\">waiting...</p>\n{/if}\n```\n\n```text\nimport { readable, writable } from 'svelte/store';\n\nlet msgs = []\nconst msgStore = readable(msgs)\nexport default msgStore\n\nconst socket = new WebSocket(\"ws://localhost:8080/socket\");\n\nsocket.binaryType = \"arraybuffer\";\n\nsocket.onopen = function (event) {\n msgs = [...msgs, \"Connected\"];\n};\n\nsocket.onmessage = function (event) {\n msgs = [...msgs, event];\n console.log(msgs.length)\n\n const msg = JSON.parse(event.data)\n const msgType = msg.messageType\n console.log(msgType)\n};\n```\n\n```text\n0\n```\n\n```js\nconst msgs = []\nexport const msgStore = writable([])\n\nsocket.onmessage(e => {\n ...\n msgs.push(msg)\n msgStore.set(msgs)\n})\n```\n\n```js\nexport const publicMsgStore = derived(msgStore, x => x)\n```\n\n```js\nexport const msgStore = readable([], set => {\n const msgs = []\n ...\n socket.onmessage(e => {\n ...\n msgs.push(msg)\n set(msgs) // <= UPDATE THE STORE!!\n })\n})\n```\n\n```text\nmsgStore\n```\n\n```text\nmsgs\n```\n\n```text\nset\n```\n\n========================================\n\nComments:\n- Thanks, @rixo. One thing I'll add for the next perplexed n00b... In Socket.svelte you have to `import { msgStore } from './socket'` Then `let items` Then `let unsubscribe = msgStore.subscribe(msgs => { items = msgs })`. In your HTML you can then iterate over items with `{#each items as msg}...`","metadata":{"transformedAt":"2026-08-18T18:33:40.709Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":166,"estimatedTokens":723}}684{"id":"stack-68875517","source":"stackoverflow","questionId":68875517,"title":"Svelte - watch changes to component property outside the component (accessors)","tags":["javascript","svelte","svelte-3"],"text":"Title: Svelte - watch changes to component property outside the component (accessors)\nTags: javascript, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nIs it possible to watch changes to a component property outside the component?\n\nI have tried using the `$:` declaration but it does not seem to work (except for the first time - detecting when the component is mounted).\n\nI.e. this is the component which property changes from the inside\n\n```\n\n export let title = 'Settings';\n\n setTimeout(() => {\n title = 'Settings - Test';\n }, 2000);\n\n//\n\n```\n\nand the component that includes it:\n\n```\n\n import SettingsPage from './Settings.svelte';\n \n let page; \n let title = '';\n \n $: {\n if (typeof page !== 'undefined') {\n title = page.title;\n }\n }\n \n $: title2 = typeof page !== 'undefined' ? page.title : '';\n \n\nAfter 2 seconds, the titles should change to \"Settings - test\" (it does not work).\n\n### title: {title}\n\n### title2: {title2}\n\n \n\n```\n\nPlayground: https://svelte.dev/repl/91ef762b9f414223835fc1f08f20bd5d?version=3.42.2\n\nUnfortunately the reactive declaration does not fire on this instance. Is there a way to make this work purely with regular properties? (I know there are workarounds, such as using a store as the property - but I would like to just have it as regular prop if possible).\n\n========================================\n\nCode:\n```text\n<script>\n export let title = 'Settings';\n\n setTimeout(() => {\n title = 'Settings - Test';\n }, 2000);\n\n//\n</script>\n\n<svelte:options accessors={true}/>\n```\n\n```text\n<script>\n import SettingsPage from './Settings.svelte';\n \n let page; \n let title = '';\n \n $: {\n if (typeof page !== 'undefined') {\n title = page.title;\n }\n }\n \n $: title2 = typeof page !== 'undefined' ? page.title : '';\n \n</script>\n\nAfter 2 seconds, the titles should change to \"Settings - test\" (it does not work).\n\n<h3>title: {title}</h3>\n<h3>title2: {title2}</h3>\n\n<div class=\"Page\">\n <svelte:component this={SettingsPage} bind:this={page} />\n</div>\n```\n\n```text\n$:\n```\n\n```text\ntitle\n```\n\n```text\nSettingsPage\n```\n\n```text\n<SettingsPage bind:title={title} />\n```\n\n```text\ntitle\n```\n\n========================================\n\nComments:\n- Is there a reason why you not just bind the `title` prop like ``. Here is an example that works fine with this structure svelte.dev/repl/605d1fd526f042b584150c9477343f9a?version=3.4‌​2.2.\n- Yep, this is a solution. Thank you.\n- Can I put it as the answer?\n- Sure, please go ahead.","metadata":{"transformedAt":"2026-08-18T18:33:40.709Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":126,"estimatedTokens":629}}685{"id":"stack-79121537","source":"stackoverflow","questionId":79121537,"title":"Not able to understand the effect function: speed up, slow down example in Svelte5 documentation","tags":["svelte","svelte-5"],"text":"Title: Not able to understand the effect function: speed up, slow down example in Svelte5 documentation\nTags: svelte, svelte-5\nSource: Stack Overflow\n\nQuestion:\nSvelte5 introduces `effect` function. On the documentation page there is an example of a simple counter with an option to increase / decrease the interval using `setInterval` function.\n\nHere is the code:\n\n```\n\n let elapsed = $state(0);\n let interval = $state(1000);\n \n $effect(() => {\n const id = setInterval(()=>{\n elapsed += 1;\n }, interval)\n \n });\n \n\n interval /= 2}>speed up\n interval *= 2}>slow down\n\nelapsed: {elapsed}\n\n```\n\nWhen we click the `speed up` button the interval gets updated and the new counter runs fast.\n\nHowever, when we click the `slow down` button, the interval gets updated but the speed doesn't reduce.\n\nThe explanation given on the doc page is as follows:\n\nThat’s because we’re not clearing out the old intervals when the\neffect updates. We can fix that by returning a cleanup function:\n\nNow the question is that when we are not clearing out the old intervals then the `speed up` should also not work.\n\nWhy do we have a case where `speed up` is working but `slow down` is not working when both lead to change of state i.e. `interval` value.\n\n========================================\n\nCode:\n```text\n<script>\n let elapsed = $state(0);\n let interval = $state(1000);\n \n $effect(() => {\n const id = setInterval(()=>{\n elapsed += 1;\n }, interval)\n \n });\n \n</script>\n\n<button onclick={() => interval /= 2}>speed up</button>\n<button onclick={() => interval *= 2}>slow down</button>\n\n<p>elapsed: {elapsed}</p>\n```\n\n```text\neffect\n```\n\n```text\nsetInterval\n```\n\n```text\nspeed up\n```\n\n```text\nslow down\n```\n\n```text\nspeed up\n```\n\n```text\nspeed up\n```\n\n```text\nslow down\n```\n\n```text\ninterval\n```\n\n========================================\n\nComments:\n- The other part that helps understand is the documentation for `setInterval()`, notably the return value. I had assumed that function was something to do with Svelte on first reading.","metadata":{"transformedAt":"2026-08-18T18:33:40.710Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":101,"estimatedTokens":513}}686{"id":"stack-64066662","source":"stackoverflow","questionId":64066662,"title":"Sapper/Svelte/Rollup external dependencies best practice?","tags":["node.js","yarnpkg","svelte","rollupjs","sapper"],"text":"Title: Sapper/Svelte/Rollup external dependencies best practice?\nTags: node.js, yarnpkg, svelte, rollupjs, sapper\nSource: Stack Overflow\n\nQuestion:\nSmart people!\n\nI’m a bundler-beginner with a bundler slash dependency-question.\n\n- On `yarn dev run` I get the error: *\"Cannot find module '@sveltejs/svelte-scroller'...\"*\n\n- I have a sapper/svelte/rollup/yarn-suite\n\n- the svelte-scroller-plugin\n\nThe plugin is by default loaded as an external in rollup.config.js:\n\n```\n{ ..., server: { ..., external: } ... }\n```\n\nAnd when I use it in a .svelte-component:\n\n```\nimport Scroller from '@sveltejs/svelte-scroller';\n\n//...\n\n```\n\n...the error slaps my face.\n\n### Notes\n\nrollup.config.js is unchanged from the template clone\n\nIf I remove the plugin from the dependencies-arr loaded as externals in rollup.config.js **the error goes away**.\n\n...which tells me that rollup *shouldn't* load the dependency as an external (assuming the only goal is to make the specified error vanish).\n\nAnd since svelte-scroller's purpose here is client-interaction-related, I presume it shouldn't be a part of the bundle either way.\n\nOf course cyberspace has related issues, but I can't seem to find a clear best practice example on how to handle this.\n\nMy current workaround is therefore:\n\n```\n// in rollup.config.js\n import pkg from './package.json';\n\n // filter out those \"not external dependencies\" \n const notExternals = ['@sveltejs/svelte-scroller'];\n const externals = Object.keys(pkg.dependencies).filter(plugin =>\n notExternals.some(not => not === plugin) ? false : true\n );\n\n export default {\n // ...,\n server: {\n // ...,\n // bundle filtered externals (along with default built in modules)\n external: externals.concat(require('module').builtinModules),\n },\n // ...\n }\n```\n\nAnd if the error revisits with another dependency, I'll just add it to the notExternals-arr.\n\n### Question\n\n- **Considering the sapper/svelte/rollup-setup, is this approach best practice when handling client-based plugins causing similar errors?**\n\nThanks in advance!\n\n### Stack\n\n```\ninternal/modules/cjs/loader.js:896\n throw err;\n ^\n\nError: Cannot find module '@sveltejs/svelte-scroller'\nRequire stack:\n\n - /.../__sapper__/dev/server/server.js\n at Function.Module._resolveFilename (internal/modules/cjs/loader.js:893:15)\n at Function.Module._load (internal/modules/cjs/loader.js:743:27)\n at Module.require (internal/modules/cjs/loader.js:965:19)\n at require (internal/modules/cjs/helpers.js:88:18)\n at Object. (/.../__sapper__/dev/server/server.js:8:16)\n at Module._compile (internal/modules/cjs/loader.js:1076:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)\n at Module.load (internal/modules/cjs/loader.js:941:32)\n at Function.Module._load (internal/modules/cjs/loader.js:782:14)\n at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) {\n code: 'MODULE_NOT_FOUND',\n requireStack: [\n '/.../__sapper__/dev/server/server.js'\n ]\n}\n```\n\n### Reproduce if you dare\n\ntemplate\n\n```\nnpx degit \"sveltejs/sapper-template#rollup\" \n```\n\nplugin\n\n```\nyarn add @sveltejs/svelte-scroller\n```\n\nimport the plugin to a .svelte-component\n\n```\n\n import Scroller from '@sveltejs/svelte-scroller';\n\n//...\n\n```\n\ngo\n\n```\nyarn run dev\n```\n\n========================================\n\nCode:\n```text\n{ ..., server: { ..., external: <**package.json-dependencies-arr**> } ... }\n```\n\n```text\nimport Scroller from '@sveltejs/svelte-scroller';\n\n//...\n\n<Scroller />\n```\n\n```text\n// in rollup.config.js\n import pkg from './package.json';\n\n // filter out those \"not external dependencies\" \n const notExternals = ['@sveltejs/svelte-scroller'];\n const externals = Object.keys(pkg.dependencies).filter(plugin =>\n notExternals.some(not => not === plugin) ? false : true\n );\n\n export default {\n // ...,\n server: {\n // ...,\n // bundle filtered externals (along with default built in modules)\n external: externals.concat(require('module').builtinModules),\n },\n // ...\n }\n```\n\n```text\ninternal/modules/cjs/loader.js:896\n throw err;\n ^\n\nError: Cannot find module '@sveltejs/svelte-scroller'\nRequire stack:\n\n - /.../__sapper__/dev/server/server.js\n at Function.Module._resolveFilename (internal/modules/cjs/loader.js:893:15)\n at Function.Module._load (internal/modules/cjs/loader.js:743:27)\n at Module.require (internal/modules/cjs/loader.js:965:19)\n at require (internal/modules/cjs/helpers.js:88:18)\n at Object.<anonymous> (/.../__sapper__/dev/server/server.js:8:16)\n at Module._compile (internal/modules/cjs/loader.js:1076:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)\n at Module.load (internal/modules/cjs/loader.js:941:32)\n at Function.Module._load (internal/modules/cjs/loader.js:782:14)\n at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) {\n code: 'MODULE_NOT_FOUND',\n requireStack: [\n '/.../__sapper__/dev/server/server.js'\n ]\n}\n```\n\n```text\nnpx degit \"sveltejs/sapper-template#rollup\" <app-name>\n```\n\n```text\nyarn add @sveltejs/svelte-scroller\n```\n\n```text\n<script>\n import Scroller from '@sveltejs/svelte-scroller';\n</script>\n\n//...\n\n<Scroller />\n```\n\n```text\nyarn run dev\n```\n\n```text\nyarn dev run\n```\n\n```text\nyarn add -D @sveltejs/svelte-scroller\n```\n\n```text\n@sveltejs/svelte-scroller\n```\n\n```text\ndependencies\n```\n\n```text\nexternal\n```\n\n```text\ndevDependencies\n```\n\n========================================\n\nComments:\n- Hi @Kiiim, this is a very good question except for one point: you should try to ask a single question; preferably whose answer doesn't involve personal opinion. This makes the question easier to answer and to the point, which can also benefit other people with similar issues.\n- @guzmonne yeah, it's sooo hard to keep things concise when your questions feels chained. But I agree, edited :)\n- Of all responses, this clearly stands out! Jokes aside, dressing all similar non js-modules as devDeps apparently works. And yeah, it seems kind of logical to let the compiler do its work. Also the word ”conventional” gives me inner peace when moving forward with this approach. Thanks sir @Rich.","metadata":{"transformedAt":"2026-08-18T18:33:40.710Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":247,"estimatedTokens":1537}}687{"id":"stack-59829088","source":"stackoverflow","questionId":59829088,"title":"How can I run a Svelte/Sapper app over HTTPS/SSL?","tags":["ssl","https","svelte","sapper"],"text":"Title: How can I run a Svelte/Sapper app over HTTPS/SSL?\nTags: ssl, https, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI can't seem to find anything about running Svelte apps over https. I would like to run on https for both dev and prod. I am able to change the port with `--port` argument in the scripts in package.json, but obviously that doesn't change the protocol from http to https.\n\n========================================\n\nTop Answer:\nThis has noting to do with sapper. Just use the options of your server framework. Do you use express or polka? their instructions!\n\n========================================\n\nCode:\n```text\n--port\n```\n\n```js\nimport sirv from 'sirv';\nimport polka from 'polka';\nimport compression from 'compression';\nimport * as sapper from '@sapper/server';\n\nconst { PORT, NODE_ENV } = process.env;\nconst dev = NODE_ENV === 'development';\n\npolka() // You can also use Express\n .use(\n compression({ threshold: 0 }),\n sirv('static', { dev }),\n sapper.middleware()\n )\n .listen(PORT, err => {\n if (err) console.log('error', err);\n });\n```\n\n```js\nimport sirv from 'sirv';\nimport polka from 'polka';\nimport compression from 'compression';\nimport * as sapper from '@sapper/server';\n\nconst { PORT, NODE_ENV } = process.env;\nconst dev = NODE_ENV === 'development';\n\nconst { createServer } = require('https');\nconst { readFileSync } = require('fs');\nconst ssl_port = 443;\n\nconst options = {\n // The path & file names could be different.\n key: readFileSync('/home/ubuntu/ssl/private.key'),\n cert: readFileSync('/home/ubuntu/ssl/certificate.crt')\n};\n\nconst { handler } = polka()\n .use(\n compression({ threshold: 0 }),\n sirv('static', { dev }),\n sapper.middleware()\n )\n .get('*', (req, res) => {\n res.end(`POLKA: Hello from ${req.pathname}`);\n });\n\n// Mount Polka to HTTPS server\ncreateServer(options, handler).listen(ssl_port, _ => {\n console.log(`> Running on https://localhost:${ssl_port}`);\n});\n```\n\n```js\nconst { createServer } = require('https');\nconst { readFileSync } = require('fs');\nconst ssl_port = 443;\n\nconst options = {\n // The path & file names could be different.\n key: readFileSync('/home/ubuntu/ssl/private.key'),\n cert: readFileSync('/home/ubuntu/ssl/certificate.crt')\n};\n```\n\n```js\nconst { handler } = polka()\n .use(\n compression({ threshold: 0 }),\n sirv('static', { dev }),\n sapper.middleware()\n )\n .get('*', (req, res) => {\n res.end(`POLKA: Hello from ${req.pathname}`);\n });\n\n// Mount Polka to HTTPS server\ncreateServer(options, handler).listen(ssl_port, _ => {\n console.log(`> Running on https://localhost:${ssl_port}`);\n});\n```\n\n```sh\n$ sudo npm run dev\n\n> TODO@0.0.1 dev /home/ubuntu/ensayar-sapper\n> sapper dev\n\n✔ server (2.1s)\n✔ client (2.1s)\n> Running on https://localhost:443\n✔ service worker (42ms)\n> Server is not listening on port 3000\n```\n\n```text\ncertificate.crt\n```\n\n```text\nprivate.key\n```\n\n```text\nserver.js\n```\n\n```text\n<sapper project directory>/src/server.js\n```\n\n```text\nserver.js\n```\n\n```text\nsudo\n```\n\n```text\nsudo npm run dev\n```\n\n```text\nsudo npm run start\n```\n\n```text\nsudo npm run dev\n```\n\n```text\nServer is not listening on port 3000\n```\n\n========================================\n\nComments:\n- There is a solution here using Devilbox and the default Svelte template.\n- ofc it is possible to use Sapper over https. Sapper uses Express middleware which has many options\n- \"he answered his own question with the best knowledge he had at the time, let's get him!\"\n- \"he made up something that was the first thing he came across and posted it for all to get wrong direction, yes let's get him\"\n- You sound like a fascinating person and I would like to get to know you better, add me on LinkedIn?\n- More-mature frameworks like React and Angular support running dev mode with SSL/HTTPS out of the box. It seems Svelte isn't there yet (or should I say sirv-cli). You're absolutely right, for prod we can use Express, Polka, etc.\n- @jspinella, I love to use tools that are focusing on their goal. I never use https in dev mode and in production it's highly recommended to use a reverse proxy which cares for all the security stuff.\n- Related for devs using Devilbox. Thank you for pointing this out! I am going through how to get things right with the default Svelte Template as well as with Svelte HMR. Otherwise if you would not mind adding the code for those templates you know what to do. ;)","metadata":{"transformedAt":"2026-08-18T18:33:40.710Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":167,"estimatedTokens":1121}}688{"id":"stack-58417881","source":"stackoverflow","questionId":58417881,"title":"Sapper/Svelte: How do I add markdown files?","tags":["markdown","svelte","sapper"],"text":"Title: Sapper/Svelte: How do I add markdown files?\nTags: markdown, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI am creating a blog using Sapper using the default sapper-template-rollup. \n\nIn the blog folder, it does mention about generating data from markdown files. But I can't find how to do it?\n\n========================================\n\nTop Answer:\nI published https://github.com/mikenikles/sapper-template-with-markdown which shows how to use the default Sapper template, but uses `*.md` files for the blog post content.\n\nThe main change was in `src/routes/blog/_posts.js` where I replaced the content with:\n\n```\nconst fs = require('fs');\nconst frontMatter = require('front-matter');\nconst marked = require('marked');\n\nconst posts = fs.readdirSync('./src/posts').map(postFilename => {\n const postContent = fs.readFileSync(`./src/posts/${postFilename}`, {\n encoding: 'utf8'\n });\n const postFrontMatter = frontMatter(postContent);\n return {\n title: postFrontMatter.attributes.title,\n slug: postFrontMatter.attributes.slug,\n html: marked(postFrontMatter.body)\n }\n});\n\nposts.forEach(post => {\n post.html = post.html.replace(/^\\t{3}/gm, '');\n});\n\nexport default posts;\n```\n\nThen, each blog post is stored in `src/posts` as a Markdown file with the following format:\n\n```\n---\ntitle: 'What is Sapper?'\nslug: 'what-is-sapper'\n---\n\nYour markdown content.\n```\n\n========================================\n\nCode:\n```text\nmarked\n```\n\n```text\nsnarkdown\n```\n\n```text\n.md\n```\n\n```text\n.md\n```\n\n```text\n.svelte\n```\n\n```text\n.md\n```\n\n```js\nconst fs = require('fs');\nconst frontMatter = require('front-matter');\nconst marked = require('marked');\n\nconst posts = fs.readdirSync('./src/posts').map(postFilename => {\n const postContent = fs.readFileSync(`./src/posts/${postFilename}`, {\n encoding: 'utf8'\n });\n const postFrontMatter = frontMatter(postContent);\n return {\n title: postFrontMatter.attributes.title,\n slug: postFrontMatter.attributes.slug,\n html: marked(postFrontMatter.body)\n }\n});\n\nposts.forEach(post => {\n post.html = post.html.replace(/^\\t{3}/gm, '');\n});\n\nexport default posts;\n```\n\n```text\n---\ntitle: 'What is Sapper?'\nslug: 'what-is-sapper'\n---\n\nYour markdown content.\n```\n\n```text\n*.md\n```\n\n```text\nsrc/routes/blog/_posts.js\n```\n\n```text\nsrc/posts\n```\n\n========================================\n\nComments:\n- Look for a markdown loader plugin for your module bundler (webpack, rollup ..)\n- It's pretty straightforward, you can make use of the `marked` package and you can absolutely refer to how svelte has built its own blog page. Check it out here github.com/sveltejs/svelte/blob/master/site/src/routes/blog/‌​…\n- See also this Sapper blog template via Brittney in the Sapper channel on the Svelte Discord, a great place to ask questions and chat.\n- I see that all the posts will have a link right after the Top-Level Domain Ex `www.example.com/post1`, `www.example.com/post2`. But what if someone using the template wants to categorize the posts. Ex `www.example.com/svelte-posts/post1`, `www.example.com/vuejs-posts/post1`\n- @JustineKizhak So you are looking to add categories on one blog or have 2 separate blogs?\n- Is there a difference between categories and 2 separate blogs on the same website? I was thinking of categories of blogs like tech blog and another blog of travelling etc. Right now I don't care if there are no categories but in future, I might. So right now I want to put in the work of dealing with the codebase, later then I just have to focus on the content.\n- @JustineKizhak If you want traditional WordPress-style categories I would add that to the markdown front matter of the posts (Jekyll docs) and then create a category page template using dynamic parameters, with links to any categories in your individual post templates as well.\n- @JustineKizhak However, if there are a limited number of categories you know ahead of time, and you want the category in the URL before the post name, it might be simpler, though limiting over time, to have separate blogs/folders of posts and use those the way the Svelte site uses the `blog` folder. This would not work well if you wanted a traditional chronological index of all of the posts from any category though, so if you did want that use the front matter approach above and not worry about the URL for individual posts.\n- @JustineKizhak Also in my experience, tags are almost always better than categories, because you can add as many as you like. What if you wrote a post comparing Svelte and Vue? Why not have it appear in both? Then you want tags not categories. WordPress has a long, confusing history with this where I think they finally made categories behave like tags because they got sick of dealing with people using categories when they wanted tags and complaining.\n- @JustineKizhak added a separate question about this to help future searchers, please feel free to continue the conversation or add your own answers over there.\n- Now I see, tags does offer more flexibility but about categories can't we do something in `js` to parse and save blogs of different categories in separate json files like `svelte-posts.json`, `vue-posts.json` as I understand a post can't belong to more than 1 category. So a `[category]/index.svelte` could only fetch the respective `json` and render it chronologically. I can see myself using both categories and tags. Categories as groups and tags for filtering. But I guess for filtering, I will have to do server-side setup too.\n- I will try to figure out a solution and post on your question. Thanks for answering.","metadata":{"transformedAt":"2026-08-18T18:33:40.710Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":138,"estimatedTokens":1402}}689{"id":"stack-70543107","source":"stackoverflow","questionId":70543107,"title":"Is this code hidden for the client in sveltekit?","tags":["javascript","svelte","sveltekit"],"text":"Title: Is this code hidden for the client in sveltekit?\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nWill the api key be hidden from the user?\n\n```\n# $lib/config.js\n\nimport { initializeApp } from 'firebase/app';\nimport { getFirestore } from \"firebase/firestore/lite\";\n \n \nconst firebaseConfig = {\n apiKey: \"my-key\",\n};\n \nconst app = initializeApp(firebaseConfig);\n \nexport const db = getFirestore(app);\n\n#index.svelte\n\nimport {db} from \"$lib/config\"\n\ndb.get...and so on\n```\n\nTrying to understand how to deal with things you want to keep hidden in sveltekit as normally js is visible for the user if wanted through source.\n\n========================================\n\nCode:\n```text\n# $lib/config.js\n\nimport { initializeApp } from 'firebase/app';\nimport { getFirestore } from \"firebase/firestore/lite\";\n \n \nconst firebaseConfig = {\n apiKey: \"my-key\",\n};\n \nconst app = initializeApp(firebaseConfig);\n \nexport const db = getFirestore(app);\n\n\n#index.svelte\n\nimport {db} from \"$lib/config\"\n\ndb.get...and so on\n```\n\n```js\nimport {db} from \"$lib/config\"\n\ndb.get...and so on\n```\n\n```js\n<script context=\"module\">\n /** @type {import('@sveltejs/kit').Load} */\n export async function load({ params, fetch, session, stuff }) {\n const url = `index.json`;\n const res = await fetch(url);\n\n if (res.ok) {\n return {\n props: {\n article: await res.json()\n }\n };\n }\n\n return {\n status: res.status,\n error: new Error(`Could not load ${url}`)\n };\n }\n</script>\n```\n\n```text\nindex.svelte\n```\n\n```text\nindex.json.js\n```\n\n```text\nindex.svelte\n```\n\n========================================\n\nComments:\n- Does this answer your question? How to use dotenv in SvelteKit project?\n- Everything you want to hide from the user has to be on the server side. You can’t hide API keys if they are used client side.\n- @t.niese So how do I do that? Will config.js be visible for the user if I build this and add the app to server?\n- I haven't used this firebase sdk before, but you can check your browser's network tab to see if your api key is visible or not.\n- @ambiguous58 Yes. I guess it will not be, but I don't understand how as it is js, when seeing this youtu.be/OTxIcU_2Qos . Otherwise apiKey is visible for the user.\n- You should make the firebase API:s requests on the server side. Your above example will expose the firebase API Key to the clients since it's directly imported in a .svelte file.\n- @OskarHane How do I do that? SSR using fetch?\n- Thank you. Best answer. Someone said: \"It's normal to have the key on the client like that, all access to resources can be controlled via security rules\". Any comment? I like the simplicity of not having to hide the apiKey on the server but want it to be secure. Btw, my code works. It talks to firestore.","metadata":{"transformedAt":"2026-08-18T18:33:40.710Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":109,"estimatedTokens":730}}690{"id":"stack-71032856","source":"stackoverflow","questionId":71032856,"title":"How to change Tailwind CSS background color with Svelte, based on a value unpacked in #each?","tags":["javascript","tailwind-css","svelte","tailwind-ui"],"text":"Title: How to change Tailwind CSS background color with Svelte, based on a value unpacked in #each?\nTags: javascript, tailwind-css, svelte, tailwind-ui\nSource: Stack Overflow\n\nQuestion:\nI am a beginner in both Svelte and Tailwind and want to avoid an XY-Problem, so here is my goal:\n\nI generate rows of a table with an `#each` loop in Svelte. (6 values per row). I now want to conditionally color the background of this row based on one value (the battery charge).\n\nMy idea was to conditionally render different tags based on this value. Like this:\n\n```\n{#each allLZ as {id, name, mac, status, lastcontact, battery}, i}\n \n {#if battery > 70}\n \n {:else if battery > 40}\n \n {:else }\n \n {/if}\n```\n\nBut this doesn't work as Svelte wants to see the tags closed to be full elements, not piecemeal code, fair enough.\n\nSo is there a good way to change tailwind background color based on a value unpacked in `#each`?\n\n========================================\n\nTop Answer:\nI would recommend having a function that give you back the background color according to the `batteryValue` like:\n\n```\nlet getBatteryColor = (batteryValue) => {\n if (batteryValue > 70) return 'green'\n if (batteryValue > 40) return 'yellow'\n return 'red'\n}\n```\n\n...and then consume it in the node's class:\n\n```\n\n ...\n\n```\n\nHave a look at the REPL.\n\n========================================\n\nCode:\n```text\n{#each allLZ as {id, name, mac, status, lastcontact, battery}, i}\n \n {#if battery > 70}\n <tr class=\"bg-green-50\">\n {:else if battery > 40}\n <tr class=\"bg-yellow-50\">\n {:else }\n <tr class=\"bg-red-50\">\n {/if}\n```\n\n```text\n#each\n```\n\n```text\n#each\n```\n\n```html\n{#each allLZ as {id, name, mac, status, lastcontact, battery}, i}\n<tr\n class:bg-red-500={battery < 39}\n class:bg-yellow-500={battery >= 40 && battery < 70}\n class:bg-green-500={ battery >= 70}>\n\n <td>{name}/{battery}</td>\n\n</tr>\n{/each}\n```\n\n```text\nclass:name\n```\n\n```js\nlet getBatteryColor = (batteryValue) => {\n if (batteryValue > 70) return 'green'\n if (batteryValue > 40) return 'yellow'\n return 'red'\n}\n```\n\n```html\n<tr class={`bg-${getBatteryColor(batteryValue)}`}>\n <td>...</td>\n</tr>\n```\n\n```text\nbatteryValue\n```\n\n========================================\n\nComments:\n- That nearly works (with added quotes after the equals-sign) but only ever colors red or green. The middle condition (with the AND) never triggers. Are you sure this is possible to do?\n- Please click on the \"repl link\" at the bottom, should see the three conditions triggered. Could you eventually paste your `allLZ`? PS. the quotes are not required.\n- Oh, I overlooked that one. Thanks a lot! My stupid mistake. Tailwind didnt have a yellow-50 apparently. yellow-100 did the trick. !\n- Easier to unit test relative to @Paolo's answer?","metadata":{"transformedAt":"2026-08-18T18:33:40.710Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":115,"estimatedTokens":705}}691{"id":"stack-73729939","source":"stackoverflow","questionId":73729939,"title":"How to properly wrap a third party component in Svelte","tags":["javascript","event-handling","svelte","wrapper","svelte-component"],"text":"Title: How to properly wrap a third party component in Svelte\nTags: javascript, event-handling, svelte, wrapper, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI'm trying to wrap a third party svelte component, but I can't figure the proper and clean way to do this.\n\n**Context** : I'm using a design system (carbon design system through `carbon-components-svelte`). I want to wrap their `` in a custom component with my own validation rules to use through my whole application.\n\n**Problem** : I can't figure out how to forward all events from `` through my custom component.\n\nhttps://github.com/sveltejs/svelte/issues/2837 talks about an `on:*` directive that would be nice but after some research, it seems like Svelte devs don't really like the idea.\n\nhttps://github.com/hperrin/svelte-material-ui/blob/273ded17c978ece3dd87f32a58dd9839e5c61325/components/forwardEvents.js could be a solution but it uses svelte actions through `use:` directive but it not available on components, only on DOM elements.\n\nSo what is the correct way of doing this then ? Should I add my handlers one by one with `on:possibleEvent={event => dispatch(event)}` ? Thats seems really heavy, especially for a textInput, and not dynamic at all.\n\n**Code** :\n\nHere is my wrapper Component :\n`sanitizedField.svelte`\n\n```\n\n import { TextInput } from 'carbon-components-svelte'\n import { createEventDispatcher } from \"svelte\";\n\n const dispatch = createEventDispatcher();\n\n export let value\n \n function thirdPartyForwarder(ev) {\n dispatch(ev.type, ev.detail)\n }\n\n```\n\nAnd How I use it :\n`Page.svelte`\n\n```\n\n import SanitizedField from '$lib/components/sanitizedField/sanitizedField.svelte'\n \n let bindedValue\n \n function doSomething(ev) {\n // ...do something\n }\n \n \n \n\n```\n\nIsn't there a cleaner way to forward every event to parent in svelte ?\n\n========================================\n\nCode:\n```text\n<script>\n import { TextInput } from 'carbon-components-svelte'\n import { createEventDispatcher } from \"svelte\";\n\n const dispatch = createEventDispatcher();\n\n export let value\n \n function thirdPartyForwarder(ev) {\n dispatch(ev.type, ev.detail)\n }\n\n</script>\n\n<TextInput {...$$props} bind:value \non:event1={thirdPartyForwarder} \non:event2={thirdPartyForwarder} // <==== this I would like to avoid\non:event3={thirdPartyForwarder} .../>\n```\n\n```text\n<script>\n import SanitizedField from '$lib/components/sanitizedField/sanitizedField.svelte'\n \n let bindedValue\n \n function doSomething(ev) {\n // ...do something\n }\n \n </script>\n \n<SanitizedField bind:value={bindedValue} on:thirdPartyEvent1={doSomething} />\n```\n\n```text\ncarbon-components-svelte\n```\n\n```text\n<TextInput>\n```\n\n```text\n<TextInput>\n```\n\n```text\non:*\n```\n\n```text\nuse:\n```\n\n```text\non:possibleEvent={event => dispatch(event)}\n```\n\n```text\nsanitizedField.svelte\n```\n\n```text\nPage.svelte\n```\n\n```html\n<TextInput on:change on:input />\n```\n\n========================================\n\nComments:\n- Okay, nice ! How could I miss that. this is obviously the good answer. Do you know what's going there ? What are the mechanism making that possible ?\n- That is just how Svelte works, an `on:event` definition without handler gets forwarded (see docs).","metadata":{"transformedAt":"2026-08-18T18:33:40.710Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":137,"estimatedTokens":802}}692{"id":"stack-58923706","source":"stackoverflow","questionId":58923706,"title":"iterate over async function result in svelte","tags":["svelte"],"text":"Title: iterate over async function result in svelte\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI am trying to iterate over some value returned by some async function.\n\n```\nimport { onMount } from 'svelte';\n\nlet navigation;\n\nonMount(async function(){\n navigation = FETCHER.data.navigation;\n console.log(navigation);\n});\n```\n\nthen in html\n\n```\n{#await navigation}\n {#each navigation.main as menuItem}\n foobar\n {/each}\n{/await}\n```\n\nhowever \"foobar\" never comes to light.\n\nInside navigation I find this datastructure:\n\n```\nmain: (3) […]\n0: Object { ID: 16, url: \"http://127.0.0.1/\", title: \"Welcome\", … }\n1: Object { ID: 15, url: \"http://127.0.0.1/\", title: \"Home\", … }\n2: Object { ID: 176, url: \"http://127.0.0.1/test/\", title: \"test\", … }\nlength: 3\n```\n\nI am really curious why anything inside the await block isn't rendered at all. Am I doing something wrong with the promise?\n\nOne thing on a sidenote which may be important: the FETCHER.data.navigation variable is passed through from WordPress using wp_localize_script, hence no fetch call whatsoever going out. \n\nThanks for any input in advance.\n\nBest,\nSebo\n\n========================================\n\nCode:\n```text\nimport { onMount } from 'svelte';\n\nlet navigation;\n\nonMount(async function(){\n navigation = FETCHER.data.navigation;\n console.log(navigation);\n});\n```\n\n```text\n{#await navigation}\n {#each navigation.main as menuItem}\n foobar\n {/each}\n{/await}\n```\n\n```text\nmain: (3) […]\n0: Object { ID: 16, url: \"http://127.0.0.1/\", title: \"Welcome\", … }\n1: Object { ID: 15, url: \"http://127.0.0.1/\", title: \"Home\", … }\n2: Object { ID: 176, url: \"http://127.0.0.1/test/\", title: \"test\", … }\nlength: 3\n```\n\n```text\n{#await navigation}\n <p>awaiting...</p>\n{:then navigation}\n {#each navigation.main as menuItem}\n foobar\n {/each}\n{:catch error}\n <p>error</p>\n{/await}\n```\n\n```text\n<script>\n import { onMount } from 'svelte';\n let promise;\n async function fetchStuff() {\n return FETCHER.data.navigation;\n }\n onMount(() => {\n promise = fetchStuff();\n });\n</script>\n\n{#await promise}\n<p>\n awaiting...\n</p>\n{:then navigation}\n<p>\n here access navigation\n</p>\n{:catch error}\n<p>\n oh noes.\n</p>\n{/await}\n```\n\n```text\nawait\n```\n\n========================================\n\nComments:\n- what is `FETCHER.data.navigation`? A promise?\n- it's an object injected from WordPress via wp_localize_script","metadata":{"transformedAt":"2026-08-18T18:33:40.710Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":127,"estimatedTokens":604}}693{"id":"stack-72821557","source":"stackoverflow","questionId":72821557,"title":"How to access to a store into array of stores? Using Svelte","tags":["typescript","svelte","sveltekit","svelte-component","svelte-store"],"text":"Title: How to access to a store into array of stores? Using Svelte\nTags: typescript, svelte, sveltekit, svelte-component, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI'm using svelte-forms and need to make an array of fields\n\nfield() returns a writable store and is a convenient function to create a new form input that will serve a your input controller.\n\nSuppose the next scenario\n\n```\n\n let fields = [field(\"f1\",\"f1\",[]), field(\"f2\",\"f1\",[]);\n\n{#each fields as field}\n {$field}\n{/each}\n```\n\nHow can i use the fields array to access to any field store?\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n let fields = [field(\"f1\",\"f1\",[]), field(\"f2\",\"f1\",[]);\n</script>\n\n{#each fields as field}\n {$field}\n{/each}\n```\n\n```html\n{#each fields as field}\n <Sub {field} />\n{/each}\n```\n\n```html\n<!-- Sub.svelte -->\n<script>\n export let field;\n</script>\n\n<input bind:value={$field.value} />\n```\n\n========================================\n\nComments:\n- Why the `field` store is not accessible in the parent component? why I need another sub component to use any field?\n- @AngelPonce A current limitation of Svelte, it will tell you something to that effect in the error message. Stores need to be declared at the top level to be accessed via `$` syntax. (You can still access them in other ways.)","metadata":{"transformedAt":"2026-08-18T18:33:40.710Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":55,"estimatedTokens":332}}694{"id":"stack-71368209","source":"stackoverflow","questionId":71368209,"title":"How to configure Svelte project with Vite so that the static files are not copied during the build?","tags":["svelte","vite"],"text":"Title: How to configure Svelte project with Vite so that the static files are not copied during the build?\nTags: svelte, vite\nSource: Stack Overflow\n\nQuestion:\nIn a NORMAL Svelte project (no SvelteKit) the static files are in the `public` directory and when running `npm run build` (`rollup -c`) the `src` folder is compiled into `public/build` and the public folder can then be hosted somewhere.\n\nI now switched (an already existing) Svelte project to Vite and the static files are still under `public` but when running `npm run build` (`vite build`), everything is bundled into the `dist` directory. So all the files in the `public` directory are actually copied and exist twice in the project. Which means when changing or adding something (which doesn't effect the app logic) the project needs to be rebuild before it can be redeployed.\n\nCan this be changed via the configuration, that either all compiled files are added again to the `public` directory or that the static files reside directly inside `dist` and nothing is copied during the build process?\n\nEdit: The project should still be able to be run in dev mode `npm run dev` (`vite`) with the assets being served\n\n========================================\n\nCode:\n```text\npublic\n```\n\n```text\nnpm run build\n```\n\n```text\nrollup -c\n```\n\n```text\nsrc\n```\n\n```text\npublic/build\n```\n\n```text\npublic\n```\n\n```text\nnpm run build\n```\n\n```text\nvite build\n```\n\n```text\ndist\n```\n\n```text\npublic\n```\n\n```text\npublic\n```\n\n```text\ndist\n```\n\n```text\nnpm run dev\n```\n\n```text\nvite\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\nimport { rm } from 'fs/promises'\n\n// https://vitejs.dev/config/\nexport default defineConfig(({ command }) => ({\n plugins: [\n svelte(),\n {\n buildStart() {\n if (command === 'build')\n rm('./dist/assets', { recursive: true }).catch(() => {})\n }\n },\n ],\n publicDir: false,\n build: {\n emptyOutDir: false,\n }\n}))\n```\n\n```js\nimport express from 'express'\nimport { createServer as createViteServer } from 'vite'\n\n// Or use require if nodejs complains about ES module\n// const express = require('express')\n// const { createServer: createViteServer } = require('vite')\n\nasync function createServer() {\n const app = express()\n\n // Create Vite server in middleware mode.\n const vite = await createViteServer({\n server: { middlewareMode: 'html'},\n })\n\n // Do not serve built index.html when visiting http://localhost:3000/\n app.use(express.static('dist', { index: false }))\n\n // Use vite's connect instance as middleware\n app.use(vite.middlewares)\n\n app.listen(3000)\n}\n\ncreateServer()\n```\n\n```text\ndist\n```\n\n```text\npublicDir\n```\n\n```text\nemptyOutdir\n```\n\n```text\nbuildStart\n```\n\n```text\ndist/assets\n```\n\n```text\nvite.config.js\n```\n\n```text\nnpm run dev\n```\n\n```text\nserver.js\n```\n\n```text\n\"dev\": \"vite\"\n```\n\n```text\n\"dev\": \"node server.js\"\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- Thanks for these settings! I think I missed a point in my question... the project should, besides being build and deployed, still be run in dev mode `npm run dev` (`vite`) with the assets being served. I think that's not possible like that, or am I wrong?\n- @Corrl Yes, you are right. I have updated the answer (with even more hacks).\n- So much hacks for such a seemingly simple setting... ;-) Thanks for the modification! You say replace `\"serve\": \"vite\"` - with the Svelte setup that's probably `dev` then. When doing that and run `npm run dev` with node v16 I get an error \"Warning: To load an ES module, set \"type\": \"module\" in the package.json or use the .mjs extension.\" which is gone by adding `\"type\": \"module\",` to `package.json` - then everything seems to work! This could/should be added to the answer?\n- While running the `dev mode` worked fine, I now get an error when building \"Rollup failed to resolve import \"global.css\" from *\"index.html. This is most likely unintended because it can break your application at runtime. If you do want to externalize this module explicitly add it to`build.rollupOptions.external`\"* (Silly me for not having tested that before....) I find for example this questions stackoverflow.com/questions/67696920/… but changing the path doesn't seem to help. Do you have an idea?\n- @Corrl Seems that it's another problem which is not related to this question. Vite has changed a lot and the answers there don't work any more. There are some issues about this (like github.com/vitejs/vite/issues/5906). Currently I have no idea how to fix this.\n- Thanks for the reply! So would you consider this as a bug and the build should usually work with your settings?\n- @Corrl Yes, it's vite's fault. Vite considered your `global.css` as a css module just because it can't be found in `src` or `public`. But it's actually not.\n- I've been in these types of situations before not just with Vite, but also Rollup (i.e., where the LOE / hacking required to achieve some simple file shuffling was not worth it), so in the end I create a `build.sh` shell script and use good ol' `cp/mv` to do whatever needed to be done.\n- Thank you @AllanChain !! I was in the same situation as OP, and your answer is really a big help! It made no sense to have twice the static files in my project. This is so much better now! Thank you kindly 🙏 now onto sparse-checkout and I'll have a cleaner/leaner workflow!","metadata":{"transformedAt":"2026-08-18T18:33:40.710Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":27,"totalLines":179,"estimatedTokens":1356}}695{"id":"stack-74938778","source":"stackoverflow","questionId":74938778,"title":"How to use the WebSpeech API in svelte","tags":["svelte","vite","webspeech-api"],"text":"Title: How to use the WebSpeech API in svelte\nTags: svelte, vite, webspeech-api\nSource: Stack Overflow\n\nQuestion:\nI am working on a frontend project which involves the use of the google WebSpeech API. When I try to declare the speech recognition, I get errors saying speech recognition is not defined or window is not defined. The project fails to compile. How do I fix this?\n\nThe code inside my tag is below;\n\n```\nconst SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;\nconst recognition = new SpeechRecognition();\n```\n\nThis is the error\n\nwindow is not defined\nReferenceError: window is not defined\n\nI am using vite-plugin-svelte for compiling & Chrome browser for testing.\n\n========================================\n\nCode:\n```text\nconst SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;\nconst recognition = new SpeechRecognition();\n```\n\n```html\n<script>\n import { onMount } from 'svelte';\n\n let recognition;\n\n onMount(() => {\n const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;\n recognition = new SpeechRecognition();\n });\n</script>\n```\n\n```text\nwindow\n```\n\n```text\nrecognition\n```\n\n```text\nonMount\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.710Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":53,"estimatedTokens":302}}696{"id":"stack-74920223","source":"stackoverflow","questionId":74920223,"title":"How to route programmatically in SveteKit 1.0?","tags":["routes","svelte","sveltekit"],"text":"Title: How to route programmatically in SveteKit 1.0?\nTags: routes, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nSvelteKit 1.0 has been out for a very short amount of time as per this writing, and I've encountered something that is nowhere in the new documentation. How can I route programmatically in SvelteKit 1.0? Before SvelteKit 1.0 there was a solution to do this, like it's written in this stackoverflow question. There was a goto function that did this (and now this function is out of the framework). You would've pass a route like \"/homepage\" and the function would route your app to the homepage page. How can I do this in SvelteKit 1.0? I have found nothing until now.\n\n========================================\n\nCode:\n```text\ngoto\n```\n\n```text\nonMount\n```\n\n```text\n+page.server.js\n```\n\n```text\nredirect\n```\n\n========================================\n\nComments:\n- `goto` still exists. Are you trying to do a server side redirect?\n- Actually, I just realized that i have the default setting on my page, so I guess SSR is enabled. Yea, in this case, I am trying to do a server side redirect.\n- Nice. If you try to use `goto` in the top-level of your script tag it will be run on the server as well, which will not work as expected. You could put the logic in a `+page.server.js` file instead and use the built-in `redirect` helper.","metadata":{"transformedAt":"2026-08-18T18:33:40.710Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":32,"estimatedTokens":337}}697{"id":"stack-70651777","source":"stackoverflow","questionId":70651777,"title":"How do I store a fetch response to a derived store in svelte?","tags":["fetch","store","svelte"],"text":"Title: How do I store a fetch response to a derived store in svelte?\nTags: fetch, store, svelte\nSource: Stack Overflow\n\nQuestion:\nI have a list of items which I consume from an own custom built API (in the example I'll use typicode) and want to display them. Additionally I want to add a client side search functionality. It is exactly like this REPL from this question.\n\nBut the given list is hardcoded, yet I can't seem to build a fetch call to get those items prior and afterwards display them. Only then can the user search and filter them.\n\nHere is my REPL.\n\n========================================\n\nCode:\n```text\nresponse.json()\n```\n\n```text\nawait\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.710Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":21,"estimatedTokens":165}}698{"id":"stack-73873803","source":"stackoverflow","questionId":73873803,"title":"How to avoid the element slightly fading out when using crossfade transition?","tags":["svelte"],"text":"Title: How to avoid the element slightly fading out when using crossfade transition?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nWhen crossfading an image it can be noticed that the element fades out a bit in the middle of the transition. Is there a way to avoid this? Changing the easing doesn't seem to have an effect.\n\nREPL\n\n**Update** The image might change the position. This might also be solved with toggling classes like here, but the transition looks different (which maybe might be prevented with different positioning and scaling from the center...), but the unsimplified actual example is a gallery like this where the element not only scales and moves, but also 'switches' the parent element.\n\nWhen playing this video about crossfade at minimum speed, I can't notice any change of the transparency so I wondered if the crossfade function might have changed since. I tried some older compiler versions, but didn't find one without the effect.\n\nWriting a custom transition function is relatively easy, but I couldn't figure out if/how it was possbile to copy and reuse the internal crossfade function with an adjusted opacity setting. Would that be possible somehow?\n\n```\n\n import { crossfade } from 'svelte/transition';\n import {quintOut} from 'svelte/easing';\n\n const [send, receive] = crossfade({\n duration: 3000,\n easing: quintOut\n });\n\n async function fetchPhoto(noCacheMarker) {\n const response = await fetch(`https://source.unsplash.com/random?${noCacheMarker}`)\n return await response.url\n }\n\n let smallImg = true\n\n smallImg = !smallImg}>\n toggle\n\n {#await fetchPhoto() then url}\n {#if smallImg}\n \n {:else}\n \n {/if}\n {/await}\n\n img {\n position: absolute;\n }\n #smallImg {\n width: 300px;\n height: 200px;\n object-fit: cover;\n left: 10%;\n bottom: 10%;\n }\n #bigImg {\n width: 600px;\n height: 400px;\n object-fit: cover;\n top: 10%;\n right: 10%;\n }\n\n```\n\n========================================\n\nTop Answer:\nIt's just that crossfade usually works like this. It also happens in the tutorial, but it's hard to see because of the movement. It is also difficult to explain why this is the case in this answer, but HTTP 203 have a great episode about this topic.\n\nProbably the best solution is to use CSS transform and transitions. In your example, you just need to add the `transition` property in CSS (you could also use something like `transform: scale(200%)` if you don't want to be messing with DOM layout).\n\n```\n\n import { crossfade } from 'svelte/transition';\n import {quintOut} from 'svelte/easing';\n\n const [send, receive] = crossfade({\n duration: 3000,\n easing: quintOut\n });\n\n async function fetchPhoto(noCacheMarker) {\n const response = await fetch(`https://source.unsplash.com/random?${noCacheMarker}`)\n return await response.url\n }\n\n let smallImg = true\n\n smallImg = !smallImg}>\n toggle\n\n {#await fetchPhoto() then url}\n \n {/await}\n\n img {\n position: absolute;\n left: 50%;\n top: 50%;\n transform: translate(-50%, -50%);\n transition: all 500ms ease;\n }\n\n .small {\n width: 300px;\n height: 200px;\n object-fit: cover;\n }\n\n .big {\n width: 600px;\n height: 400px;\n object-fit: cover;\n }\n\n```\n\nIf you *really* need to use deffered transitions, it might be possible to write your own (since they're customizable) to try fix this problem. But it seems a bad solution and you should probably avoid it.\n\n========================================\n\nCode:\n```text\n<script>\n import { crossfade } from 'svelte/transition';\n import {quintOut} from 'svelte/easing';\n\n const [send, receive] = crossfade({\n duration: 3000,\n easing: quintOut\n });\n\n async function fetchPhoto(noCacheMarker) {\n const response = await fetch(`https://source.unsplash.com/random?${noCacheMarker}`)\n return await response.url\n }\n\n let smallImg = true\n</script>\n\n<button on:click={() => smallImg = !smallImg}>\n toggle\n</button>\n\n<div>\n {#await fetchPhoto() then url}\n {#if smallImg}\n <img src=\"{url}\" alt=\"\" id=\"smallImg\"\n out:send=\"{{key: url}}\"\n in:receive=\"{{key: url}}\"\n />\n {:else}\n <img src=\"{url}\" alt=\"\" id=\"bigImg\"\n out:send=\"{{key: url}}\"\n in:receive=\"{{key: url}}\"\n />\n {/if}\n {/await}\n</div>\n\n<style>\n img {\n position: absolute;\n }\n #smallImg {\n width: 300px;\n height: 200px;\n object-fit: cover;\n left: 10%;\n bottom: 10%;\n }\n #bigImg {\n width: 600px;\n height: 400px;\n object-fit: cover;\n top: 10%;\n right: 10%;\n }\n</style>\n```\n\n```js\ncss: (t, u) => `\n opacity: ${t**(1/16) * opacity};\n ...\n```\n\n```text\ncrossfade\n```\n\n```html\n<script>\n import { crossfade } from 'svelte/transition';\n import {quintOut} from 'svelte/easing';\n\n const [send, receive] = crossfade({\n duration: 3000,\n easing: quintOut\n });\n\n async function fetchPhoto(noCacheMarker) {\n const response = await fetch(`https://source.unsplash.com/random?${noCacheMarker}`)\n return await response.url\n }\n\n let smallImg = true\n</script>\n\n<button on:click={() => smallImg = !smallImg}>\n toggle\n</button>\n\n<div>\n {#await fetchPhoto() then url}\n <img src=\"{url}\" alt=\"\" class={smallImg ? 'small' : 'big'}/>\n {/await}\n</div>\n\n<style>\n img {\n position: absolute;\n left: 50%;\n top: 50%;\n transform: translate(-50%, -50%);\n transition: all 500ms ease;\n }\n\n .small {\n width: 300px;\n height: 200px;\n object-fit: cover;\n }\n\n .big {\n width: 600px;\n height: 400px;\n object-fit: cover;\n }\n</style>\n```\n\n```text\ntransition\n```\n\n```text\ntransform: scale(200%)\n```\n\n========================================\n\nComments:\n- Thanks for the link! The example I gave was a bit too simplified, mainly for illustrating the fading... just added some more info.\n- Thanks H.B., I simplified a bit too much... just added some more info to the question.\n- I added a suggestion, though a real solution would require a rewrite of the existing `crossfade`.\n- Can't you just do `opacity: ${opacity};`, since both images are the same? If the images are the same, you can just have them both visible all the time I think.\n- Thanks a lot for the added example! I was also wondering about the opacity (@Odilf) , why there's even any fading needed when it's the same image. And it does indeed seem to also work when removing the opacity altogether. But looks like the calculation of position and size is not as precise and there's a noticable snap into place at the end of the scaling down. So I can imagine the variant with the small image scaling up and the big fading in/out on top would be better.\n- @Odilf: As Corrl noted, if the opacity is not changed you can unfortunately get a noticeable jump from the artifacts generated by the scaling/transform interpolation.\n- @Corrl: By the way, the opacity issue has actually been known for quite a while (just went to check whether it has been reported yet).","metadata":{"transformedAt":"2026-08-18T18:33:40.710Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":259,"estimatedTokens":1755}}699{"id":"stack-74900771","source":"stackoverflow","questionId":74900771,"title":"How to set a base path for SCSS imports in SvelteKit?","tags":["javascript","sass","svelte","sveltekit"],"text":"Title: How to set a base path for SCSS imports in SvelteKit?\nTags: javascript, sass, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI want to import an scss file in one of my components. Is there a way to use aliases or something else so I can import them without a long relative path.\n\nFor example, rather than this:\n` @use '../../../styles/main.scss' `\n\nI would like to do something like this instead:\n` @use '@/styles/main.scss' `\n\nI'm using the sass a svelte-preprocess packages.\n\nThis works in Vue but not sure if a similar thing is possible in svelte.\n\n========================================\n\nCode:\n```text\n<style lang='scss'> @use '../../../styles/main.scss' </style>\n```\n\n```text\n<style lang='scss'> @use '@/styles/main.scss' </style>\n```\n\n```text\nimport adapter from '@sveltejs/adapter-auto';\nimport { vitePreprocess } from '@sveltejs/kit/vite';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n kit: {\n adapter: adapter()\n },\n preprocess: [vitePreprocess()] // Add this line and its import (above)\n};\n\nexport default config;\n```\n\n```text\nimport { sveltekit } from '@sveltejs/kit/vite'\nimport path from 'path'\n\n/** @type {import('vite').UserConfig} */\nconst config = {\n plugins: [\n sveltekit()\n ],\n resolve: {\n alias: {\n '@': path.resolve('src') // Styles in src/styles will be accessible as '@/styles/whatever.scss'\n }\n }\n}\n\nexport default config\n```\n\n```text\nnpm install --save-dev vite-plugin-restart\n```\n\n```text\nimport { sveltekit } from '@sveltejs/kit/vite'\nimport VitePluginRestart from 'vite-plugin-restart'\nimport path from 'path'\n\n// No idea why this is needed\n// The default export of vite-plugin-restart looks to be the function but it doesn't work when imported\n// Need to access the 'default' key from the imported object instead\nconst ViteRestart = VitePluginRestart.default\n\n/** @type {import('vite').UserConfig} */\nconst config = {\n plugins: [\n sveltekit(),\n ViteRestart({\n restart: [\n 'src/styles/*.scss' // For some reason path.resolve doesn't seem to work here\n ]\n })\n ],\n resolve: {\n alias: {\n '@': path.resolve('src')\n }\n }\n}\n\nexport default config\n```\n\n```text\nsvelte.config.js\n```\n\n```text\nvite.config.js\n```\n\n```text\nvite-plugin-restart\n```\n\n```text\nvite.config.js\n```\n\n========================================\n\nComments:\n- I haven't tried this myself so I can't say for certain that it works, but it might work if you put it in `src/lib/styles/main.scss` and import it like `@use '$lib/styles/main.scss'`\n- @Tholle Thanks, this does indeed seem to work. I have been experimenting with other options to get it to work as well and I think I have figured it out. I'll post it as an answer below.\n- Do you happen to know if this answer is still current as of 2024? I see lots of examples elsewhere on the internet suggesting setting `config.preprocess.scss.includePaths` but I'm having trouble making it work.","metadata":{"transformedAt":"2026-08-18T18:33:40.710Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":118,"estimatedTokens":759}}700{"id":"stack-74352013","source":"stackoverflow","questionId":74352013,"title":"How do I pass props/data from parent +page.svelte file to a child +page.svelte file in sveltekit?","tags":["javascript","svelte","sveltekit"],"text":"Title: How do I pass props/data from parent +page.svelte file to a child +page.svelte file in sveltekit?\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm using the latest version of sveltekit where I'm using the +page.svelte, +page.js, +page.server.js, etc. format. I have a folder called \"nowPlaying\" that pulls all the movies that are playing in theaters from the movie db. Inside my +page.svelte for this folder I have an object called \"pkg\" and a function called \"acquireMovieInfo\" that helps me get movie details on click that looks like this:\n\n```\n\n let pkg = {\n movieID: \"\",\n movieName: \"\",\n movieOverview: \"\",\n movieReleaseDate: \"\",\n moviePosterPath: \"\",\n }\n\n function acquireMovieInfo(id, name, overview, release, poster) {\n const userPickID = id;\n const userPickName = name;\n const userPickOverview = overview;\n const userPickReleaseDate = release;\n const userPickPosterPath = poster;\n pkg = {\n movieID: userPickID,\n movieName: userPickName,\n movieOverview: userPickOverview,\n movieReleaseDate: userPickReleaseDate,\n moviePosterPath: userPickPosterPath,\n }\n console.log(pkg);\n }\n\n```\n\nUnder my script I have a ul that lists out all of the movies now playing from my fetch request to the movie db (my fetch request lives in the +page.server.js not shown here) no prob and works great. The list is displayed as the movie posters. My function above is then used like this:\n\n```\n\n \n {#each movies_nowPlaying as movieNowPlaying}\n \n acquireMovieInfo(movieNowPlaying.id, movieNowPlaying.original_title, movieNowPlaying.overview, movieNowPlaying.release_date, movieNowPlaying.poster_path)}>\n \n {/each}\n \n\n```\n\nAll of this works great and per the console log in my function, I am able to get all of the info from each movie poster I click saved to the \"pkg\" object and able to log it.\n\nMy question is how can I now send over the info saved on my pkg to the directory listed on my a tag, nowPlayingMovieDetails, and get this data showing within that +page.svelte that lives in the nowPlayingMovieDetails folder? Because I want my a tag to be clicked and then it lead to the nowPlayingMovieDetails directory where I can then use the data within \"pkg\" to display the details for that movie that was clicked on.\n\nSo far I haven't been able to find how to move this data over especially with the recent update to sveltekit.\n\nMy file structure is\n\n```\n+ src\n |\n +-- routes\n |\n +-- nowPlaying\n |\n +-- +page.server.js\n +-- +page.svelte\n |\n +-- nowPlayingMovieDetails\n |\n +-- +page.js\n +-- +page.svelte\n```\n\nI am fairly new to sveltekit, let alone svelte in general, but I really enjoy using it so if you have any suggestions, please let me know.\n\n========================================\n\nCode:\n```text\n<script>\n let pkg = {\n movieID: \"\",\n movieName: \"\",\n movieOverview: \"\",\n movieReleaseDate: \"\",\n moviePosterPath: \"\",\n }\n\n function acquireMovieInfo(id, name, overview, release, poster) {\n const userPickID = id;\n const userPickName = name;\n const userPickOverview = overview;\n const userPickReleaseDate = release;\n const userPickPosterPath = poster;\n pkg = {\n movieID: userPickID,\n movieName: userPickName,\n movieOverview: userPickOverview,\n movieReleaseDate: userPickReleaseDate,\n moviePosterPath: userPickPosterPath,\n }\n console.log(pkg);\n }\n</script>\n```\n\n```text\n<div>\n <ul>\n {#each movies_nowPlaying as movieNowPlaying}\n <li>\n <a href=\"/nowPlayingMovieDetails\" data-movie-id={movieNowPlaying.id} on:click={() => acquireMovieInfo(movieNowPlaying.id, movieNowPlaying.original_title, movieNowPlaying.overview, movieNowPlaying.release_date, movieNowPlaying.poster_path)}><img src=\"http://image.tmdb.org/t/p/w500/{movieNowPlaying.poster_path}\" alt=\"{movieNowPlaying.title} movie poster\"></a>\n </li>\n {/each}\n </ul>\n</div>\n```\n\n```text\n+ src\n |\n +-- routes\n |\n +-- nowPlaying\n |\n +-- +page.server.js\n +-- +page.svelte\n |\n +-- nowPlayingMovieDetails\n |\n +-- +page.js\n +-- +page.svelte\n```\n\n```text\nroutes/nowPlaying/[id]/details/+page.svelte\n```\n\n```text\n/nowPlaying/42/details\n```\n\n```html\n<a href=\"/nowPlaying/{movieNowPlaying.id}/details\" ...>\n```\n\n```text\n[id]\n```\n\n```text\nid\n```\n\n```text\nhref\n```\n\n```text\nhref\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.711Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":161,"estimatedTokens":1109}}701{"id":"stack-66318919","source":"stackoverflow","questionId":66318919,"title":"How can I dynamically add a column in CSS grid without wrapping to a new row?","tags":["html","css","svelte"],"text":"Title: How can I dynamically add a column in CSS grid without wrapping to a new row?\nTags: html, css, svelte\nSource: Stack Overflow\n\nQuestion:\nHow can I add a new column in css dynamically (e.g. a button is toggled and a new component (I'm working with Svelte) appears in a new column), but without that (if viewport is too small) the new component skips to a new row. The already visible components should just get \"squeezed\".\n\nmy code (html):\n\n```\n\n \n {#if $entitiesStore.get(id).entityType === \"person\"}\n \n {:else}\n \n \n {#if $entitiesStore.get(id).showReadingView}\n \n {/if}\n \n {#if $entitiesStore.get(id).showFacsimile}\n \n {/if}\n \n \n \n \n {/if}\n\n```\n\nmy css:\n\n```\n.entity-view {\n width: 100%;\n height: auto;\n overflow: hidden;\n padding: 45px;\n box-sizing: border-box;\n \n }\n .reading-version-view-and-facsimile{\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));\n }\n .reading-version {\n grid-column: span 1.42;\n }\n \n .marginal{\n position: relative;\n margin-left: 7em;\n }\n```\n\nat the moment the .marginal skips to a new row and doesn't stay in place and when toggling the Facsimile-View, die ReadingVersionView doesn't move one bit and it just \"overlays\".\n\nI hope my question is clear enough. Thanks a lot!\n\n========================================\n\nCode:\n```text\n<div class=\"entity-view\">\n <CorrespondenceNavigation entity = \"{$entitiesStore.get(id)}\"/>\n {#if $entitiesStore.get(id).entityType === \"person\"}\n <PersonView entity=\"{$entitiesStore.get(id)}\" />\n {:else}\n <div class = \"reading-version-view-and-facsimile\">\n <div class = \"reading-version\">\n {#if $entitiesStore.get(id).showReadingView}\n <ReadingVersionView entity=\"{$entitiesStore.get(id)}\" />\n {/if}\n </div>\n {#if $entitiesStore.get(id).showFacsimile}\n <FacsimileView entity=\"{$entitiesStore.get(id)}\" />\n {/if}\n <div class = \"marginal\">\n <MarginalColumnView entity=\"{$entitiesStore.get(id)}\" />\n </div>\n </div>\n {/if}\n</div>\n```\n\n```css\n.entity-view {\n width: 100%;\n height: auto;\n overflow: hidden;\n padding: 45px;\n box-sizing: border-box;\n \n }\n .reading-version-view-and-facsimile{\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));\n }\n .reading-version {\n grid-column: span 1.42;\n }\n \n .marginal{\n position: relative;\n margin-left: 7em;\n }\n```\n\n```css\n.wrapper {\n display: grid;\n grid-auto-flow: column;\n}\n\n.wrapper {\n grid-gap: 10px;\n background-color: #fff;\n color: #444;\n}\n\n.box {\n background-color: #444;\n color: #fff;\n padding: 10px 0;\n text-align: center;\n font-size: 150%;\n}\n```\n\n```html\n<div class=\"wrapper\">\n <div class=\"box a\">A</div>\n <div class=\"box b\">B</div>\n <div class=\"box c\">C</div>\n <div class=\"box c\">D</div>\n <div class=\"box c\">C</div>\n <div class=\"box c\">D</div>\n</div>\n```\n\n```text\ngrid-auto-flow\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.711Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":145,"estimatedTokens":780}}702{"id":"stack-70486828","source":"stackoverflow","questionId":70486828,"title":"Fetch requet is triggered twice on page load and after page finishes loading","tags":["svelte","svelte-3","sveltekit"],"text":"Title: Fetch requet is triggered twice on page load and after page finishes loading\nTags: svelte, svelte-3, sveltekit\nSource: Stack Overflow\n\nQuestion:\nThe following is a page for confirming your email address, I'm using fetch to send the unique token param to the API, but what happens is that the fetch request on the load function is getting called twice and even if it doesn't show on console the value of the response change.\nHere's a simple step by step:\n\n- click on the link\n\n- fetch sends a request to the API with the unique token\n\n- the API responds with either OK or Not Found (if you've already confirmed your email)\n\nThe third step is what causes an issue, once the page loads it looks like it fetched in the background and show a success message until it finishes loading then the message shown changes into an error, when I check the API I get to see two requests as the first success and the next is not found (not found results from removing the token after validating the user)\n\n```\n\n import type { Load } from '@sveltejs/kit';\n\n import { variables } from '$lib/variables';\n\n const { api } = variables;\n\n export const load: Load = async ({ fetch, page }) => {\n const res = await fetch(api + '/Newsletters/subscribers/validation/' + page.params.token);\n\n if (res.status === 200 && res.statusText === 'OK') {\n return {\n props: {\n showSpinner: false,\n isErr: false\n }\n };\n }\n\n return {\n props: {\n showSpinner: false,\n isErr: true\n }\n };\n };\n\n export let isErr: boolean = false;\n\n export let showSpinner: boolean = true;\n\n {#if showSpinner}\n \n {:else if isErr}\n \n {:else}\n \n {/if}\n\n```\n\nHere's also references to other issues that this could be related to:\n\n- __layout.svelte may run twice after browser reload in dev\n\n- Svelte module script being run multiple times\n\n***I'm using a workaround by adding a button to click on to fetch rather than doing it on load, but it's not the right approach for how these kind of pages works.***\n\n========================================\n\nTop Answer:\nFrom https://svelte.dev/tutorial/onmount:\n\nIt's recommended to **put the `fetch` in `onMount` rather than at the top level of the ``** because of server-side rendering (SSR). With the exception of `onDestroy`, ***lifecycle functions don't run during SSR**, which means we can **avoid fetching data that should be loaded lazily** once the component has been mounted in the DOM*.\n\n- If the `fetch` should always run on the client, use `fetch` in `onMount`\n\n- If the `fetch` should run on the server during server-side rendering and in the browser during client-side navigation, use `load` functions. If the URL contains API key or secret token, use +page.server.js otherwise use +page.js.\n\n========================================\n\nCode:\n```js\n<script context=\"module\" lang=\"ts\">\n import type { Load } from '@sveltejs/kit';\n\n import { variables } from '$lib/variables';\n\n const { api } = variables;\n\n export const load: Load = async ({ fetch, page }) => {\n const res = await fetch(api + '/Newsletters/subscribers/validation/' + page.params.token);\n\n if (res.status === 200 && res.statusText === 'OK') {\n return {\n props: {\n showSpinner: false,\n isErr: false\n }\n };\n }\n\n return {\n props: {\n showSpinner: false,\n isErr: true\n }\n };\n };\n</script>\n\n<script lang=\"ts\">\n export let isErr: boolean = false;\n\n export let showSpinner: boolean = true;\n</script>\n\n<section>\n {#if showSpinner}\n <!-- spinner -->\n {:else if isErr}\n <!-- err -->\n {:else}\n <!-- ok -->\n {/if}\n</section>\n```\n\n```text\nfetch\n```\n\n```text\nonMount\n```\n\n```text\n<script>\n```\n\n```text\nonDestroy\n```\n\n```text\nfetch\n```\n\n```text\nfetch\n```\n\n```text\nonMount\n```\n\n```text\nfetch\n```\n\n```text\nload\n```\n\n========================================\n\nComments:\n- The `OnMount` worked, although it can work as expected in prod but it is still confusing on dev while doing testing. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:40.711Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":166,"estimatedTokens":1018}}703{"id":"stack-65179520","source":"stackoverflow","questionId":65179520,"title":"Import alias svelte component in typescript svelte","tags":["javascript","typescript","svelte","svelte-3","svelte-component"],"text":"Title: Import alias svelte component in typescript svelte\nTags: javascript, typescript, svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI want to import a svelte component in a typescript svelte component, it works for typescript file and other type of files, but in this case of svelte component, it resulted in a path error, here's my code :\n\n```\n\n import LoadingIcon from \"src/components/LoadingIcon.svelte\";\n\n```\n\nIt only works if i use `../../components/LoadingIcon.svelte` instead of `src/components/LoadingIcon.svelte`\n\nHere's the error:\n`Uncaught (in promise) TypeError: Failed to resolve module specifier \"src/forms/groups/GroupFilterForm.svelte\". Relative references must start with either \"/\", \"./\", or \"../\".`\n\nhttps://i.sstatic.net/F861u.png\n\nHere's my `tsconfig.json`:\n\n```\n{\n \"include\": [\"src/**/*\"],\n \"exclude\": [\"node_modules/*\", \"public/*\", \"tests/*\", \"docs/*\", \"demo/*\"],\n \"compilerOptions\": {\n \"rootDir\": \"src\",\n \"lib\": [\"es2017\", \"dom\"],\n \"target\": \"es2017\",\n \"baseUrl\": \".\",\n \"noEmitOnError\": true,\n \"noErrorTruncation\": true,\n \"module\": \"esnext\",\n \"moduleResolution\": \"node\",\n \"resolveJsonModule\": true,\n \"allowSyntheticDefaultImports\": true,\n \"noImplicitThis\": true,\n \"noUnusedLocals\": true,\n \"noUnusedParameters\": true,\n \"types\": [\"svelte\", \"node\"],\n \"typeRoots\": [\"./node_modules\", \"./src/types\"]\n }\n}\n```\n\nand here's my `rollup.config.js`:\n\n```\nimport svelte from \"rollup-plugin-svelte\";\nimport resolve from \"@rollup/plugin-node-resolve\";\nimport commonjs from \"@rollup/plugin-commonjs\";\nimport typescript from \"@rollup/plugin-typescript\";\nimport replace from \"@rollup/plugin-replace\";\nimport json from \"@rollup/plugin-json\";\nimport livereload from \"rollup-plugin-livereload\";\nimport { terser } from \"rollup-plugin-terser\";\nimport sveltePreprocess from \"svelte-preprocess\";\nimport copy from \"rollup-plugin-copy\";\nimport del from \"rollup-plugin-delete\";\nconst buildDir = \"public/build\";\nconst deploymentDir = \"public\";\n\nconst production = !process.env.ROLLUP_WATCH;\n\nconst dotenv = require(\"dotenv-flow\");\n\ndotenv.config({\n node_env: process.env.NODE_ENV,\n default_node_env: \"development\",\n});\n\nconst fileDev = dotenv.listDotenvFiles(\"/\", {\n node_env: \"development\",\n});\nconst fileProd = dotenv.listDotenvFiles(\"/\", {\n node_env: \"production\",\n});\n\nfunction serve() {\n let server;\n\n function toExit() {\n if (server) server.kill(0);\n }\n\n return {\n writeBundle() {\n if (server) return;\n server = require(\"child_process\").spawn(\n \"npm\",\n [\"run\", \"start\", \"--\", \"--dev\"],\n {\n stdio: [\"ignore\", \"inherit\", \"inherit\"],\n shell: true,\n }\n );\n\n process.on(\"SIGTERM\", toExit);\n process.on(\"exit\", toExit);\n },\n };\n}\nconst baseUrl =\n process.env.BASE_URL == \"/\"\n ? \"\"\n : \"/\" + (process.env.BASE_URL || \"\").replace(/^\\/|\\/$/g, \"\");\nexport default [\n {\n input: \"src/main.ts\",\n output: {\n sourcemap: true,\n format: \"esm\",\n name: \"app\",\n dir: `${buildDir}/`,\n },\n plugins: [\n del({ targets: `${deploymentDir}/*`, runOnce: true }),\n copy({\n targets: [\n { src: \"scripts/*\", dest: `${buildDir}/` },\n {\n src: \"src/index.html\",\n dest: `${deploymentDir}/`,\n transform: (contents) => {\n let content = contents.toString();\n content = content.replace(\n /()/gm,\n baseUrl\n );\n return content;\n },\n copyOnce: true,\n },\n {\n src: \"src/assets/images/*\",\n dest: `${deploymentDir}/images/`,\n copyOnce: true,\n },\n {\n src: \"src/assets/lang/*\",\n dest: `${deploymentDir}/lang/`,\n copyOnce: true,\n },\n {\n src: \"src/assets/plugins/*\",\n dest: `${deploymentDir}/plugins/`,\n copyOnce: true,\n },\n ],\n }),\n json(),\n replace({\n \"process.browser\": true,\n \"process.env.NODE_ENV\": JSON.stringify(\n production ? \"production\" : \"development\"\n ),\n \"process.env.BASE_URL\": JSON.stringify(process.env.BASE_URL),\n \"process.env.API_URL\": JSON.stringify(process.env.API_URL),\n }),\n svelte({\n dev: !production,\n css: (css) => {\n css.write(`bundle.css`);\n },\n preprocess: sveltePreprocess({\n postcss: {\n configFilePath: \"./postcss.config.js\",\n },\n typescript: {\n tsconfigFile: `./tsconfig.json`,\n },\n }),\n }),\n resolve({\n browser: true,\n dedupe: [\"svelte\"],\n extensions: [\".mjs\", \".ts\", \".js\", \".json\", \".node\", \".svelte\"],\n }),\n commonjs(),\n typescript({\n sourceMap: !production,\n inlineSources: !production,\n }),\n\n // In dev mode, call `npm run start` once\n // the bundle has been generated\n !production && serve(),\n\n // Watch the `public` directory and refresh the\n // browser on changes when not in production\n !production && livereload(deploymentDir),\n\n // If we're building for production (npm run build\n // instead of npm run dev), minify\n production && terser(),\n ],\n watch: {\n clearScreen: false,\n },\n },\n];\n```\n\nAnyone knows how to fix this issue? thank you for your help\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n import LoadingIcon from \"src/components/LoadingIcon.svelte\";\n</script>\n```\n\n```json\n{\n \"include\": [\"src/**/*\"],\n \"exclude\": [\"node_modules/*\", \"public/*\", \"tests/*\", \"docs/*\", \"demo/*\"],\n \"compilerOptions\": {\n \"rootDir\": \"src\",\n \"lib\": [\"es2017\", \"dom\"],\n \"target\": \"es2017\",\n \"baseUrl\": \".\",\n \"noEmitOnError\": true,\n \"noErrorTruncation\": true,\n \"module\": \"esnext\",\n \"moduleResolution\": \"node\",\n \"resolveJsonModule\": true,\n \"allowSyntheticDefaultImports\": true,\n \"noImplicitThis\": true,\n \"noUnusedLocals\": true,\n \"noUnusedParameters\": true,\n \"types\": [\"svelte\", \"node\"],\n \"typeRoots\": [\"./node_modules\", \"./src/types\"]\n }\n}\n```\n\n```js\nimport svelte from \"rollup-plugin-svelte\";\nimport resolve from \"@rollup/plugin-node-resolve\";\nimport commonjs from \"@rollup/plugin-commonjs\";\nimport typescript from \"@rollup/plugin-typescript\";\nimport replace from \"@rollup/plugin-replace\";\nimport json from \"@rollup/plugin-json\";\nimport livereload from \"rollup-plugin-livereload\";\nimport { terser } from \"rollup-plugin-terser\";\nimport sveltePreprocess from \"svelte-preprocess\";\nimport copy from \"rollup-plugin-copy\";\nimport del from \"rollup-plugin-delete\";\nconst buildDir = \"public/build\";\nconst deploymentDir = \"public\";\n\nconst production = !process.env.ROLLUP_WATCH;\n\nconst dotenv = require(\"dotenv-flow\");\n\ndotenv.config({\n node_env: process.env.NODE_ENV,\n default_node_env: \"development\",\n});\n\nconst fileDev = dotenv.listDotenvFiles(\"/\", {\n node_env: \"development\",\n});\nconst fileProd = dotenv.listDotenvFiles(\"/\", {\n node_env: \"production\",\n});\n\nfunction serve() {\n let server;\n\n function toExit() {\n if (server) server.kill(0);\n }\n\n return {\n writeBundle() {\n if (server) return;\n server = require(\"child_process\").spawn(\n \"npm\",\n [\"run\", \"start\", \"--\", \"--dev\"],\n {\n stdio: [\"ignore\", \"inherit\", \"inherit\"],\n shell: true,\n }\n );\n\n process.on(\"SIGTERM\", toExit);\n process.on(\"exit\", toExit);\n },\n };\n}\nconst baseUrl =\n process.env.BASE_URL == \"/\"\n ? \"\"\n : \"/\" + (process.env.BASE_URL || \"\").replace(/^\\/|\\/$/g, \"\");\nexport default [\n {\n input: \"src/main.ts\",\n output: {\n sourcemap: true,\n format: \"esm\",\n name: \"app\",\n dir: `${buildDir}/`,\n },\n plugins: [\n del({ targets: `${deploymentDir}/*`, runOnce: true }),\n copy({\n targets: [\n { src: \"scripts/*\", dest: `${buildDir}/` },\n {\n src: \"src/index.html\",\n dest: `${deploymentDir}/`,\n transform: (contents) => {\n let content = contents.toString();\n content = content.replace(\n /(<%=)[\\s]{0,}(BASE_URL)[\\s]{0,}(%>)/gm,\n baseUrl\n );\n return content;\n },\n copyOnce: true,\n },\n {\n src: \"src/assets/images/*\",\n dest: `${deploymentDir}/images/`,\n copyOnce: true,\n },\n {\n src: \"src/assets/lang/*\",\n dest: `${deploymentDir}/lang/`,\n copyOnce: true,\n },\n {\n src: \"src/assets/plugins/*\",\n dest: `${deploymentDir}/plugins/`,\n copyOnce: true,\n },\n ],\n }),\n json(),\n replace({\n \"process.browser\": true,\n \"process.env.NODE_ENV\": JSON.stringify(\n production ? \"production\" : \"development\"\n ),\n \"process.env.BASE_URL\": JSON.stringify(process.env.BASE_URL),\n \"process.env.API_URL\": JSON.stringify(process.env.API_URL),\n }),\n svelte({\n dev: !production,\n css: (css) => {\n css.write(`bundle.css`);\n },\n preprocess: sveltePreprocess({\n postcss: {\n configFilePath: \"./postcss.config.js\",\n },\n typescript: {\n tsconfigFile: `./tsconfig.json`,\n },\n }),\n }),\n resolve({\n browser: true,\n dedupe: [\"svelte\"],\n extensions: [\".mjs\", \".ts\", \".js\", \".json\", \".node\", \".svelte\"],\n }),\n commonjs(),\n typescript({\n sourceMap: !production,\n inlineSources: !production,\n }),\n\n // In dev mode, call `npm run start` once\n // the bundle has been generated\n !production && serve(),\n\n // Watch the `public` directory and refresh the\n // browser on changes when not in production\n !production && livereload(deploymentDir),\n\n // If we're building for production (npm run build\n // instead of npm run dev), minify\n production && terser(),\n ],\n watch: {\n clearScreen: false,\n },\n },\n];\n```\n\n```text\n../../components/LoadingIcon.svelte\n```\n\n```text\nsrc/components/LoadingIcon.svelte\n```\n\n```text\nUncaught (in promise) TypeError: Failed to resolve module specifier \"src/forms/groups/GroupFilterForm.svelte\". Relative references must start with either \"/\", \"./\", or \"../\".\n```\n\n```text\ntsconfig.json\n```\n\n```text\nrollup.config.js\n```\n\n```text\n// ... other imports\nimport alias from \"@rollup/plugin-alias\";\n\n// ..\n plugins: [\n // ... after typescript({..})\n \n alias({\n entries: [\n // If you add a new top-level-folder besides src which you want to use, add it here\n { find: /^src(\\/|$)/, replacement: `${__dirname}/src/` },\n ],\n }),\n```\n\n```text\nbaseUrl\n```\n\n```text\n@rollup/plugin-typescript\n```\n\n```text\n@rollup/plugin-alias\n```\n\n========================================\n\nComments:\n- Please post you `tsconfig.json` because that file determines if imports like this are valid. Also, what do you use for bundling? Rollup/Webpack? That config file is relevant, too.\n- @dummdidumm thanks for your reply, i've added my tsconfig.json and rollup.config.js\n- Thanks for the solution !, works perfectly, didn't realize i just need to add the alias plugin to my rollup config","metadata":{"transformedAt":"2026-08-18T18:33:40.711Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":449,"estimatedTokens":2903}}704{"id":"stack-66738770","source":"stackoverflow","questionId":66738770,"title":"How to cast this target using this form of inline destructuring in a input element on:input action using Svelte?","tags":["typescript","typescript-typings","svelte","svelte-3"],"text":"Title: How to cast this target using this form of inline destructuring in a input element on:input action using Svelte?\nTags: typescript, typescript-typings, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI don't know how to cast this `target` here using this form of inline destructuring in a Svelte 3 form:\n\n```\n doSomething(value)}\n/>\n```\n\nbeacause typescript now is complaining with:\n\n`Property 'value' does not exist on type 'EventTarget'`\n\nI wanna assert `target` is an `HTMLInputElement`.\n\nAm I wrong?\n\n========================================\n\nCode:\n```text\n<input\n on:input={({ target: { value } }) => doSomething(value)}\n/>\n```\n\n```text\ntarget\n```\n\n```text\nProperty 'value' does not exist on type 'EventTarget'\n```\n\n```text\ntarget\n```\n\n```text\nHTMLInputElement\n```\n\n```text\n<input\n on:input={({ currentTarget: { value } }) => doSomething(value)}\n/>\n```\n\n```text\n<script lang=\"ts\">\n function onInput(e: Event) {\n const target = e.target as HTMLInputElement;\n ..\n }\n</script>\n\n<input\n on:input={onInput}\n/>\n```\n\n```text\ntarget\n```\n\n```text\ntarget\n```\n\n```text\ncurrentTarget\n```\n\n```text\nHTMLInputElement\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.711Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":79,"estimatedTokens":283}}705{"id":"stack-66660282","source":"stackoverflow","questionId":66660282,"title":"How should I build two svelte pages with rollup?","tags":["svelte"],"text":"Title: How should I build two svelte pages with rollup?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI'm following the official Svelte for new developers blog post for my svelte app. It's working fine, and now I want to add a separate \"admin\" app. Except for interfacing the same database and being hosted on the same domain, it shares no components with my main app.\n\nWould the best approach be to create a second svelte app and host it in a folder, or is there a way do to this in the same rollup?\n\n```\nnpx degit sveltejs/template my-project-admin-page\n```\n\n========================================\n\nTop Answer:\nThe best way to do this is using svelte-kit, but for simplicity reasons, once I used tinro and it was so good and simple, you can also use svelte-routing.\n\nIn this case, your code will be like:\n\n```\n\n Go to admin\n \n\n### You are on main page\n\n Back to tasks\n \n\n### You are on admin page\n\n```\n\ntinro: https://github.com/AlexxNB/tinro\n\ntinro-example: https://svelte.dev/repl/4bc37ff40ada4111b71fe292a4eb90f6?version=3.46.4\n\nsvelte-routing: https://github.com/EmilTholin/svelte-routing\n\n========================================\n\nCode:\n```text\nnpx degit sveltejs/template my-project-admin-page\n```\n\n```js\nexport default [\n { ...config for normal app ...},\n { ...config for admin app ...}\n]\n```\n\n```js\nexport default [\n getConfig('index'),\n getConfig('admin')\n]\n```\n\n```text\nrollup.config.js\n```\n\n```html\n<Route path=\"/\">\n <a href=\"/admin\">Go to admin</a>\n <h2>You are on main page</h2>\n</Route>\n<Route path=\"/admin\">\n <a href=\"/\">Back to tasks</a>\n <h2>You are on admin page</h2>\n</Route>\n```\n\n========================================\n\nComments:\n- created this hiring a friend of mine: github.com/kokizzu/svelte-mpa\n- Thanks for answer, can you explain more details please?","metadata":{"transformedAt":"2026-08-18T18:33:40.711Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":81,"estimatedTokens":449}}706{"id":"stack-67895215","source":"stackoverflow","questionId":67895215,"title":"Svelte contenteditable is not updated properly","tags":["svelte"],"text":"Title: Svelte contenteditable is not updated properly\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI created spreadsheet with Svelte, but it seems like it won't update the cell properly.\n\nI appended the \"2\" postfix to every cell, and when I edit the content (say to fix first letter in jim to be uppercased) it should end up with two \"2\" as \"Jim22\". But it end up with just one \"2\" as \"Jim2\".\n\nI also have JSON output to inspect the value of `rows`, and it changed, so the component was updated correctly, but the editable cell was not updated to \"Jim22\" it still \"Jim2\".\n\nWhy, and how to fix that?\n\nplayground\n\nhttps://i.sstatic.net/KKhyK.png\n\nCode\n\n```\n\n let rows = [\n [\"jim\"],\n [\"Kate\"]\n ]\n\n function update(i, j, event) {\n rows[i][j] = event.target.innerText\n }\n\n {#each rows as row, i}\n \n {#each row as cell, j}\n update(i, j, event)}\">{cell}2\n {/each}\n \n {/each}\n\n{JSON.stringify(rows, null, 2)}\n```\n\n========================================\n\nTop Answer:\nJust add the key for each statement. according to document\n\n```\n\n let rows = [\n [\"Jim\", \"Raynor\"],\n [\"Kate\", \"Bishop\"]\n ]\n\n function update(i, j, event) {\n rows[i][j] = event.target.innerText\n }\n\n {#each rows as row, i (row)}\n \n {#each row as cell, j (cell)}\n update(i, j, event)}\">{cell}2\n {/each}\n \n {/each}\n\n{JSON.stringify(rows, null, 2)}\n```\n\n========================================\n\nCode:\n```text\n<script>\n let rows = [\n [\"jim\"],\n [\"Kate\"]\n ]\n\n function update(i, j, event) {\n rows[i][j] = event.target.innerText\n }\n</script>\n\n<table>\n {#each rows as row, i}\n <tr>\n {#each row as cell, j}\n <td contenteditable=\"true\" on:blur=\"{(event) => update(i, j, event)}\">{cell}2</td>\n {/each}\n </tr>\n {/each}\n</table>\n\n<pre>{JSON.stringify(rows, null, 2)}</pre>\n```\n\n```text\nrows\n```\n\n```text\n\"Jim\"\n```\n\n```text\n\"Jim2\"\n```\n\n```text\nset_data\n```\n\n```text\ntext.wholeText === data\n```\n\n```text\ntext.data\n```\n\n```text\n\"Jim\"\n```\n\n```text\ntext.wholeText\n```\n\n```text\ndata\n```\n\n```text\n\"Jim2\"\n```\n\n```text\nwholeText\n```\n\n```text\nText.wholeText\n```\n\n```text\nText\n```\n\n```text\nchildNodes\n```\n\n```text\ntd\n```\n\n```text\n<td>{cell}2</td>\n```\n\n```text\nText\n```\n\n```text\n\"Jim\"\n```\n\n```text\n\"2\"\n```\n\n```text\nwholeText\n```\n\n```text\n\"Jim2\"\n```\n\n```text\n<td>{cell + \"2\"}</td>\n```\n\n```text\nText\n```\n\n```text\n<td>{@html cell}2</td>\n```\n\n```text\nset_data\n```\n\n```text\n<td>{cell}2</td>\n```\n\n```text\n<script>\n let rows = [\n [\"Jim\", \"Raynor\"],\n [\"Kate\", \"Bishop\"]\n ]\n\n function update(i, j, event) {\n rows[i][j] = event.target.innerText\n }\n</script>\n\n<table>\n {#each rows as row, i (row)}\n <tr>\n {#each row as cell, j (cell)}\n <td contenteditable=\"true\" on:blur=\"{(event) => update(i, j, event)}\">{cell}2</td>\n {/each}\n </tr>\n {/each}\n</table>\n\n<pre>{JSON.stringify(rows, null, 2)}</pre>\n```\n\n========================================\n\nComments:\n- I don't know why, but I found that `{@html cell}2` solves the problem. Looking for the explanation.\n- I don't know why it doesn't work either but `{cell + \"2\"}` works as well. Also, what's interesting is that when you initially load your playground and then inspect the `` it displays `\"Jim\"` and then `\"2\"` on a new line.","metadata":{"transformedAt":"2026-08-18T18:33:40.711Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":230,"estimatedTokens":797}}707{"id":"stack-65233318","source":"stackoverflow","questionId":65233318,"title":"How to create a hybrid app on Angularjs and Svelte","tags":["angularjs","svelte"],"text":"Title: How to create a hybrid app on Angularjs and Svelte\nTags: angularjs, svelte\nSource: Stack Overflow\n\nQuestion:\nI have a large Angularjs application. There is also a small project in Svelte.\n\nI need to insert an svelte-application into the first project, how can this be done? How to transfer components? How to build a project?\n\n========================================\n\nCode:\n```text\nnew App({\n target: document.getElementById('someElement'),\n });\n```\n\n```text\nAngularJS\n```\n\n```text\nnpm run build\n```\n\n```text\nindex.html\n```\n\n```text\nbundle.js\n```\n\n```text\nscript\n```\n\n```text\nbundle.css\n```\n\n```text\nstyle\n```\n\n```text\nsomeElement\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.711Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":49,"estimatedTokens":162}}708{"id":"stack-65836112","source":"stackoverflow","questionId":65836112,"title":"Getting undefined when updating array in stores using Svelte","tags":["svelte"],"text":"Title: Getting undefined when updating array in stores using Svelte\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI am learning Svelte and how to make custom stores using it. I've come across a problem where when I try to update a writable array using update, it causes an undefined error in components that subscribe to the array.\n\nHere is my store where I have a simple array with one element, a string:\n\n```\nimport { writable } from 'svelte/store'\n\nexport const activeData = writable([\"array\"])\n```\n\nHere is a component that updates the store. I am simply pushing the word \"pushed\" to the activeData array:\n\n```\n\nimport {activeData} from './Store.js'\n\nlet handlePush = ()=>{\n activeData.update(val=>{val.push('pushed!')\n val = val\n}\n )\n}\n\npush\n\n```\n\nAnd then in this app.svelte component, I am subscribing to activeData and hoping to print the elements of the activeData array using Svelte's #each directive:\n\n```\n\n import {activeData} from './Store.js'\n import Push from './Push.svelte'\n \n\n {#each $activeData as datum}\n {datum}\n\n {/each}\n\n {@debug $activeData}\n\n```\n\nWhen I check the console for activeData, I see that it updates by adding \"Push!\" to the array. However, I then get an error in my app.svelte component saying \"Error: {#each} only iterates over array-like objects.\"\n\nSo after updating the array, the array is no longer an array to components subscribing to it.\n\nAny idea why this is happening?\n\n========================================\n\nTop Answer:\nThis is how I ended up doing it. Instead of using update, I directly accessed the store value and just manipulated it there.\n\n```\n$activeData = [...$activeData, 'pushed!']\n```\n\nThis fixed my issue. I just couldn't get it to work with the update method.\n\n========================================\n\nCode:\n```text\nimport { writable } from 'svelte/store'\n\nexport const activeData = writable([\"array\"])\n```\n\n```text\n<script>\nimport {activeData} from './Store.js'\n\nlet handlePush = ()=>{\n activeData.update(val=>{val.push('pushed!')\n val = val\n}\n )\n}\n\n</script>\n\n<button\non:click={handlePush}>\npush\n</button>\n```\n\n```text\n<script>\n import {activeData} from './Store.js'\n import Push from './Push.svelte'\n \n\n</script>\n\n<div>\n {#each $activeData as datum}\n <p>{datum}</p>\n {/each}\n\n {@debug $activeData}\n</div>\n\n<Push/>\n```\n\n```text\nactiveData.update(val => [...val, 'pushed!'])\n```\n\n```text\nundefined\n```\n\n```text\n$activeData = [...$activeData, 'pushed!']\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.711Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":124,"estimatedTokens":613}}709{"id":"stack-60154209","source":"stackoverflow","questionId":60154209,"title":"How to refresh DOM when props change in Svelte?","tags":["svelte"],"text":"Title: How to refresh DOM when props change in Svelte?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI have a grid-like structure with a pointer object coming from a parent. Now with some operation, the pointer is getting updated but the change is not getting reflected in the child component, nor is DOM getting updated.\n\nParent:\n\n```\n\n import Boxes from \"./Boxes.svelte\";\n\n let boxes = [\n [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"]\n ];\n\n let activeBox = {\n x: 0,\n y: 0\n };\n\n function handleKeydown(keyEvent) {\n let i = activeBox.x;\n let j = activeBox.y;\n\n const width = boxes[i].length,\n height = boxes.length,\n left = 37,\n up = 38,\n right = 39,\n down = 40,\n tab = 9,\n backspace = 8;\n\n // Loop around single row with right and left arrows\n if (keyEvent.keyCode == right) {\n activeBox.x = activeBox.x + 1;\n if(activeBox.x === boxes[i].length) activeBox.x = 0;\n return;\n }\n\n $: console.log(\"^^^ activeBox &&\", activeBox);\n\n main {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n @media (min-width: 640px) {\n main {\n max-width: none;\n }\n }\n\n \n\n```\n\nThe child component is using the activeBox variable to render the selected box. But this doesn't seem to work as while the first render works perfectly, the box doesn't get updated with it.\n\nChild: \n\n```\n\n export let boxes;\n export let activeBox;\n\n $: console.log(\"^^^ active Box updated\");\n\n function getSelectedClass(i, j) {\n if (activeBox.x === j && activeBox.y === i) {\n return \"selected\";\n }\n return \"\";\n }\n\n .grid-container {\n display: grid;\n grid-template-columns: auto auto auto auto auto auto auto auto;\n background-color: #2196f3;\n padding: 0px;\n }\n .grid-item {\n background-color: rgba(255, 255, 255, 0.8);\n border: 1px solid rgba(0, 0, 0, 0.8);\n width: 40px;\n height: 40px;\n padding: 20px;\n font-size: 30px;\n text-align: center;\n }\n .selected {\n border: 1px solid red;\n }\n\n \n {#each boxes as row, i}\n {#each row as column, j}\n {boxes[i][j]}\n {/each}\n {/each}\n \n\n```\n\nI could really use some insight as I still haven't properly grasped the concept of Svelte. Any help would be much appreciated.\n\n========================================\n\nTop Answer:\nSo a few things to be aware of when using Svelte:\n\n- Don't console log in reactive declarations $: console.log() will run as soon as the component is created but has no other meaning or use.\n\n- When your exported variable is the same as the variable name in the parent component just use {varName} in the tag, no need for varName={varName}\n\nAs far as updating activeBox in the child component, it is being updated but in your code there's no way for it to know that it needs to run the function that selects class again. That function only runs once, which is why it works on initial render.\n\nOne way you can keep the class updated is to have a ternary operator directly in your conditional class statement in the child:\n\n```\n{boxes[i][j]}\n```\n\nAnd just drop the function. Like this\n\n========================================\n\nCode:\n```text\n<script>\n import Boxes from \"./Boxes.svelte\";\n\n let boxes = [\n [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"],\n [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"]\n ];\n\n let activeBox = {\n x: 0,\n y: 0\n };\n\n function handleKeydown(keyEvent) {\n let i = activeBox.x;\n let j = activeBox.y;\n\n const width = boxes[i].length,\n height = boxes.length,\n left = 37,\n up = 38,\n right = 39,\n down = 40,\n tab = 9,\n backspace = 8;\n\n\n\n // Loop around single row with right and left arrows\n if (keyEvent.keyCode == right) {\n activeBox.x = activeBox.x + 1;\n if(activeBox.x === boxes[i].length) activeBox.x = 0;\n return;\n }\n\n $: console.log(\"^^^ activeBox &&\", activeBox);\n</script>\n\n<style>\n main {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n @media (min-width: 640px) {\n main {\n max-width: none;\n }\n }\n</style>\n\n<svelte:window on:keydown=\"{handleKeydown}\" />\n<main>\n <Boxes boxes={boxes} activeBox={activeBox} />\n</main>\n```\n\n```text\n<script>\n export let boxes;\n export let activeBox;\n\n $: console.log(\"^^^ active Box updated\");\n\n function getSelectedClass(i, j) {\n if (activeBox.x === j && activeBox.y === i) {\n return \"selected\";\n }\n return \"\";\n }\n</script>\n\n<style>\n .grid-container {\n display: grid;\n grid-template-columns: auto auto auto auto auto auto auto auto;\n background-color: #2196f3;\n padding: 0px;\n }\n .grid-item {\n background-color: rgba(255, 255, 255, 0.8);\n border: 1px solid rgba(0, 0, 0, 0.8);\n width: 40px;\n height: 40px;\n padding: 20px;\n font-size: 30px;\n text-align: center;\n }\n .selected {\n border: 1px solid red;\n }\n</style>\n\n<main>\n <div class=\"grid-container\">\n {#each boxes as row, i}\n {#each row as column, j}\n <div class=\" grid-item {getSelectedClass(i, j)}\">{boxes[i][j]}</div>\n {/each}\n {/each}\n </div>\n</main>\n```\n\n```js\n$: console.log(\"^^^ active Box updated\");\n```\n\n```html\n{#each boxes as row, i}\n ...\n {/each}\n```\n\n```html\n<div class=\" grid-item {getSelectedClass(i, j)}\">...</div>\n```\n\n```html\n<div class=\" grid-item {getSelectedClass(i, j, activeBox)}\">...</div>\n```\n\n```html\n<div class=\"grid-item\" class:selected={activeBox.x === j && activeBox.y === i}>{boxes[i][j]}</div>\n```\n\n```html\n<script>\n // NOTE this block contains activeBox variable, so isSelected is recreated when\n // activeBox changes\n $: isSelected = (i, j) => activeBox.x === j && activeBox.y === i\n</script>\n\n<main>\n <div class=\"grid-container\">\n {#each boxes as row, i}\n {#each row as column, j}\n <div class=\"grid-item\" class:selected={isSelected(i, j)}>{boxes[i][j]}</div>\n {/each}\n {/each}\n </div>\n</main>\n```\n\n```text\nactiveBox\n```\n\n```text\nboxes\n```\n\n```text\n{getSelectedClass(i, j)}\n```\n\n```text\ngetSelectedClass\n```\n\n```text\ni\n```\n\n```text\nj\n```\n\n```text\ni\n```\n\n```text\nj\n```\n\n```text\ngetSelectedClass\n```\n\n```text\ngetSelectedClass = 'foo'\n```\n\n```text\nactiveBox\n```\n\n```text\nactiveBox\n```\n\n```html\n<div class=\" grid-item {activeBox.x === j && activeBox.y === i? 'selected' : ''}\">{boxes[i][j]}</div>\n```\n\n========================================\n\nComments:\n- I didn't know you could pass arguments with reactive declarations like that, thanks for this awesome answer.","metadata":{"transformedAt":"2026-08-18T18:33:40.711Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":346,"estimatedTokens":1671}}710{"id":"stack-67617050","source":"stackoverflow","questionId":67617050,"title":"Wait for component to be ready in custom svelte directive","tags":["javascript","svelte","svelte-3"],"text":"Title: Wait for component to be ready in custom svelte directive\nTags: javascript, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI recently tried to write a custom directive that did some logic and dispatched an event back to the element it was used on.\n\n```\n//svelte file\n...\n```\n\n```\n// Custom directive\nexport const customDirective = node => {\n //some synchronous logic here\n\n node.dispatchEvent(new CustomEvent('success', node))\n}\n```\n\nWhat I found out is that since the logic in my directive is synchronous it will dispatch the new custom event before the node is ready to catch it. I was able to easily solve it by using `setTimeout()`, but that does not seem like a proper solution. Is there any way for me to use a lifecycle method or something in the directive to make sure the component is ready for the dispatched event?\n\n========================================\n\nCode:\n```text\n//svelte file\n<div use:customDiective on:success={handleSuccess}>...</div>\n```\n\n```js\n// Custom directive\nexport const customDirective = node => {\n //some synchronous logic here\n\n node.dispatchEvent(new CustomEvent('success', node))\n}\n```\n\n```text\nsetTimeout()\n```\n\n```js\n// directive.js\nimport { onMount } from 'svelte';\n\nexport const customDirective = (node) => {\n onMount(() => {\n // other logic\n node.dispatchEvent(new CustomEvent('success', node));\n }); \n}\n```\n\n```html\n<!-- App.svelte -->\n<script>\n import { customDirective } from './directive.js';\n \n let isSuccess = false;\n</script>\n\n<div use:customDirective on:success={() => (isSuccess = true)}>{isSuccess}</div>\n```\n\n```html\n<div on:success={() => (isSuccess = true)} use:customDirective>{isSuccess}</div>\n```\n\n```js\n// on: before use:\nif (!mounted) {\n dispose = [\n listen(div, \"success\", /*success_handler*/ ctx[1]),\n action_destroyer(customDirective_action = customDirective.call(null, div))\n ];\n\n mounted = true;\n}\n\n// use: before on:\nif (!mounted) {\n dispose = [\n action_destroyer(customDirective_action = customDirective.call(null, div)),\n listen(div, \"success\", /*success_handler*/ ctx[1])\n ];\n\n mounted = true;\n}\n```\n\n```text\non:\n```\n\n```text\nuse:\n```\n\n========================================\n\nComments:\n- You could use a Promise for readying the state of the node and call its .then() method in order to dispatch your custom event.\n- putting the on: directive before the use: directive did the trick for me, thank you!","metadata":{"transformedAt":"2026-08-18T18:33:40.711Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":106,"estimatedTokens":617}}711{"id":"stack-73338240","source":"stackoverflow","questionId":73338240,"title":"Dynamically load a template in a Svelte component","tags":["javascript","svelte"],"text":"Title: Dynamically load a template in a Svelte component\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm not entirely sure if this is possible, but I want to dynamically load a component's template in runtime in Svelte. Basically download some user-defined template and use that to build out the component in run-time. Is this actually possible to do?\n\n========================================\n\nCode:\n```js\nimport { compile } from 'svelte/compiler';\n\nconst { js, css } = compile(template, {\n filename: 'Component.svelte',\n format: 'esm',\n});\n\nconsole.log(js.code, css.code);\n```\n\n```js\nconst code = `\n ${js.code.replace(\n 'svelte/internal',\n 'https://unpkg.com/svelte@3.49.0/internal/index.mjs',\n )}\n\n new Component({ target: document.body });\n`;\n\nsrcdoc = `\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset=\"utf-8\">\n <title>Svelte App</title>\n <${''}style>${css.code}</${''}style>\n </head>\n <body>\n <${''}script type=\"module\">${code}</${''}script>\n </body>\n </html>\n`;\n```\n\n```js\nconst componentSrc = URL.createObjectURL(\n new Blob([code], { type: 'text/javascript' })\n);\nconst { default: Component } = await import(componentSrc);\nURL.revokeObjectURL(componentSrc);\n\nnew Component({ target: ... });\n```\n\n```text\n'svelte/internal'\n```\n\n```text\nimport\n```\n\n```text\niframe.srcdoc\n```\n\n```text\n${}\n```\n\n```text\nimport\n```\n\n```text\nBlob\n```\n\n```text\niframe\n```\n\n========================================\n\nComments:\n- Hey this is absolutely fantastic. Thank you so much! I had a question though, could this method be used to handle dependencies? As in, the `template` variable, could it have imports that bring in other Svelte components? And if so, how would I handle this?\n- Depends on where the components come from. If the component is already compiled including all its dependencies, then you can just import the component like any other. E.g. if you want to import `carbon-components-svelte` via unpkg, that would currently not work directly, because it has a live dependency on `flatpickr`. Other components, e.g. `@bulatdashiev/svelte-slider` have no dependencies and could be imported directly. If you want to import components from your current site, you probably should set up your build system such, that they are compiled as independent assets.","metadata":{"transformedAt":"2026-08-18T18:33:40.711Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":89,"estimatedTokens":595}}712{"id":"stack-73250196","source":"stackoverflow","questionId":73250196,"title":"How does server side rendering work with client side routing in SvelteKit?","tags":["javascript","routes","svelte","server-side-rendering","sveltekit"],"text":"Title: How does server side rendering work with client side routing in SvelteKit?\nTags: javascript, routes, svelte, server-side-rendering, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have just read on the SvelteKit docs that SSR is enabled by default and you need to manually disabled it if you don't want it present. This is great for SEO so I'm happy that SvelteKit enforces this by default 😁\n\nI'm getting a little confused though with how SSR interacts with Client side routing.\n\nWhen a SvelteKit app with client side routing enabled is rendered into a browser, is the entire compiled SvelteKit app passed to the browser so that the main content of the page can be swapped in and out with JavaScript when you navigate to a new route on the client side?\n\ne.g. :\n\nYou have a SvelteKit app with two pages `/home` & `/about`. A user travels to the `/home` page. Would then compiled content of the `/about` page also be passed to the client on page load of the `/home` page with client side routing enabled?\n\nIf this is the case should it be a common practice to disable client side routing by default? This way the entire SvelteKit app wouldn't be loaded into the browser when a user may only view a single page of it ?\n\nThanks for reading ! 👋🤠\n\n========================================\n\nCode:\n```text\n/home\n```\n\n```text\n/about\n```\n\n```text\n/home\n```\n\n```text\n/about\n```\n\n```text\n/home\n```\n\n========================================\n\nComments:\n- Great talk just watched it through now, answers a lot of my questions to do with modern web practices in general so thanks for that link. Just checked out the network tab too and you're right in sveltekit the fetching of the page data is just done in the background so the initial page load is not anywhere near as expensive as I thought it was. Thanks for explaining !\n- All of his talks are great :)","metadata":{"transformedAt":"2026-08-18T18:33:40.711Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":47,"estimatedTokens":463}}713{"id":"stack-59693964","source":"stackoverflow","questionId":59693964,"title":"Setting a CSS class based on a variable in Svelte","tags":["javascript","css","svelte"],"text":"Title: Setting a CSS class based on a variable in Svelte\nTags: javascript, css, svelte\nSource: Stack Overflow\n\nQuestion:\ni am working on a custom component in Svelte and i want to be able to set the color with the help of corresponding identifiers(i callem types). For example success -> green, error -> red, etc.\n\nRight now I am exporting a boolean for each of the \"types\" that can be set to true or false and therefore enables a class with the same name or not.\n\n```\nlet success = false;\nlet error = false;\nlet info = false;\nlet warning = false; \n...\n\n```\n\nThis way the user would have to disable all but one of these types everytime he wants to change the type. \n\nIs there a way i could do this similar like this almost pseudo code :D\n\n```\nexport let type = \"\";\n...\n\n```\n\nSo the User could then just use it the following way.\n\n```\n\n```\n\n========================================\n\nCode:\n```text\nlet success = false;\nlet error = false;\nlet info = false;\nlet warning = false; \n...\n<div\n class:success\n class:error\n class:info\n class:warning >\n</div>\n```\n\n```text\nexport let type = \"\";\n...\n<div\n class:{type} >\n</div>\n```\n\n```text\n<custom-comp type={warning} />\n```\n\n```text\nclass={type}\n```\n\n```text\nclass:{type}\n```\n\n========================================\n\nComments:\n- can be even shorter :) by removing the quotes: `class={type}`","metadata":{"transformedAt":"2026-08-18T18:33:40.711Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":75,"estimatedTokens":337}}714{"id":"stack-74178164","source":"stackoverflow","questionId":74178164,"title":"SvelteKit Maintenance Mode","tags":["javascript","svelte","sveltekit"],"text":"Title: SvelteKit Maintenance Mode\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nIs there a good way to do display a maintenance page when visiting any route of my SvelteKit website?\n\nMy app is hosted on Vercel, for those who want to know.\n\nWhat I've tried so far:\n\n- Set an environment variable called `MAINTENANCE_MODE` with a value `1` in Vercel.\n\n- For development purposes I've set this in my .env file to `VITE_MAINTENANCE_MODE` and called with `import.meta.env.VITE_MAINTENANCE_MODE`.\n\nThen inside `+layout.server.js` I have the following code to redirect to `/maintenance` route\n\n```\nimport { redirect } from \"@sveltejs/kit\";\n\nexport async function load({ url }) {\n const { pathname } = url;\n\n // Replace import.meta.env.VITE_MAINTENANCE_MODE with process.env.MAINTENANCE_MODE in Production\n if (import.meta.env.VITE_MAINTENANCE_MODE == 1) {\n if (pathname == \"/maintenance\") return;\n throw redirect(307, \"/maintenance\");\n } else {\n if (pathname == \"/maintenance\") {\n throw redirect(307, \"/\");\n };\n };\n};\n```\n\nWhat I've also tried is just throwing an `error` in `+layout.server.js` with the following:\n\n```\nimport { error } from \"@sveltejs/kit\";\n\nexport async function load() {\n if (import.meta.env.VITE_MAINTENANCE_MODE == 1) {\n throw error(503, \"Scheduled for maintenance\");\n };\n};\n```\n\nHowever this just uses SvelteKit's static fallback error page and not `+error.svelte`. I've tried creating `src/error.html` in the hope to create a custom error page for `+layout.svelte` but couldn't get it to work.\nI would like to use a custom page to display \"Down for maintenance\", but I don't want to create an endpoint for every route in my app to check if the `MAINTENANCE_MODE` is set to 1.\n\nAny help is appreciated\n\n========================================\n\nTop Answer:\nYou can also use `+layout.ts` to hook up for the maintenance mode. You can even make this conditional for some parts of the site (have frontpage still up and running).\n\nHere is the trick we use:\n\n```\nimport type { LayoutLoad } from './$types';\nimport { chainsUnderMaintenance } from '$lib/config';\nimport { error } from '@sveltejs/kit';\n\nexport const load: LayoutLoad = ({ params }) => {\n // Check chain maintenance status; if under maintenance, trigger error (see +error.svelte)\n const chainName = chainsUnderMaintenance[params.chain];\n if (chainName) {\n throw error(503, `Chain under maintenance: ${chainName}`);\n }\n};\n```\n\n========================================\n\nCode:\n```js\nimport { redirect } from \"@sveltejs/kit\";\n\nexport async function load({ url }) {\n const { pathname } = url;\n\n // Replace import.meta.env.VITE_MAINTENANCE_MODE with process.env.MAINTENANCE_MODE in Production\n if (import.meta.env.VITE_MAINTENANCE_MODE == 1) {\n if (pathname == \"/maintenance\") return;\n throw redirect(307, \"/maintenance\");\n } else {\n if (pathname == \"/maintenance\") {\n throw redirect(307, \"/\");\n };\n };\n};\n```\n\n```js\nimport { error } from \"@sveltejs/kit\";\n\nexport async function load() {\n if (import.meta.env.VITE_MAINTENANCE_MODE == 1) {\n throw error(503, \"Scheduled for maintenance\");\n };\n};\n```\n\n```text\nMAINTENANCE_MODE\n```\n\n```text\n1\n```\n\n```text\nVITE_MAINTENANCE_MODE\n```\n\n```text\nimport.meta.env.VITE_MAINTENANCE_MODE\n```\n\n```text\n+layout.server.js\n```\n\n```text\n/maintenance\n```\n\n```text\nerror\n```\n\n```text\n+layout.server.js\n```\n\n```text\n+error.svelte\n```\n\n```text\nsrc/error.html\n```\n\n```text\n+layout.svelte\n```\n\n```text\nMAINTENANCE_MODE\n```\n\n```js\nimport { env } from '$env/dynamic/private';\nimport type { Handle } from '@sveltejs/kit';\n\nexport const handle: Handle = async ({ event, resolve }) => {\n if (env.MAINTENANCE_MODE == '1' && event.route.id != '/maintenance')\n return new Response(undefined, { status: 302, headers: { location: '/maintenance' } });\n\n // <other logic>\n \n // Default response\n return await resolve(event);\n}\n```\n\n```js\nimport { beforeNavigate } from '$app/navigation';\n\nbeforeNavigate(async ({ cancel }) => {\n cancel();\n});\n```\n\n```text\nhandle\n```\n\n```text\nsrc/hooks.server.ts\n```\n\n```text\nfetch\n```\n\n```text\nimport type { LayoutLoad } from './$types';\nimport { chainsUnderMaintenance } from '$lib/config';\nimport { error } from '@sveltejs/kit';\n\nexport const load: LayoutLoad = ({ params }) => {\n // Check chain maintenance status; if under maintenance, trigger error (see +error.svelte)\n const chainName = chainsUnderMaintenance[<string>params.chain];\n if (chainName) {\n throw error(503, `Chain under maintenance: ${chainName}`);\n }\n};\n```\n\n```text\n+layout.ts\n```\n\n========================================\n\nComments:\n- Thanx, will try this. I've wanted to do a handle hook, just couldn't figure out the redirect. My question to this, would it also redirect if routing to eg. /login?\n- The code currently only excludes the `/maintenance` route (to prevent a loop), if you want to exclude others you just have to extend the `if` statement.\n- Nothing's happening for me during development. Would the `hooks.server.ts` only run when deployed?\n- No, it should always work. Make sure it is in the correct folder and check whether the default hooks location was changed via the config (see docs).\n- Got it working. I was just due to a simple update to SvelteKit 🤦. I'll mark this as the solution\n- Please notice that it is now `event.route.id` instead of `event.routeId` in Sveltekit 1.0","metadata":{"transformedAt":"2026-08-18T18:33:40.711Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":214,"estimatedTokens":1347}}715{"id":"stack-73819151","source":"stackoverflow","questionId":73819151,"title":"Svelte (Vite) + Bootstrap 5 + SvelteStrap error: Type 'string' is not assignable to type 'ButtonColor'","tags":["typescript","svelte","bootstrap-5"],"text":"Title: Svelte (Vite) + Bootstrap 5 + SvelteStrap error: Type 'string' is not assignable to type 'ButtonColor'\nTags: typescript, svelte, bootstrap-5\nSource: Stack Overflow\n\nQuestion:\nI'm using Svelte (Vite) + Bootstrap 5 + SvelteStrap. My code is the following:\n\n```\n\n \n\n import { Button } from 'sveltestrap';\n let color = \"danger\";\n\n {color}\n\n```\n\nThis works normally on the browser, but VSCode says:\n\nType 'string' is not assignable to type 'ButtonColor'.\n\nI'm just starting out with Svelte, and I'm trying to modify the standard example on the SvelteStrap website:\n\n```\n\n \n\n import { Button } from 'sveltestrap';\n const colors: any = [\n 'primary',\n 'secondary',\n 'success',\n 'danger',\n 'warning',\n 'info',\n 'light',\n 'dark'\n ];\n\n{#each colors as color}\n \n {color}\n \n{/each}\n```\n\nUsing the standard example, no erros are fired. What am I doing wrong? Why is this happening?\n\n========================================\n\nCode:\n```text\n<head>\n <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css\">\n</head>\n<script>\n import { Button } from 'sveltestrap';\n let color = \"danger\";\n</script>\n\n<div>\n <Button color=\"{color}\">{color}</Button>\n</div>\n```\n\n```text\n<head>\n <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css\">\n</head>\n<script lang=\"ts\">\n import { Button } from 'sveltestrap';\n const colors: any = [\n 'primary',\n 'secondary',\n 'success',\n 'danger',\n 'warning',\n 'info',\n 'light',\n 'dark'\n ];\n</script>\n\n{#each colors as color}\n <div>\n <Button {color}>{color}</Button>\n </div>\n{/each}\n```\n\n```js\nconst colors = [\n 'primary',\n 'secondary',\n 'success',\n 'danger',\n 'warning',\n 'info',\n 'light',\n 'dark'\n] as const; // <--\n```\n\n```js\ndeclare type ButtonColor =\n | 'primary'\n | 'secondary'\n | 'success'\n | 'danger'\n | 'warning'\n | 'info'\n | 'light'\n | 'dark'\n | 'link';\n```\n\n```js\nimport type { SvelteComponentTyped } from 'svelte';\nimport type { Button } from 'sveltestrap';\n\ntype PropsOf<C> = C extends SvelteComponentTyped<infer Props> ? Props : never;\ntype ButtonProps = PropsOf<Button>;\ntype ButtonColor = Exclude<ButtonProps['color'], undefined>;\n```\n\n```js\nconst colors: ButtonColor[] = [\n 'primary',\n 'secondary',\n 'success',\n 'danger',\n 'warning',\n 'info',\n 'light',\n 'dark'\n];\n```\n\n```text\ncolor\n```\n\n```text\nstring[]\n```\n\n```text\nas const\n```\n\n```text\nButtonColor\n```\n\n```text\nButton\n```\n\n========================================\n\nComments:\n- Thanks for the in-detail explanation, it solved my issue!","metadata":{"transformedAt":"2026-08-18T18:33:40.711Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":163,"estimatedTokens":653}}716{"id":"stack-63296482","source":"stackoverflow","questionId":63296482,"title":"Websockets in Sapper","tags":["javascript","websocket","svelte","sapper"],"text":"Title: Websockets in Sapper\nTags: javascript, websocket, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI have a readable store in Svelte that looks like this:\n\n```\nconst state = {};\nexport const channels = readable(state, set => {\n let st = state;\n let socket = new WebSocket(\"ws://127.0.0.1:5999\");\n \n socket.onmessage = function (event) {\n var datastr = event.data.split(':');\n st[datastr[0]].value = datastr[1];\n st[datastr[0]].timestamp = Date.now();\n set(st)\n };\n return () => {\n socket.close()\n }\n \n});\n```\n\nWhen I import it to my Svelte App works. But if I put that App.svelte as my index.svelte running on Sapper, it doesnt work at first. It says error 500 websocket is not defined. Once I reload the page in the browser start to work...\nI have try to parse a function that creates the store instead:\n\n```\nexport const getChannel = () => {\n // here my store\nreturn {...store}\n}\n```\n\nand then creating the store inside a onMount() like this:\n\n```\nonMount( ()=> {\n const channel = getChannel();\n});\n```\n\nBut doesnt seem to do the trick... What do I miss?\nNote: If a just replace the store by a simple writable, and create the websocket onMount(), it works without any problem. I just only wanted to put all the communication inside the store as a readable...\n\n========================================\n\nCode:\n```text\nconst state = {};\nexport const channels = readable(state, set => {\n let st = state;\n let socket = new WebSocket(\"ws://127.0.0.1:5999\");\n \n socket.onmessage = function (event) {\n var datastr = event.data.split(':');\n st[datastr[0]].value = datastr[1];\n st[datastr[0]].timestamp = Date.now();\n set(st)\n };\n return () => {\n socket.close()\n }\n \n});\n```\n\n```text\nexport const getChannel = () => {\n // here my store\nreturn {...store}\n}\n```\n\n```text\nonMount( ()=> {\n const channel = getChannel();\n});\n```\n\n```js\nconst state = {};\nexport const channels = readable(state, (set) => {\n if (typeof WebSocket === 'undefined') return;\n\n let st = state;\n let socket = new WebSocket(\"ws://127.0.0.1:5999\");\n\n socket.onmessage = function (event) {\n var datastr = event.data.split(\":\");\n st[datastr[0]].value = datastr[1];\n st[datastr[0]].timestamp = Date.now();\n set(st);\n };\n return () => {\n socket.close();\n };\n});\n```\n\n```text\nonMount\n```\n\n```text\nif (process.browser) {...}\n```\n\n```text\n$channels\n```\n\n```text\nchannels.subscribe(...)\n```\n\n```text\nWebSocket\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.711Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":121,"estimatedTokens":630}}717{"id":"stack-60572188","source":"stackoverflow","questionId":60572188,"title":"Is passing environment variables to sapper's client side secure with Rollup Replace?","tags":["environment-variables","svelte","rollupjs","sapper"],"text":"Title: Is passing environment variables to sapper's client side secure with Rollup Replace?\nTags: environment-variables, svelte, rollupjs, sapper\nSource: Stack Overflow\n\nQuestion:\nI am using replace in my rollup configuration for sapper and sapper-environment to pass environment variables to the client side in sapper - is this secure? Is there a better/safer way to approach this?\n\nUsing this config below:\n\n```\nrollup.config.js\n\n const sapperEnv = require('sapper-environment'); \n\n export default {\n client: {\n input: config.client.input(),\n output: config.client.output(),\n plugins: [\n replace({\n ...sapperEnv(),\n 'process.browser': true,\n 'process.env.NODE_ENV': JSON.stringify(mode)\n })\n ...\n```\n\nAnd then this allows me to use the variables in stores.js:\n\n```\nimport { writable } from 'svelte/store';\nimport Client from 'shopify-buy';\n\nconst key = process.env.SAPPER_APP_SHOPIFY_KEY;\nconst domain = process.env.SAPPER_APP_SHOPIFY_DOMAIN;\n\n// Initialize a client\nconst client = Client.buildClient({\n domain: domain,\n storefrontAccessToken: key\n});\n\nexport { key, domain, client };\n```\n\nI have tried running this in server,js and passing the variables through the session data, but client side no matter what I do they always seems to return 'undefined'.\n\n========================================\n\nCode:\n```text\nrollup.config.js\n\n const sapperEnv = require('sapper-environment'); \n\n export default {\n client: {\n input: config.client.input(),\n output: config.client.output(),\n plugins: [\n replace({\n ...sapperEnv(),\n 'process.browser': true,\n 'process.env.NODE_ENV': JSON.stringify(mode)\n })\n ...\n```\n\n```text\nimport { writable } from 'svelte/store';\nimport Client from 'shopify-buy';\n\nconst key = process.env.SAPPER_APP_SHOPIFY_KEY;\nconst domain = process.env.SAPPER_APP_SHOPIFY_DOMAIN;\n\n// Initialize a client\nconst client = Client.buildClient({\n domain: domain,\n storefrontAccessToken: key\n});\n\nexport { key, domain, client };\n```\n\n```text\nundefined\n```\n\n========================================\n\nComments:\n- Thanks for the clarification on security. I tried to just use the environment variables in server.js and call the shopify initialize client but I think I can't pass it to the middleware as when it gets run through devalue it fails as the function contains custom classes. Is there a solution to that? I tried just exporting the returned value and it kept coming back as 'client is undefined' on the clientside.\n- For reference when I initialize the shopify client in server.js and try to display the variable on client side I get nothing and the console in browser reads - `TypeError: Error resolving module specifier: fs` ? Here is REPL of the code.\n- I have a similar issue. I just want to pass some process.env fields so I don't have to hard code an api protocol, host, and port. I'm finding it very hard to pass those to a route component. There is a preload function, but I want values to be available directly from the component.\n- @SMBNS you can't run a Sapper app in the REPL. Given your error message it sounds like you're importing server-specific code in parts of your app that run in the client\n- Thanks @RichHarris - I know it won't run in the REPL it was more to show the code I was using. I have found out the API i want to use is an unauthenticated one so can probably be passed client side safely. But I will experiment with using a server route or similar to see if I can achieve what I want.","metadata":{"transformedAt":"2026-08-18T18:33:40.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":96,"estimatedTokens":893}}718{"id":"stack-73432013","source":"stackoverflow","questionId":73432013,"title":"Trying to understand why changing a variable re-triggers reactive statements of unrelated variables","tags":["svelte","svelte-3"],"text":"Title: Trying to understand why changing a variable re-triggers reactive statements of unrelated variables\nTags: svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\n### Context\n\nHere's a simplified version of my context:\n\nhttps://i.sstatic.net/CAcmk.png\nI have a component which\n\n- fetches a collection of items from the server -> `bookmarks [{title, url}, ...]`\n\n- in a reactive statement, populates a new collection from `bookmarks` by adding a new property with the domain name of the url: `xbookmarks = [{title, url, domain}, ...]\nmakes it possible to filter bookmarks by domain, by displaying a list of checkboxes, one per domain:\n\n- this is achieved by declaring a `filter: {domains: {domain:true|false, ...}}` variable\n\n- the `filter.domains` map is populated in a reactive statement by iterating over `xbookmarks` and setting all domains to `true`\n\n- finally, a `filterdBookmarks` variable is computed in a reactive statement by filtering `xbookmarks` using `filter`\n\n- displays the filtered bookmarks\n\n### What I have tried\n\nHere's the flow in pseudo-javascript:\n\n```\nlet bookmarks=[]\n\nlet xbookmarks=[]\n$: xbookmarks = bookmarks.map(b=>{...b, domain: computeDomain(b)})\n\nlet filter = {domains: {}}\n$: filter.domains=extractDomains(xbookmarks)\n\nlet filterdBookmarks=[]\n$: filterBookmarks = xbookmarks.filter(using filter)\n```\n\nHere's a link to the svelte REPL with the complete code described above: https://svelte.dev/repl/d07ffc88e4a34cb797d2ceb6ba0ec6a4?version=3.49.0\n\n### Problem\n\nWhen I try to uncheck one of the domains checkboxes:\n\n### Expected behaviour:\n\n`filter` changed => trigger recomputation of depending variables, i.e. `filterdBookmarks`\n\n### Actual behaviour:\n\n`filter` changed => Svelte recomputes `xbookmarks`, then `filter.domains` which resets it back to all domains being checked, then `filterdBookmarks`\n\nI can't understand why Svelte considers that `xbookmarks` depends on `filter`\n\nWhen I looked into the JS code generated by Svelte, this shouldn't be happening:\n\nhttps://i.sstatic.net/JyClu.png\n\nAs can be seen in the screenshot above, the generated code matches my intuition about the dependencies:\n\n- `xbookmarks` is recomputed when `bookmarks` changes\n\n- `filter.domains` is recomputed when `xbookmarks` changes\n\n- `filteredBookmarks` is recomputed when either of `filter` of `xbookmarks` changes\n\nP.S.: I have just started learning and playing with Svelte\n\n========================================\n\nCode:\n```js\nlet bookmarks=[]\n\nlet xbookmarks=[]\n$: xbookmarks = bookmarks.map(b=>{...b, domain: computeDomain(b)})\n\nlet filter = {domains: {}}\n$: filter.domains=extractDomains(xbookmarks)\n\nlet filterdBookmarks=[]\n$: filterBookmarks = xbookmarks.filter(using filter)\n```\n\n```text\nbookmarks [{title, url}, ...]\n```\n\n```text\nbookmarks\n```\n\n```text\nfilter: {domains: {domain:true|false, ...}}\n```\n\n```text\nfilter.domains\n```\n\n```text\nxbookmarks\n```\n\n```text\ntrue\n```\n\n```text\nfilterdBookmarks\n```\n\n```text\nxbookmarks\n```\n\n```text\nfilter\n```\n\n```text\nfilter\n```\n\n```text\nfilterdBookmarks\n```\n\n```text\nfilter\n```\n\n```text\nxbookmarks\n```\n\n```text\nfilter.domains\n```\n\n```text\nfilterdBookmarks\n```\n\n```text\nxbookmarks\n```\n\n```text\nfilter\n```\n\n```text\nxbookmarks\n```\n\n```text\nbookmarks\n```\n\n```text\nfilter.domains\n```\n\n```text\nxbookmarks\n```\n\n```text\nfilteredBookmarks\n```\n\n```text\nfilter\n```\n\n```text\nxbookmarks\n```\n\n```text\ninput_change_handler\n```\n\n========================================\n\nComments:\n- @H.B.: that indeed seems to be the case ! Thank you ! Could you post your comment as an answer so that I could accept it ?\n- Well, technically this probably should be closed as duplicate or deleted, but ok...","metadata":{"transformedAt":"2026-08-18T18:33:40.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":193,"estimatedTokens":911}}719{"id":"stack-76413876","source":"stackoverflow","questionId":76413876,"title":"Svelte mui Select ignores on:change handler","tags":["material-ui","svelte","smui"],"text":"Title: Svelte mui Select ignores on:change handler\nTags: material-ui, svelte, smui\nSource: Stack Overflow\n\nQuestion:\nI have a basic example of Select control on which I try to attach an onChange handler:\n\n```\n\n import Select, { Option } from '@smui/select';\n\n const onChange = () => {\n console.log('on change!');\n };\n\n let fruits = ['Apple', 'Orange', 'Banana', 'Mango'];\n\n let value = 'Orange';\n\n```\n\n```\n\n \n {#each fruits as fruit}\n {fruit}\n {/each}\n \n \n Selected: {value}\n \n```\n\nHowever the event handler is ignored. I am using latest smui and svelte\n\n========================================\n\nCode:\n```text\n<script type=\"ts\">\n import Select, { Option } from '@smui/select';\n\n const onChange = () => {\n console.log('on change!');\n };\n\n let fruits = ['Apple', 'Orange', 'Banana', 'Mango'];\n\n let value = 'Orange';\n</script>\n```\n\n```text\n<div>\n <Select bind:value label=\"Select Menu\" on:change={onChange}>\n {#each fruits as fruit}\n <Option value={fruit}>{fruit}</Option>\n {/each}\n </Select>\n \n <pre class=\"status\">Selected: {value}</pre>\n </div>\n```\n\n```html\n<script type=\"ts\">\n import Select, { Option } from '@smui/select';\n\n const onChange = () => {\n console.log('on change!');\n };\n\n let fruits = ['Apple', 'Orange', 'Banana', 'Mango'];\n\n let value = 'Orange';\n</script>\n\n<div>\n <Select bind:value label=\"Select Menu\" on:SMUISelect:change={onChange}>\n {#each fruits as fruit}\n <Option value={fruit}>{fruit}</Option>\n {/each}\n </Select>\n\n <pre class=\"status\">Selected: {value}</pre>\n</div>\n```\n\n```text\non:SMUISelect:change\n```\n\n========================================\n\nComments:\n- How do you even know that there *is* a `change` event? The documentation for `smui` is kinda useless/cannot even be called that.\n- I don't know, but it seems like a basic feature to have for a Select control. Actually the only events for which I get an autocomplete in VSCode are focus and blur,which doesn't work either. I might do something wrong though. on:click works, for example","metadata":{"transformedAt":"2026-08-18T18:33:40.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":97,"estimatedTokens":526}}720{"id":"stack-72784767","source":"stackoverflow","questionId":72784767,"title":"How to debug svelte with Chrome/Firefox devtools","tags":["debugging","google-chrome-devtools","svelte"],"text":"Title: How to debug svelte with Chrome/Firefox devtools\nTags: debugging, google-chrome-devtools, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implement Svelte in some parts of my web but I can't debug it with chrome devtools.\n\nI generate sourcemaps to see the source svelte component and it let me add breakpoints but when going next step, the debugger breaks and it jumps lines.\n\nIn the example the debugger is stopped in the first line of the click handler and it works perfect: can see variable value etc.\n\nhttps://i.sstatic.net/u2ud2.png\n\nBut, when clicking the \"Next step\" button to go to the *else* statement the debugger breaks.\n\nhttps://i.sstatic.net/qXD1o.png\n\nAs you can see, the debugger is stopped in the *]*, but it should be stopped in the line 9. That occurs also if you put another breakopoint in that line.\n\nI know I can use `@debug` in template and `console.log`'s in javascript but debugger is more powerful.\n\n========================================\n\nTop Answer:\n**Hope this will help you**\n\nI'm not seeing any error for debugger.\nAs the value of `name` is `availableNames[0]` so its 'Christian'.\n\nAs you can see, the debugger is stopped in the ], but it should be stopped in the line 9\n\nDebugger shouldn't stop at the line 9 cause condition is met with line 6, so it will go inside that if block.\n\n========================================\n\nCode:\n```text\n@debug\n```\n\n```text\nconsole.log\n```\n\n```text\nname\n```\n\n```text\navailableNames[0]\n```\n\n========================================\n\nComments:\n- I usually just use the compiled output; a bit more messy but you don't have to deal with source maps not working correctly.\n- Apparently source map is incorrect, probably a bug in Svelte or in devtools.\n- What about adding the statement \"debugger\" (without quotes) at line 6. if your dev tools are open it will stop the code execution and u will see variables values\n- @H.B. That's a little bit weird, isn't it? xD\n- @wOxxOm that's what I thought.\n- @AbdelkaderKEBIR Tried! But same result that setting manually the breakpoint\n- Thanks for answer but the name in the example was \"Esteban\" because was the second time I called the function. Sorry for misunderstanding. Still I didn't think that the debugger should be stopped in the closing bracket. It should mark the starting point as you can see in this vanilla js example: imgur.com/a/gmgr24J\n- How you configured your project? Did you use `npm init vite my-app -- --template svelte` to start the project? Thanks\n- it's a project created 1 year ago, so i think it's not the same method as yours. there is no vite in my environement","metadata":{"transformedAt":"2026-08-18T18:33:40.712Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":64,"estimatedTokens":653}}721{"id":"stack-58286601","source":"stackoverflow","questionId":58286601,"title":"Who is my parent component / parent name in Svelte 3","tags":["svelte","svelte-component","svelte-3"],"text":"Title: Who is my parent component / parent name in Svelte 3\nTags: svelte, svelte-component, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI have a component which is used by different kind of components (parents). This component's behaviour slightly depends on who is his parent (the kind of parent).\n\nOfcourse I can pass the parent's name as a prop or bind or ... \n\n**My question:** Is it possible for the nested component to find out by itself who is the parent? during onMount?\n\n========================================\n\nComments:\n- OK. I think maybe I can hack something using a \"this binding (bind:this=..)\" and then looking in the dom for the parent. But we skip the hack and pass a prop with a component kind id.","metadata":{"transformedAt":"2026-08-18T18:33:40.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":15,"estimatedTokens":179}}722{"id":"stack-60899838","source":"stackoverflow","questionId":60899838,"title":"Svelte.js component property is undefined within script tag with customElement: true","tags":["javascript","web-component","svelte","svelte-3","svelte-component"],"text":"Title: Svelte.js component property is undefined within script tag with customElement: true\nTags: javascript, web-component, svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nThis might possibly be how Svelte.js works, but I'm curious if I'm doing something wrong, or if there's a workaround.\n\nIf I set compiler option `customElement: true`, properties passed to components are not available in the `` tag within that component. I use webpack with svelte-loader. Here's a simple example:\n\n```\n// index.html\n\n// script.js (bundled into bundle.js)\n\nimport App from './App.svelte';\ncustomElements.define('my-app', App);\n\n// App.svelte\n\n export let foo;\n console.log(foo); // undefined\n\n $: bar = foo.toUpperCase(); // Cannot read property 'toUpperCase' of undefined\n\n $: qux = String(foo).toUpperCase(); // No error, works\n\n{ foo } // testing svelte - works, as expected\n\n{ qux } // TESTING SVELTE - works, as expected\n```\n\nAlso if `customElement: true` is not set, and the framework is instantiated with `const app = new App(...)` constructor, `console.log(foo)` would work, just as `$: bar = foo.toUpperCase()`.\n\nCould anyone explain why Svelte works this way? Thanks, cheers!\n\n========================================\n\nCode:\n```text\n// index.html\n\n<my-app foo=\"testing svelte\"></my-app>\n<script src=\"bundle.js\"></script>\n\n\n// script.js (bundled into bundle.js)\n\nimport App from './App.svelte';\ncustomElements.define('my-app', App);\n\n\n// App.svelte\n\n<script>\n export let foo;\n console.log(foo); // undefined\n\n $: bar = foo.toUpperCase(); // Cannot read property 'toUpperCase' of undefined\n\n $: qux = String(foo).toUpperCase(); // No error, works\n</script>\n\n{ foo } // testing svelte - works, as expected\n\n{ qux } // TESTING SVELTE - works, as expected\n```\n\n```text\ncustomElement: true\n```\n\n```text\n<script>\n```\n\n```text\ncustomElement: true\n```\n\n```text\nconst app = new App(...)\n```\n\n```text\nconsole.log(foo)\n```\n\n```text\n$: bar = foo.toUpperCase()\n```\n\n```js\nconst app = new App({ target })\napp.$set({ foo: 'bar' })\n```\n\n```js\nconst app = new App({ target, props: { foo: 'bar' } })\n```\n\n```html\n<script>\n // default value\n export let name = ''\n\n // ... or sanity check\n export let other\n $: otherName = other != null ? other + name : null\n<script>\n```\n\n```text\nconsole.log\n```\n\n```text\n<script>\n```\n\n```text\nnew App(...)\n```\n\n========================================\n\nComments:\n- Thanks, totally makes sense now, that's why `String(foo).toUpperCase()` worked - by using the `String` constructor on a declared (undefined) variable, it's value is `'undefined'`, which is a string so `toUpperCase` wouldn't trigger an error, and when the component gets rendered, it already has the updated value. So the easiest solution is basically setting an empty string as a default value.","metadata":{"transformedAt":"2026-08-18T18:33:40.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":127,"estimatedTokens":703}}723{"id":"stack-56736213","source":"stackoverflow","questionId":56736213,"title":"How to pass the item from an each loop into a function","tags":["svelte"],"text":"Title: How to pass the item from an each loop into a function\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI have a component which contains:\n\n```\n{#each menuItems as item}\n\n ...stuff...\n\n{/each}\n```\n\nmenuItems is an array of objects:\n\n```\n$: menuItem = [{\nid: 'abc',\nselected: true,\n}]\n```\n\nI have a function called `select` which needs to take the item from the each loop as a parameter. How would I do this? The current example does not work due to `on:click` requiring a function like `on:click={submit}`. I have tried within quotation marks, and that did not work either.\n\n========================================\n\nCode:\n```html\n{#each menuItems as item}\n<div class=\"menu-item {item.selected ? 'selected' : ''}\" on:click={select(item)}>\n ...stuff...\n</div>\n{/each}\n```\n\n```js\n$: menuItem = [{\nid: 'abc',\nselected: true,\n}]\n```\n\n```text\nselect\n```\n\n```text\non:click\n```\n\n```text\non:click={submit}\n```\n\n```html\n<script>\n const menuItems = [\n {\n id: 'abc',\n selected: true\n },\n {\n id: 'def',\n selected: false\n }\n ];\n\n function select(item) {\n alert(item.id);\n }\n</script>\n\n{#each menuItems as item}\n <div\n class=\"menu-item {item.selected ? 'selected' : ''}\"\n on:click={() => select(item)}\n >\n {item.id}\n </div>\n{/each}\n```\n\n```text\non:click={select(item)}\n```\n\n```text\nselect\n```\n\n```text\non:click\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":95,"estimatedTokens":340}}724{"id":"stack-73873322","source":"stackoverflow","questionId":73873322,"title":"Derived store populated by async request","tags":["javascript","asynchronous","svelte"],"text":"Title: Derived store populated by async request\nTags: javascript, asynchronous, svelte\nSource: Stack Overflow\n\nQuestion:\nIn svelte, I have a store `parent`:\n\n```\n// parent.js\nimport { writable } from \"svelte/store\"\n\nlet parent = writable('')\n\nexport default parent\n```\n\nI now want to create a derived store `child`, which fetches additional data from an external API in an asynchronous request. In my views, I would like to await `child` to be populated with the updated date when I display its contents.\n\nI have worked myself through the examples of stores on svelte.dev, but I was not able to come up with a solution.\n\nI tried to different things, but I feel I lack understanding of how a derived store works in svelte.\n\n========================================\n\nCode:\n```js\n// parent.js\nimport { writable } from \"svelte/store\"\n\nlet parent = writable('')\n\nexport default parent\n```\n\n```text\nparent\n```\n\n```text\nchild\n```\n\n```text\nchild\n```\n\n```js\nconst child = derived(parent, $parent => (async () => {\n // Delay to simulate a long API call\n await new Promise(res => setTimeout(res, 500));\n \n return {\n parent: $parent,\n child: new Date(), // Some new child data here\n };\n})()); // <- Immediately invoked async function\n```\n\n```html\n{#await $child then childData}\n ...\n{/await}\n```\n\n```text\nderived\n```\n\n```text\n$parent\n```\n\n```text\nparent\n```\n\n```text\nchild\n```\n\n========================================\n\nComments:\n- The `parent` within the writable argument makes no sense, it references the store itself.\n- @H.B.Thanks, sorry, that was a typo.","metadata":{"transformedAt":"2026-08-18T18:33:40.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":85,"estimatedTokens":395}}725{"id":"stack-75094459","source":"stackoverflow","questionId":75094459,"title":"Svelte / SvelteKit 'before:event'?","tags":["javascript","typescript","forms","events","svelte"],"text":"Title: Svelte / SvelteKit 'before:event'?\nTags: javascript, typescript, forms, events, svelte\nSource: Stack Overflow\n\nQuestion:\nI have a custom `Form.svelte` component, which has its own submit handler, however I would like to expose this somewhat, to allow me to have a specific function run *before* the submit function is called.\n\nA simplified version:\n\n`Form.svelte`\n\n```\n\nconst handleSubmit = async () => {\n // Do things\n}\n\n \n\n```\n\n`customers/new/+page.svelte`\n\n```\n\ntype Customer = { postcode: string, shipping_postcode: string };\n\nlet duplicateAddress = false;\nconst customer = { postcode: \"\", shipping_postcode: \"\" };\n\nconst beforeSubmit = () => {\n if (duplicateAddress) customer.shipping_postcode = customer.postcode;\n\n if (!customer.postcode) {\n // Throw an error, for example.\n }\n}\n\n \n \n\n```\n\nIs this possible and, if so, how do I implement this?\n\n========================================\n\nTop Answer:\nTholle's answer shows how to do it correctly (and recommended) according to svelte way. But because of I was late and I have already started writing an answer, I will offer an alternative method as an option:\n\nit would be possible to pass the beforeSubmit function as an argument to the Form component. This would allow in such a way as shown below, to make the execution of handleSubmit dependent on the result of the beforeSubmit execution\n\n```\n\nimport Form from './Form.svelte';\n \n\nlet duplicateAddress = false;\nconst customer = { postcode: \"\", shipping_postcode: \"\" };\n\nconst beforeSubmit = (e) => { \n if (duplicateAddress) customer.shipping_postcode = customer.postcode;\n\n e.preventDefault()\n if (!customer.postcode) {\n // Throw an error, for example.\n alert('cancel')\n return false;\n }\n \n return true;\n}\n\n \n \n\n```\n\n```\n\n \nimport { createEventDispatcher } from 'svelte';\nconst dispatch = createEventDispatcher();\n \nexport let beforeSubmit = null;\n \nconst handleSubmit = async (e) => {\n \n alert('submit')\n}\n\n beforeSubmit(e) && handleSubmit(e) : handleSubmit} class=\"new-form\">\n \n\n```\n\n========================================\n\nCode:\n```text\n<script>\nconst handleSubmit = async () => {\n // Do things\n}\n</script>\n\n<form on:submit={handleSubmit} class=\"new-form\">\n <slot />\n</form>\n```\n\n```text\n<script lang=\"ts\">\ntype Customer = { postcode: string, shipping_postcode: string };\n\nlet duplicateAddress = false;\nconst customer = { postcode: \"\", shipping_postcode: \"\" };\n\nconst beforeSubmit = () => {\n if (duplicateAddress) customer.shipping_postcode = customer.postcode;\n\n if (!customer.postcode) {\n // Throw an error, for example.\n }\n}\n</script>\n\n<Form before:submit={beforeSubmit} data={customer}>\n <input type=\"text\" bind:value={customer.postcode} placeholder=\"Postcode\" />\n <input type=\"checkbox\" bind:checked={duplicateAddress} />\n</Form>\n```\n\n```text\nForm.svelte\n```\n\n```text\nForm.svelte\n```\n\n```text\ncustomers/new/+page.svelte\n```\n\n```html\n<!-- Form.svelte -->\n<script>\n import { createEventDispatcher } from 'svelte';\n\n const dispatch = createEventDispatcher();\n \n const handleSubmit = async () => {\n dispatch('beforeSubmit');\n\n // Do things\n }\n</script>\n\n<form on:submit={handleSubmit} class=\"new-form\">\n <slot />\n</form>\n\n<!-- customers/new/+page.svelte -->\n<script lang=\"ts\">\n // ...\n\n const beforeSubmit = () => {\n // ...\n }\n</script>\n\n<Form on:beforeSubmit={beforeSubmit} data={customer}>\n <input type=\"text\" bind:value={customer.postcode} placeholder=\"Postcode\" />\n <input type=\"checkbox\" bind:checked={duplicateAddress} />\n</Form>\n```\n\n```text\nbeforeSubmit\n```\n\n```text\non:beforeSubmit\n```\n\n```text\n<script lang=\"ts\">\n\nimport Form from './Form.svelte';\n \n\nlet duplicateAddress = false;\nconst customer = { postcode: \"\", shipping_postcode: \"\" };\n\nconst beforeSubmit = (e) => { \n if (duplicateAddress) customer.shipping_postcode = customer.postcode;\n\n e.preventDefault()\n if (!customer.postcode) {\n // Throw an error, for example.\n alert('cancel')\n return false;\n }\n \n return true;\n}\n</script>\n\n<Form data={customer} beforeSubmit={beforeSubmit}>\n <input type=\"text\" bind:value={customer.postcode} placeholder=\"Postcode\" />\n <input type=\"checkbox\" bind:checked={duplicateAddress} />\n</Form>\n```\n\n```text\n<script>\n \nimport { createEventDispatcher } from 'svelte';\nconst dispatch = createEventDispatcher();\n \nexport let beforeSubmit = null;\n \nconst handleSubmit = async (e) => {\n \n alert('submit')\n}\n</script>\n\n<form on:submit={beforeSubmit ? e => beforeSubmit(e) && handleSubmit(e) : handleSubmit} class=\"new-form\">\n <slot />\n</form>\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.712Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":233,"estimatedTokens":1138}}726{"id":"stack-75153526","source":"stackoverflow","questionId":75153526,"title":"Integration of 'sort by' (and other filters) with SvelteKit","tags":["express","filtering","svelte","prisma","sveltekit"],"text":"Title: Integration of 'sort by' (and other filters) with SvelteKit\nTags: express, filtering, svelte, prisma, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a backend route '/products' (using ExpressJS and Prisma) that returns a list of all products, however it also has some query parameters that can be used to specify futher, namely:\n\n- page (and count): used for pagination\n\n- sort and sortDir: used for sorting by a value in a specific direction (desc or asc)\n\n- category: comma separated list of categories to search by\n\nI load the products on the frontend SvelteKit project in `+page.server.ts` and display them in a table format. However, when the user changes, for instance, the sort direction, how would I update the page data using a new route (namely the original one, with sortDir=desc). Is there some way of invalidating the query and replacing it with a new one, with the correct search parameters?\n\nOr is there some other way that this is normally implemented in production?\n\n========================================\n\nCode:\n```text\n+page.server.ts\n```\n\n```text\n// +page.server.js\nexport async function load({ fetch, url }) => {\n const sortDir = url.searchParams.get(\"sortDir\")\n return {\n products: await ...,\n };\n};\n```\n\n```text\n<a href=\"?sortDir=asc\">ASC</a>\n```\n\n```text\n$app/navigation\n```\n\n========================================\n\nComments:\n- Thanks! Will that append the search param onto the URL, or completely overwrite them? And I'll definitely look into Prisma on the +page.server.js files! That sounds useful :D\n- Overwrite them, so you might need to write a little utility function that generates urls based on the current searchParams. (Readable from the $page.url store)\n- Gotcha! Could it be worth storing them in a writable store, or is that overkill when I could simply parse the current url and modify it accordingly? (More of an opiniated question, I know, but just curious on your thoughts)","metadata":{"transformedAt":"2026-08-18T18:33:40.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":48,"estimatedTokens":484}}727{"id":"stack-77099074","source":"stackoverflow","questionId":77099074,"title":"Layering toast alerts above dialog modal","tags":["html","css","modal-dialog","svelte","toast"],"text":"Title: Layering toast alerts above dialog modal\nTags: html, css, modal-dialog, svelte, toast\nSource: Stack Overflow\n\nQuestion:\nWhen combining a DaisyUI modal (a TailwindCSS UI library) with a toast alert library, I can't seem to find any CSS that'll allow my global toast alerts to appear above the modal dialog (while just experimenting via the browser's DevTools).\n\nI've tried:\n\n- Various variations of `z-index` and `position` options for the components and their parents based on this answer and the MDN article on stacking context.\n\n- Also changing the ordering and placement of the components and their parents in my larger app (while still keeping my alerting mechanism in a \"global\" location), but I found the same problem in the minimal example below.\n\n- I also found I could investigate with Chrome's DevTool's \"Layers\" tool (and Edge's 3D View), but it didn't seem to give me any clear reasoning for which layers are above the others beyond saying that it \"Overlaps other composited content\".\n\nThe only thing I found that *did work*, was if I change the location of the dialog in the live webpage by using drag & drop in the DevTools Inspector. That immediately moves all the toast alerts above the dialog regardless of where I move the dialog, but I don't know how to make use of that.\n\nHere's a minimal reproducible example:\n\n\r\n\r\n\n```\n\n \n \n Layer test\n \n \n \n \n\nopen modal\n\n \n \n\n### Hello!\n\n Press ESC key or click the button below to close\n\n Trigger alert!\n \n \n Close\n \n \n \n\n const toastApp = new SvelteToast({\n target: document.body,\n props: {\n options: {\n reversed: true,\n intro: { y: 192 },\n }\n }\n })\n\n /* Style to put alerts in bottom middle. */\n :root {\n --toastContainerTop: auto;\n --toastContainerRight: auto;\n --toastContainerBottom: 1rem;\n --toastContainerLeft: calc(50vw - 8rem);\n }\n\n```\n\n========================================\n\nCode:\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <title>Layer test</title>\n <link href=\"https://cdn.jsdelivr.net/npm/daisyui@3.7.3/dist/full.css\" rel=\"stylesheet\" type=\"text/css\" />\n <script src=\"https://cdn.tailwindcss.com\"></script> \n <!-- Load `toast` and `SvelteToast` into global scope -->\n <script src=\"https://cdn.jsdelivr.net/npm/@zerodevx/svelte-toast@0.9.5\"></script>\n</head>\n\n<body>\n\n<button class=\"btn\" onclick=\"my_modal_1.showModal()\">open modal</button>\n<dialog id=\"my_modal_1\" class=\"modal\">\n <div class=\"modal-box\">\n <h3 class=\"font-bold text-lg\">Hello!</h3>\n <p class=\"py-4\">Press ESC key or click the button below to close</p>\n <button class=\"btn btn-primary\" onclick=\"toast.push('Alert!', { initial: 0 })\">Trigger alert!</button>\n <div class=\"modal-action\">\n <form method=\"dialog\">\n <button class=\"btn\">Close</button>\n </form>\n </div>\n </div>\n</dialog>\n\n<script>\n const toastApp = new SvelteToast({\n target: document.body,\n props: {\n options: {\n reversed: true,\n intro: { y: 192 },\n }\n }\n })\n</script>\n\n<style>\n /* Style to put alerts in bottom middle. */\n :root {\n --toastContainerTop: auto;\n --toastContainerRight: auto;\n --toastContainerBottom: 1rem;\n --toastContainerLeft: calc(50vw - 8rem);\n }\n</style>\n</body>\n\n</html>\n```\n\n```text\nz-index\n```\n\n```text\nposition\n```\n\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <title>Layer test</title>\n <link href=\"https://cdn.jsdelivr.net/npm/daisyui@3.7.3/dist/full.css\" rel=\"stylesheet\" type=\"text/css\" />\n <script src=\"https://cdn.tailwindcss.com\"></script> \n <!-- Load `toast` and `SvelteToast` into global scope -->\n <script src=\"https://cdn.jsdelivr.net/npm/@zerodevx/svelte-toast@0.9.5\"></script>\n</head>\n\n<body>\n\n<button class=\"btn\" onclick=\"my_modal_1.showModal()\">open modal</button>\n<dialog id=\"my_modal_1\" class=\"modal\">\n <div class=\"modal-box\">\n <h3 class=\"font-bold text-lg\">Hello!</h3>\n <p class=\"py-4\">Press ESC key or click the button below to close</p>\n <button class=\"btn btn-primary\" onclick=\"toast.push('Alert!', { initial: 0 })\">Trigger alert!</button>\n <div class=\"modal-action\">\n <form method=\"dialog\">\n <button class=\"btn\">Close</button>\n </form>\n </div>\n </div>\n</dialog>\n\n<script>\n const dialog = document.getElementById(\"my_modal_1\");\n const toastProps = {\n options: {\n reversed: true,\n intro: { y: 192 },\n }\n };\n /*\n Attach to 2 different areas: one for global alerts and the\n other for alerts that happen while the dialog is showing.\n */\n const toastApp = new SvelteToast({\n target: document.body,\n props: toastProps\n });\n const toastDialog = new SvelteToast({\n target: dialog,\n props: toastProps\n });\n</script>\n\n<style>\n /* Style to put alerts in bottom middle. */\n :root {\n --toastContainerTop: auto;\n --toastContainerRight: auto;\n --toastContainerBottom: 1rem;\n --toastContainerLeft: calc(50vw - 8rem);\n }\n</style>\n</body>\n\n</html>\n```\n\n========================================\n\nComments:\n- What are the implications of instantiating two s. I have my original main one in +layout.svelte and now a new one within a Dialog. Is there a way to assign the new one an id and/or guarantee it is destroyed when the Dialog is closed?","metadata":{"transformedAt":"2026-08-18T18:33:40.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":206,"estimatedTokens":1369}}728{"id":"stack-71325247","source":"stackoverflow","questionId":71325247,"title":"Can't figure our how to remove padding from imported component","tags":["css","svelte","sveltekit"],"text":"Title: Can't figure our how to remove padding from imported component\nTags: css, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nSo I'm using the smui-accordion component and I just can't figure out how to remove it's padding!\nI've tried putting everywhere zero padding but to no avail...\nhttps://i.sstatic.net/i5foa.png\n\n```\n\n \n \n\n### Reviews ({reviews_list.length})\n\n \n \n \n expand_less\n expand_more\n \n \n \n {#each reviews_list as review, i}\n \n {/each}\n \n\n```\n\n========================================\n\nTop Answer:\nHave you tried to use \"!important\" css statement?\n\n```\nstyle=\"padding: 0 !important\"\n```\n\n========================================\n\nCode:\n```text\n<Accordion style=\"padding: 0\">\n<Panel style=\"padding: 0\" bind:open={reviewAccordion} variant=\"unelevated\">\n <Header style=\"padding: 0\">\n <h3 style=\"padding: 0\"class=\"mva\">Reviews ({reviews_list.length})</h3>\n <div style=\"padding: 0\" class=\"flex1\"></div>\n <div class=\"mva\" style=\"padding: 0; height: 20px;\"><StarRating rating={rating} config={star_config}/></div>\n <IconButton style=\"padding: 0\" slot=\"icon\" toggle pressed={reviewAccordion}>\n <Icon class=\"material-icons\" on>expand_less</Icon>\n <Icon class=\"material-icons\">expand_more</Icon>\n </IconButton>\n </Header>\n <Content style=\"padding: 0\">\n {#each reviews_list as review, i}\n <div style=\"padding: 0\"><Review review={review}/></div>\n {/each}\n </Content>\n</Panel>\n```\n\n```html\n<Accordion class=\"myclass\" />\n```\n\n```text\nstyle=\"padding: 0 !important\"\n```\n\n```text\n.smui-accordion .smui-accordion__panel > .smui-accordion__header .smui-accordion__header__title {padding: 0}\n```\n\n========================================\n\nComments:\n- Check out this answer for how to target components. The issue is that `style` is actually being read by Svelte as a prop and not HTML.\n- thanks, but that didn't work\n- that's what worked for me! * :global(.bra .smui-accordion__header__title) { padding: 0 !important; }","metadata":{"transformedAt":"2026-08-18T18:33:40.712Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":81,"estimatedTokens":505}}729{"id":"stack-76915395","source":"stackoverflow","questionId":76915395,"title":"What is the second 'invalidate' argument to Readable.subscribe?","tags":["svelte"],"text":"Title: What is the second 'invalidate' argument to Readable.subscribe?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nThe docs only say: `invalidate cleanup callback`. Not very informative.\nhttps://svelte.dev/docs/svelte-store#types-readable\n\nAnyone got a little bit more info on this? Maybe a tiny example?\n\n========================================\n\nCode:\n```text\ninvalidate cleanup callback\n```\n\n```js\nit('prevents glitches', () => {\n const lastname = writable('Jekyll');\n const firstname = derive(lastname, n => n === 'Jekyll' ? 'Henry' : 'Edward');\n\n const fullname = derive([firstname, lastname], names => names.join(' '));\n\n const values = [];\n\n const unsubscribe = fullname.subscribe(value => {\n values.push(value);\n });\n\n lastname.set('Hyde');\n\n assert.deepEqual(values, [\n 'Henry Jekyll',\n 'Edward Hyde'\n ]);\n\n unsubscribe();\n});\n```\n\n```js\n[\n 'Henry Jekyll',\n 'Edward Jekyll', // <- Should not be here\n 'Edward Hyde',\n]\n```\n\n```text\nderived\n```\n\n```text\npending\n```\n\n```text\n3.0.0-alpha6\n```\n\n```text\n3.0.0-alpha7\n```\n\n```text\nvalues\n```\n\n========================================\n\nComments:\n- That's some high quality sleuthing you did just there. I found the place invalidate gets called because of it: github.com/sveltejs/svelte/blob/master/packages/svelte/src/… It's in the `writable.set` implementation. It calls a subscribers invalidate fn just before calling the subscriber with the new value.\n- First thing I looked at, unfortunately did not explain anything 😅\n- And this is the invalidate fn in the derived implementation: github.com/sveltejs/svelte/blob/master/packages/svelte/src/… I understand the test case, but the code implementation is impenetrable to me. But yeah I concur that invalidate seems like an internal implementation detail. I would love it if the documentation would tell me that. Or just not tell me about the existence of invalidate at all.","metadata":{"transformedAt":"2026-08-18T18:33:40.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":75,"estimatedTokens":487}}730{"id":"stack-69521559","source":"stackoverflow","questionId":69521559,"title":"Can the Astro Static Site Generator framework be used to create pages on the fly from data fetched from an API?","tags":["dynamic","content-management-system","svelte","static-site-generation","astrojs"],"text":"Title: Can the Astro Static Site Generator framework be used to create pages on the fly from data fetched from an API?\nTags: dynamic, content-management-system, svelte, static-site-generation, astrojs\nSource: Stack Overflow\n\nQuestion:\nA project in our company was built using Astro and Svelte. In this project, API calls have to be made to a CMS to create blog posts dynamically. I would like a way for my clients to write blog posts, update the CMS(GraphCMS) and see that the website has created a new post.\n\n========================================\n\nTop Answer:\nIf your company use Svelte, take a look at Sveltekit. See:\n\nhttps://docs.astro.build/comparing-astro-vs-other-tools/#sveltekit-vs-astro\n\nhttps://kit.svelte.dev/\n\nhttps://svelteland.github.io/svelte-kit-blog-demo/create-your-blog/\n\n========================================\n\nComments:\n- The creation of the post in the CMS would need to trigger a build on your host. With a static site generator this will never be instant or dynamic since the build process needs to run and be published by the host. If you want it to be truly dynamic you lose out on the SEO goodies SSGs get you and load speed increases for users, I usually do some client education to help them understand the post publishing delay. But if you really want dynamic post creation from the API call, Astro is the wrong tool for you.\n- Hi @JHeth thank you so much for commenting, I was having a really hard time with this framework. I feel so relieved after getting your viewpoint on this. So, in essence, Astro isn't really the best tool for a website with content that is dynamically changing. I'll try and convey this to my team as well.\n- Clients always think they need dynamically changing content but most only add content once a week so SSG may be the actual best thing for the client (better SEO, faster load times). The difficulty is educating them on the benefits of what they need vs the convenience they want in post creation/editing. This talk should happen with your team first, then pitched to the client as an option to help their business. Here's a good article on the different hosting approaches dev.to/matfrana/…\n- Thanks! Read the article and it explained the trade-offs for each paradigm quite effectively.\n- @JHeth do Astro supports incremental building? like if we want to add only one page, so there is no need to rebuild all the project. Is Astro capable to do such thing?\n- Yup, seen that but my hands are tied at this moment.\n- Hi! Thank you so much for answering. I actually figured this out after some time with the framework and GraphCMS. Adding client-side JS defeats the purpose of Astro but I still feel like your answer should be marked as correct since you gave more info.\n- Sorry it came a bit too late for your particular situation @Aryan3212, hope it helps someone else.","metadata":{"transformedAt":"2026-08-18T18:33:40.712Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":29,"estimatedTokens":711}}731{"id":"stack-75434947","source":"stackoverflow","questionId":75434947,"title":"How to add a left panel right next to a component using carbon components?","tags":["javascript","reactjs","svelte","carbon-components","carbon-components-svelte"],"text":"Title: How to add a left panel right next to a component using carbon components?\nTags: javascript, reactjs, svelte, carbon-components, carbon-components-svelte\nSource: Stack Overflow\n\nQuestion:\nI have a Sveltekit app and for my home route I want to display a table based on carbon components. I want to filter the data displayed in the table by adding a left panel right next to the table. I'm basically looking for their example\n\nhttps://i.sstatic.net/JjwZ8.png\n\nbut I don't know how they solved it. I know the navbar has a navigation panel but this panel has nothing to do with the navigation and should only appear for my home route.\n\nI tried to modify the official codebox sample to show what I have so far ( please have mercy, I've never used React before ). I hope the technology ( React / Vue / Svelte ) shouldn't matter.\n\n```\nimport React from \"react\";\nimport { render } from \"react-dom\";\nimport {\n Header,\n HeaderName,\n HeaderNavigation,\n HeaderMenuItem,\n Theme,\n Content,\n DataTable,\n TableContainer,\n Table,\n TableHead,\n TableRow,\n TableHeader,\n TableBody,\n TableCell\n} from \"@carbon/react\";\n\nconst App = () => (\n \n \n Nav goes here\n \n Link 1\n \n \n \n {/* TODO add sidebar for filters right next to the table */}\n\n \n {({ rows, headers, getHeaderProps, getTableProps }) => (\n \n \n \n \n {headers.map((header) => (\n \n {header.header}\n \n ))}\n \n \n \n {rows.map((row) => (\n \n {row.cells.map((cell) => (\n {cell.value}\n ))}\n \n ))}\n \n \n \n )}\n \n \n \n);\n\nrender(, document.getElementById(\"root\"));\n```\n\nI thought about using a Grid component but then both columns get the same width and the grid comes with **a big** horizontal margin.\n\nIf the grid is the right component for the job, how can I tell the first column ( filters ) to use the width it needs and the second column ( table ) fills the rest?\n\nDo you have any ideas how to setup a left panel?\n\n========================================\n\nCode:\n```text\nimport React from \"react\";\nimport { render } from \"react-dom\";\nimport {\n Header,\n HeaderName,\n HeaderNavigation,\n HeaderMenuItem,\n Theme,\n Content,\n DataTable,\n TableContainer,\n Table,\n TableHead,\n TableRow,\n TableHeader,\n TableBody,\n TableCell\n} from \"@carbon/react\";\n\nconst App = () => (\n <Theme theme=\"g100\">\n <Header>\n <HeaderName>Nav goes here</HeaderName>\n <HeaderNavigation>\n <HeaderMenuItem>Link 1</HeaderMenuItem>\n </HeaderNavigation>\n </Header>\n <Content>\n {/* TODO add sidebar for filters right next to the table */}\n\n <DataTable\n rows={[\n {\n id: 1,\n name: \"First element\"\n }\n ]}\n headers={[\n {\n key: \"name\",\n header: \"Name\"\n }\n ]}\n >\n {({ rows, headers, getHeaderProps, getTableProps }) => (\n <TableContainer title=\"DataTable\">\n <Table {...getTableProps()}>\n <TableHead>\n <TableRow>\n {headers.map((header) => (\n <TableHeader {...getHeaderProps({ header })}>\n {header.header}\n </TableHeader>\n ))}\n </TableRow>\n </TableHead>\n <TableBody>\n {rows.map((row) => (\n <TableRow key={row.id}>\n {row.cells.map((cell) => (\n <TableCell key={cell.id}>{cell.value}</TableCell>\n ))}\n </TableRow>\n ))}\n </TableBody>\n </Table>\n </TableContainer>\n )}\n </DataTable>\n </Content>\n </Theme>\n);\n\nrender(<App />, document.getElementById(\"root\"));\n```\n\n```html\n<Content>\n <Grid fullWidth noGutter>\n <Row>\n <Column sm={4} md={2}>\n <div class=\"panel\">\n Left Panel\n </div>\n </Column>\n <Column>Content</Column>\n </Row>\n </Grid>\n</Content>\n```\n\n```text\nfullWidth\n```\n\n```text\nnoGutter\n```\n\n```text\nnoGutterLeft\n```\n\n```text\nnoGutterRight\n```\n\n```text\nGrid\n```\n\n```text\nRow\n```\n\n```text\nColumn\n```\n\n```text\nsm={4}\n```\n\n```text\nmd={2}\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":213,"estimatedTokens":1039}}732{"id":"stack-70365170","source":"stackoverflow","questionId":70365170,"title":"Axios get request can't convert undefined to object","tags":["javascript","axios","svelte"],"text":"Title: Axios get request can't convert undefined to object\nTags: javascript, axios, svelte\nSource: Stack Overflow\n\nQuestion:\nI am trying to make a get request in my js/svelte application.\nThe REST-API works perfectly fine in the browser or when testing with postman.\n\nWhen I click the Go button on the website then the following error ocours in the console from the inspection tool.\n\nUncaught TypeError: can't convert undefined to object\n\nmergeConfig mergeConfig.js:92\nrequest Axios.js:39\nmethod Axios.js:129\nwrap bind.js:9\nlogin Login.svelte:11\nlisten index.mjs:412\nlisten_dev index.mjs:1961\nmount bundle.js:3413\nmount_component index.mjs:1745\nupdate bundle.js:765\nupdate bundle.js:931\nupdate index.mjs:1075\nflush index.mjs:1042\npromise callback*schedule_update index.mjs:1000\nmake_dirty index.mjs:1777\nctx index.mjs:1815\nunsubscribeLoc bundle.js:1442\nsubscribe index.mjs:50\ninstance$3 Router.svelte:493\ninit index.mjs:1809\nRouter bundle.js:1583\ncreate_fragment bundle.js:3583\ninit index.mjs:1824\nApp bundle.js:3655\napp main.js:3\n bundle.js:3675\n\nAnd this is the code.\n\n```\n\n import {replace} from 'svelte-spa-router'\n import {LoginDto} from \"../scripts/data_transfer_objects/LoginDto\";\n import axios from \"axios\";\n\n let loginTemplate = new LoginDto();\n\n function login(){\n console.log(loginTemplate.password);\n axios.get(\"http://localhost:5000/login\", {\n auth: {\n username: \"test\",\n password: \"1234\"\n }\n });\n replace(\"#/activities\");\n }\n\n \n Go\n\n```\n\nDoes someone have a idea what the problem is?\n\nThanks in advance!\n\n**EDIT**\n\nI tryied it with a even simpler example.\n\n```\n\n import axios from \"axios\";\n\n axios.get(\"localhost:5000/activities\");\n\n```\n\nThis does not work either.\nI prduces the same error as described above.\n\n========================================\n\nTop Answer:\nTry to log what the server return. You might know what happened.\n\n```\naxios.get(\"http://localhost:5000/login\", {\n auth: {\n username: \"test\",\n password: \"1234\"\n }\n}).then(response => console.log(response));\n```\n\n========================================\n\nCode:\n```text\n<script>\n import {replace} from 'svelte-spa-router'\n import {LoginDto} from \"../scripts/data_transfer_objects/LoginDto\";\n import axios from \"axios\";\n\n let loginTemplate = new LoginDto();\n\n function login(){\n console.log(loginTemplate.password);\n axios.get(\"http://localhost:5000/login\", {\n auth: {\n username: \"test\",\n password: \"1234\"\n }\n });\n replace(\"#/activities\");\n }\n</script>\n\n<div>\n <input type=\"password\" placeholder=\"Password\" bind:value={loginTemplate.password}>\n <button on:click={login}>Go</button>\n</div>\n```\n\n```text\n<script>\n import axios from \"axios\";\n\n axios.get(\"localhost:5000/activities\");\n</script>\n```\n\n```text\n@rollup/plugin-commonjs\n```\n\n```text\n17.0.0\n```\n\n```text\n21.0.1\n```\n\n```js\naxios.get(\"http://localhost:5000/login\", {\n auth: {\n username: \"test\",\n password: \"1234\"\n }\n}).then(response => console.log(response));\n```\n\n========================================\n\nComments:\n- This does not work either. I am pretty sure its oke to pass a auth: {} with a get request. It works when using postman.\n- What version of axios?\n- \"axios\": \"^0.24.0\",\n- The request doesn't get to the server, the error ocours before hands. But i have tryied it and i still get the same error.","metadata":{"transformedAt":"2026-08-18T18:33:40.712Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":163,"estimatedTokens":845}}733{"id":"stack-70468246","source":"stackoverflow","questionId":70468246,"title":"Async each in Svelte","tags":["javascript","svelte","svelte-3"],"text":"Title: Async each in Svelte\nTags: javascript, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI tried to use async `#each` loop in svelte and found it it runs synchronously no matter what, using async await function like this:\n\n```\n{#each items as item (item.id)}\n {#await render(item) then source}\n \n {:catch}\n error\n\n {/await}\n{/each}\n```\n\nand found it there is no way to use async component in svelte cause onmount can't be used asynchronously like this:\n\n```\n{#each items as item (item.id)}\n \n{/each}\n```\n\nis there any workaround this problem?\n\n========================================\n\nCode:\n```text\n{#each items as item (item.id)}\n {#await render(item) then source}\n <Canvas {source} />\n {:catch}\n <p>error</p>\n {/await}\n{/each}\n```\n\n```text\n{#each items as item (item.id)}\n <Canvas {item} />\n{/each}\n```\n\n```text\n#each\n```\n\n```text\n// App.svelte\n<svelte:options immutable={false} />\n\n<script>\n import Item from \"./Item.svelte\";\n import { onMount } from \"svelte\";\n\n let array;\n\n const sleep = async (ms) => await new Promise((r) => setTimeout(r, ms));\n\n async function render(id) {\n await sleep(800);\n array = array.map((item) => {\n if (item.id === id) {\n return {\n ...item,\n render: item.render + 1,\n };\n }\n return item;\n });\n }\n\n onMount(() => {\n async function init() {\n array = await Promise.all(\n [...Array.from({ length: 5 }).keys()].map((i) =>\n Promise.resolve({\n id: i + 1,\n name: `item_${i + 1}`,\n render: 0,\n })\n )\n );\n }\n\n init();\n\n return () => console.log(\"destroyed\");\n });\n</script>\n\n{#if array && array.length}\n {#each array as item (item.id)}\n <Item {item} on:click={() => render(item.id)} />\n {/each}\n{/if}\n```\n\n```text\n// ./Item.svelte\n<svelte:options immutable={true} />\n\n<script>\n import { afterUpdate } from \"svelte\";\n \n export let item;\n</script>\n\n<div>\n <p>\n {item.name} [render: {item.render}]\n </p>\n <button on:click>render</button>\n</div>\n```\n\n```text\n// App.svelte\n<svelte:options immutable={false} />\n\n<script>\n import Item from \"./Item.svelte\";\n import { onMount } from \"svelte\";\n\n let array;\n\n async function render(id) {\n array = await Promise.all(\n array.map(async (promiseItem) => {\n if (promiseItem.id === id) {\n const _item = await promiseItem.item;\n return {\n id: promiseItem.id,\n item: new Promise((r) =>\n setTimeout(() => r({ ..._item, render: _item.render + 1,}), 800)\n ),\n };\n }\n return promiseItem;\n })\n );\n }\n\n onMount(() => {\n async function init() {\n array = [...Array.from({ length: 5 }).keys()].map((i) => ({\n id: i,\n item: Promise.resolve({\n id: i + 1,\n name: `item_${i + 1}`,\n render: 0,\n }),\n }));\n }\n\n init();\n\n return () => console.log(\"destroyed\");\n });\n</script>\n\n{#if array && array.length}\n {#each array as { id, item: promise } (id)}\n {#await promise}\n <p>...rendering</p>\n {:then item}\n <Item {item} on:click={() => render(item.id)} />\n {/await}\n {/each}\n{/if}\n```\n\n```text\n<script>\n import { onMount } from \"svelte\";\n\n let promise;\n\n async function render(i) {\n return {\n id: i + 1,\n name: `item_${i + 1}`,\n };\n }\n\n onMount(() => {\n const array = [...Array.from({length: 5}).keys()];\n promise = Promise.all(array.map((i) => render(i)));\n\n return () => console.log(\"destroyed\");\n });\n</script>\n\n{#await promise}\n <p>...rendering</p>\n{:then array}\n {#if array && array.length}\n {#each array as item (item.id)}\n <p>\n {item.name}\n </p>\n {/each}\n {/if}\n{:catch error}\n <p>oh dear.</p>\n{/await}\n```\n\n```text\nonMount\n```\n\n```text\nimmutable\n```\n\n```text\n{#await}\n```\n\n```text\nItem\n```\n\n```text\nonMount\n```\n\n```text\n{#await}\n```\n\n```text\nPromise.all\n```\n\n========================================\n\nComments:\n- I already tried a similar approach using stores and i don’t wanna lose reactivity upon updating the array hence it will reload all of the items/images again every time hence currently it only reloads the updated item only but my problem is it doesn’t load them ordered initially.\n- It Works! .. not what i exactly had in mind cause now it preloads all the images but it kept the order, i'll try to figure out away to fix that later.\n- Is there any way to render them one by one in order not with promise all! just to show the rendered first and move to the next one?\n- Nevermind i finally did it, thank you :)","metadata":{"transformedAt":"2026-08-18T18:33:40.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":247,"estimatedTokens":1292}}734{"id":"stack-72192733","source":"stackoverflow","questionId":72192733,"title":"Best way to move data between two pages in SvelteKit?","tags":["svelte","sveltekit"],"text":"Title: Best way to move data between two pages in SvelteKit?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\ntl;dr - best practice for moving data between two pages in Svelte?\n\nI have two pages, let's say First.svelte and Second.svelte.\n\nIn a traditional framework, I might create a form on First.svelte and then post it to Second.svelte. I can bind hidden input values on the First.svelte form and then post it to Second.svelte. I have found a lot of great information on how to manage the form locally to the page itself, but not on how to move data between pages.\n\nI'm having a surprisingly hard time figuring out how the best way to read form data in a SvelteKit page. It looks like I could use get/setContext instead, or perhaps there is another option?\n\nIt also appears that form submission is often handled via an endpoint instead of just in the script tag at the top of the receiving page. Is that considered a SvelteKit best practice, or...?\n\nI found this article and it made it look like the endpoint was more or less required. https://codechips.me/sveltekit-ssr-forms/\n\nIs there a recommended/best practice/officially supported Svelte/SvelteKit solution for moving data between pages?\n\n========================================\n\nComments:\n- Keep in mind, often form submissions are \"handled\" in endpoints because either you are using a \"traditional\" form submit and are getting data from formData or the submission needs to be entered into a database, external api, or something else that can't be exposed on the client side due to secrets or similar. \"I have two pages, let's say First.svelte and Second.svelte.\". Do you mean First has its own submission and Second has a different submission? It it something like a wizard multi step/page form?\n- Keep in mind, you can always just create a svelte store and access it from different pages to store data between pages. Maybe you could use something like stackblitz to create an example of what you are trying to accomplish.\n- I don't quite understand the question. Do you mean you want to persist data across pages?\n- tl;dr - yes, the answer is to use page endpoints (formerly called shadow endpoints). Yes, I have a form on First.svelte that is (more or less) like the first step in a multi submit process - fill a bit of data on First.svelte, which then posts to Second.svelte to complete. It took some fiddling to figure out how to a) do the post/submits, how the page endpoints inject values, and how to do error handling. Now that it's working it's actually very slick but the docs are virtually non-existent. Hopefully will have a nice writeup to explain in the next few days.","metadata":{"transformedAt":"2026-08-18T18:33:40.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":26,"estimatedTokens":663}}735{"id":"stack-71557580","source":"stackoverflow","questionId":71557580,"title":"Retrieve value from IndexedDB using Dexie and Svelte","tags":["javascript","promise","svelte","indexeddb","dexie"],"text":"Title: Retrieve value from IndexedDB using Dexie and Svelte\nTags: javascript, promise, svelte, indexeddb, dexie\nSource: Stack Overflow\n\nQuestion:\nI don't understand how I can get a value from IndexedDB using Dexie. Database is all good in 'application' tab in inspect tool. Total newbie, so please be understanding.\n\nMy db.js\n\n```\nimport Dexie from \"dexie\";\n\nexport const db = new Dexie(\"myDatabase\");\ndb.version(2).stores({\n history: \"++id, daterange, days\",\n storage: \"id, name, value\"\n});\n\ndb.on(\"populate\", function () {\n db.storage.add({\n id: 0,\n name: \"total\",\n value: 20\n });\n db.storage.add({\n id: 1,\n name: \"left\",\n value: 20\n });\n});\ndb.open();\n```\n\nApp.svelte\n\n```\n\n import Counter from \"./src/Counter.svelte\";\n import New from \"./src/New.svelte\";\n import History from \"./src/History.svelte\";\n import { liveQuery } from \"dexie\";\n import { db } from \"./src/db\";\n\n let total = liveQuery(() =>\n db.storage\n .where(\"name\")\n .equals(\"total\")\n .value.then(function(a) {\n totals = a;\n })\n );\n\n let left = 25;\n\n main {\n width: 100%;\n }\n\n \n \n \n\n```\n\nWhatever I try, object with `daysMax={total}` outputs `undefined`, `[object Object]` or something like `[Dexie object Object]`. I just want to get `20` from db, as seen in db.js:\n\n```\ndb.on(\"populate\", function () {\n db.storage.add({\n id: 0,\n name: \"total\",\n value: 20\n });\n```\n\n(This all works and is visible in indexedDb)\nI also tried `daysMax={$total}`\n\nCodeSandbox\n\n========================================\n\nCode:\n```text\nimport Dexie from \"dexie\";\n\nexport const db = new Dexie(\"myDatabase\");\ndb.version(2).stores({\n history: \"++id, daterange, days\",\n storage: \"id, name, value\"\n});\n\ndb.on(\"populate\", function () {\n db.storage.add({\n id: 0,\n name: \"total\",\n value: 20\n });\n db.storage.add({\n id: 1,\n name: \"left\",\n value: 20\n });\n});\ndb.open();\n```\n\n```text\n<script>\n import Counter from \"./src/Counter.svelte\";\n import New from \"./src/New.svelte\";\n import History from \"./src/History.svelte\";\n import { liveQuery } from \"dexie\";\n import { db } from \"./src/db\";\n\n let total = liveQuery(() =>\n db.storage\n .where(\"name\")\n .equals(\"total\")\n .value.then(function(a) {\n totals = a;\n })\n );\n\n let left = 25;\n</script>\n\n<style>\n main {\n width: 100%;\n }\n</style>\n\n<main>\n <Counter daysLeft={left} daysMax={total}/>\n <New />\n <History />\n</main>\n```\n\n```text\ndb.on(\"populate\", function () {\n db.storage.add({\n id: 0,\n name: \"total\",\n value: 20\n });\n```\n\n```text\ndaysMax={total}\n```\n\n```text\nundefined\n```\n\n```text\n[object Object]\n```\n\n```text\n[Dexie object Object]\n```\n\n```text\n20\n```\n\n```text\ndaysMax={$total}\n```\n\n```js\nlet total = liveQuery(() =>\n db.storage\n .where(\"name\")\n .equals(\"total\")\n .value.then(function(a) {\n totals = a;\n })\n );\n```\n\n```js\nlet total = liveQuery(() =>\n db.storage\n .where(\"name\")\n .equals(\"total\")\n .first()\n );\n```\n\n```js\n<script>\n // ...your existing script code with updated query...\n $: daysMax = $total?.value // undefined until the query resolves, actual value once the query has resolved\n</script>\n\n<main>\n {#if daysMax !== undefined}\n <Counter daysLeft={left} {daysMax} />\n {/if}\n <New />\n <History />\n</main>\n```\n\n```text\ndb.storage.where(\"name\").equals(\"total\")\n```\n\n```text\n.value\n```\n\n```text\nliveQuery\n```\n\n```text\ntotal\n```\n\n```text\n$\n```\n\n```text\n$total\n```\n\n```text\n$total\n```\n\n```text\nvalue\n```\n\n```text\n$total\n```\n\n```text\nundefined\n```\n\n========================================\n\nComments:\n- That's super helpful! I was confused for three days, I'm thankful for such a detailed explanation. There's not so many sources covering Dexie and even less in Svelte.\n- Glad I could help! I updated the last paragraph a little bit, for what I believe is a better way to access `.value`. Also fixed the CodeSandbox, as I apparently had forgotten to save my changes xD Sorry for that.","metadata":{"transformedAt":"2026-08-18T18:33:40.713Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":253,"estimatedTokens":984}}736{"id":"stack-72050095","source":"stackoverflow","questionId":72050095,"title":"Dynamically get/set store value in svelte from input","tags":["svelte"],"text":"Title: Dynamically get/set store value in svelte from input\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI want to do this, **TLDR**:\n\n```\n/** This is the Input.svelte */\n\n export let identifier;\n\n import * as state from \"./store\"\n\n```\n\nLonger story, I've defined a load of input fields in a list of objects, which I then iterate over and put on the `` component... but I need to save these values in a store to then continuously update a \"Preview panel\".\n\n========================================\n\nCode:\n```js\n/** This is the Input.svelte */\n\n<script>\n export let identifier;\n\n import * as state from \"./store\"\n</script>\n\n<input bind:value={$state[identifier]} />\n```\n\n```text\n<Input field />\n```\n\n```js\nimport { writable } from 'svelte/store';\nexport const state = writable({});\n```\n\n```html\n<script>\n import { state } from \"./store\";\n export let identifier;\n</script>\n<input bind:value={$state[identifier]} />\n```\n\n```html\n<script>\n import Input from './Input.svelte';\n import { state } from './store';\n</script>\n\n<Input identifier=\"value1\"/>\n<Input identifier=\"value2\"/>\n\n<p>Value1: {$state.value1}</p>\n<p>Value1: {$state.value2}</p>\n```\n\n```text\n*\n```\n\n```text\nstore.js\n```\n\n```text\nInput.svelte\n```\n\n```text\nidentifier\n```\n\n```text\neach\n```\n\n```text\neach\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.713Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":86,"estimatedTokens":319}}737{"id":"stack-64876542","source":"stackoverflow","questionId":64876542,"title":"rendering difference between Firefox and Chrome","tags":["html","css","svelte"],"text":"Title: rendering difference between Firefox and Chrome\nTags: html, css, svelte\nSource: Stack Overflow\n\nQuestion:\nI am working on a guitar chord app and the problem is Firefox is not rendering paragraphs as expected.\n\nFirefox is render `p` tags with extra space on both bottom and top.\nThere is no padding, nor margin. Firefox says there is just \"gap\" between the elements. I am super surprised...https://i.sstatic.net/TIiDu.png\nPlease note that I have highlighted two sibling `p` elements, and the there is nothing between them.\nHere is my structure:\n\n\r\n\r\n\n```\np {\n margin: 0; padding: 0; \n }\n```\n\n\r\n\n```\n\n (Song metadata, you can see example in the screenshot)\n chords\n\n a line of lyrics\n\n chords\n\n a line of lyrics\n\n chords\n\n a line of lyrics\n\n chords\n\n a line of lyrics\n\n chords\n\n a line of lyrics\n\n ...\n\n```\n\n\r\n\r\n\r\n\nExpected (from `Chrome`): https://i.sstatic.net/EbnUwl.png\n\n`Firefox`: https://i.sstatic.net/M2el6l.png\n\nFirefox screenshot, `p` element boundaries\nhttps://i.sstatic.net/0GxrCl.png\n\nI tried those:\n\n- Changing `margin`,`padding` of the both `pre` and `p` elements\n\n- Changing `display` css prop on both elements\n\n- Setting `p`'s style to `line-height: 0.6em` works, but it is not a solution.\n\n#EDIT 1: Forgot to add stylesheet. btw, there is no margin, nor padding. I added image to show boundary of `p` element.\n\n#EDIT 2: Added what I've tried\n\n========================================\n\nCode:\n```css\np {\n margin: 0; padding: 0; \n }\n```\n\n```html\n<pre>\n <section style=\"inline-block\">(Song metadata, you can see example in the screenshot)</section>\n <p>chords</p>\n <p>a line of lyrics</p>\n <p>chords</p>\n <p>a line of lyrics</p>\n <p>chords</p>\n <p>a line of lyrics</p>\n <p>chords</p>\n <p>a line of lyrics</p>\n <p>chords</p>\n <p>a line of lyrics</p>\n ...\n</pre>\n```\n\n```text\np\n```\n\n```text\np\n```\n\n```text\nChrome\n```\n\n```text\nFirefox\n```\n\n```text\np\n```\n\n```text\nmargin\n```\n\n```text\npadding\n```\n\n```text\npre\n```\n\n```text\np\n```\n\n```text\ndisplay\n```\n\n```text\np\n```\n\n```text\nline-height: 0.6em\n```\n\n```text\np\n```\n\n```text\np\n```\n\n```text\npre\n```\n\n```text\np\n```\n\n========================================\n\nComments:\n- Why not just explicitly set the padding/margin for `pre p` elements?\n- I have set both margin, padding to zero. I forgot to add `style`, now I edited the post and appended it. Ty\n- View this on your Browser Inspector and see if anything is overwriting your CSS declaration for the padding of the `` element\n- in between each you have a line-break, firefox treat your and that line-break as a block element , chrome doesn't . or white-space:pre will do the same\n- Because your code is inside a `` tag; the whitespace is also given a volume\n- best is probably to use white-space on the p tags and a monospace font .\n- I use monospace font actually. Making each `p`'s style to `white-space: pre` made it.","metadata":{"transformedAt":"2026-08-18T18:33:40.713Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":173,"estimatedTokens":720}}738{"id":"stack-65277169","source":"stackoverflow","questionId":65277169,"title":"SvelteKit dev server doesn't start","tags":["javascript","node.js","svelte"],"text":"Title: SvelteKit dev server doesn't start\nTags: javascript, node.js, svelte\nSource: Stack Overflow\n\nQuestion:\nI want to try out the new SvelteKit replacement for Sapper, but I'm not able to start a dev server.\n\nI ran:\n\n```\nnpm init svelte@next\nnpm install\nnpm run dev -- --open\n```\n\nError:\n\n```\n(node:16570) UnhandledPromiseRejectionWarning: .../Desktop/Programming/Web Development/Svelte/Demo-app/node_modules/@sveltejs/kit/dist/index4.js:262\n #map;\n ^\n\nSyntaxError: Invalid or unexpected token\n at Module._compile (internal/modules/cjs/loader.js:723:23)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)\n at Module.load (internal/modules/cjs/loader.js:653:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:593:12)\n at Function.Module._load (internal/modules/cjs/loader.js:585:3)\n at Module.require (internal/modules/cjs/loader.js:692:17)\n at require (internal/modules/cjs/helpers.js:25:18)\n at Object. (../Desktop/Programming/Web Development/Svelte/Demo-app/node_modules/@sveltejs/kit/dist/index.js:13:13)\n at Module._compile (internal/modules/cjs/loader.js:778:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)\n(node:16570) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)\n(node:16570) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\nI haven't touched the generated code.\n\nI know these kinds of errors pop when it's unable to open a new browser tab with the server started, but I have no idea how to fix it here.\n\n- Node Version: v10.19.0\n\n- OS: Ubuntu 20.04.1 LTS, 64-bit\n\n- Browser: Firefox 83.0 (64-bit)\n\n- Proxy: Burp Suite\n\n========================================\n\nTop Answer:\nI'm guessing you are trying to make a template and using the template syntax\n\n```\n{#map bla bla}\n```\n\nThen the error might just be that `map` is not supported and you might have to switch to #each\n\n```\n{#each expression as name}...{/each}\n```\n\n========================================\n\nCode:\n```text\nnpm init svelte@next\nnpm install\nnpm run dev -- --open\n```\n\n```text\n(node:16570) UnhandledPromiseRejectionWarning: .../Desktop/Programming/Web Development/Svelte/Demo-app/node_modules/@sveltejs/kit/dist/index4.js:262\n #map;\n ^\n\nSyntaxError: Invalid or unexpected token\n at Module._compile (internal/modules/cjs/loader.js:723:23)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)\n at Module.load (internal/modules/cjs/loader.js:653:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:593:12)\n at Function.Module._load (internal/modules/cjs/loader.js:585:3)\n at Module.require (internal/modules/cjs/loader.js:692:17)\n at require (internal/modules/cjs/helpers.js:25:18)\n at Object.<anonymous> (../Desktop/Programming/Web Development/Svelte/Demo-app/node_modules/@sveltejs/kit/dist/index.js:13:13)\n at Module._compile (internal/modules/cjs/loader.js:778:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)\n(node:16570) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)\n(node:16570) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\n```text\n#map\n```\n\n```text\nprivate class field\n```\n\n```text\n{#map bla bla}\n```\n\n```text\n{#each expression as name}...{/each}\n```\n\n```text\nmap\n```\n\n========================================\n\nComments:\n- The error is pointing towards node_modules, I haven't started coding yet.\n- it's true what you say. as a side note, we can check this looking at `package.json` for something like `\"engines\": {\"node\": \">= xxx\"}`. In my case xxx is `12.17.0`.","metadata":{"transformedAt":"2026-08-18T18:33:40.713Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":118,"estimatedTokens":1044}}739{"id":"stack-68785064","source":"stackoverflow","questionId":68785064,"title":"Svelte Won't Allow Me to Use an Exported Enum (TypeScript) in the Component Body","tags":["typescript","svelte","svelte-component"],"text":"Title: Svelte Won't Allow Me to Use an Exported Enum (TypeScript) in the Component Body\nTags: typescript, svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI have the following code...\n\n```\n\n import { TToken } from \"./global.d\";\n const value:TToken = TToken.X;\n\n{#if value == TToken.X}\n Hi There!\n{:else}\n I don't like you\n{/if}\n```\n\nAnd here's global.d.ts:\n\n```\n/// \nexport enum TToken {\n X = 'X',\n O = 'O',\n Blank = ' '\n}\n```\n\nWhen I run **npx svelte-check**, it finds no errors. But when I try to run svelte via **npm run dev**, I get the following:\n\n```\nrollup v2.56.2\nbundles src/main.ts → public\\build\\bundle.js...\n[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)\nsrc\\global.d.ts (2:7)\n1: /// \n2: export enum TToken {\n ^\n3: X = 'X',\n4: O = 'O',\nError: Unexpected token (Note that you need plugins to import files that are not JavaScript)\n at error (C:\\svelte-test\\node_modules\\rollup\\dist\\shared\\rollup.js:151:30)\n at Module.error (C:\\svelte-test\\node_modules\\rollup\\dist\\shared\\rollup.js:10059:16)\n at Module.tryParse (C:\\svelte-test\\node_modules\\rollup\\dist\\shared\\rollup.js:10462:25)\n at Module.setSource (C:\\svelte-test\\node_modules\\rollup\\dist\\shared\\rollup.js:10365:24)\n at ModuleLoader.addModuleSource (C:\\svelte-test\\node_modules\\rollup\\dist\\shared\\rollup.js:19708:20)\n at ModuleLoader.fetchModule (C:\\svelte-test\\node_modules\\rollup\\dist\\shared\\rollup.js:19764:9)\n at async Promise.all (index 1)\n at ModuleLoader.fetchStaticDependencies (C:\\svelte-test\\node_modules\\rollup\\dist\\shared\\rollup.js:19790:34)\n at async Promise.all (index 0)\n at ModuleLoader.fetchModule (C:\\svelte-test\\node_modules\\rollup\\dist\\shared\\rollup.js:19766:9)\n```\n\nI googled and found people reporting similar issues, but none of the resolutions I found applied to my case. For instance, one person said the issue was that plugins and watch needed to be outside output in the rollup, but that was already the case for me.\n\nRemoving the export will of course cause **svelte-check** to fail.\n\nDoes anyone know the resolution to this issue? I need to be able to have my enums in separate files, so I can't declare it in the component.\n\nThanks!\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n import { TToken } from \"./global.d\";\n const value:TToken = TToken.X;\n</script>\n{#if value == TToken.X}\n Hi There!\n{:else}\n I don't like you\n{/if}\n```\n\n```text\n/// <reference types=\"svelte\" />\nexport enum TToken {\n X = 'X',\n O = 'O',\n Blank = ' '\n}\n```\n\n```text\nrollup v2.56.2\nbundles src/main.ts → public\\build\\bundle.js...\n[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)\nsrc\\global.d.ts (2:7)\n1: /// <reference types=\"svelte\" />\n2: export enum TToken {\n ^\n3: X = 'X',\n4: O = 'O',\nError: Unexpected token (Note that you need plugins to import files that are not JavaScript)\n at error (C:\\svelte-test\\node_modules\\rollup\\dist\\shared\\rollup.js:151:30)\n at Module.error (C:\\svelte-test\\node_modules\\rollup\\dist\\shared\\rollup.js:10059:16)\n at Module.tryParse (C:\\svelte-test\\node_modules\\rollup\\dist\\shared\\rollup.js:10462:25)\n at Module.setSource (C:\\svelte-test\\node_modules\\rollup\\dist\\shared\\rollup.js:10365:24)\n at ModuleLoader.addModuleSource (C:\\svelte-test\\node_modules\\rollup\\dist\\shared\\rollup.js:19708:20)\n at ModuleLoader.fetchModule (C:\\svelte-test\\node_modules\\rollup\\dist\\shared\\rollup.js:19764:9)\n at async Promise.all (index 1)\n at ModuleLoader.fetchStaticDependencies (C:\\svelte-test\\node_modules\\rollup\\dist\\shared\\rollup.js:19790:34)\n at async Promise.all (index 0)\n at ModuleLoader.fetchModule (C:\\svelte-test\\node_modules\\rollup\\dist\\shared\\rollup.js:19766:9)\n```\n\n```text\n// types.ts\n\nexport enum TToken {\n X = 'X',\n O = 'O',\n Blank = ' '\n}\n```\n\n```text\n.ts\n```\n\n```text\ntypes.ts\n```\n\n```text\n.d.ts\n```\n\n```text\nd.ts\n```\n\n```text\nd.ts\n```\n\n```text\n.ts\n```\n\n```text\n.js\n```\n\n========================================\n\nComments:\n- Since you are already using typescript in your project why not export it from a `types.ts` file for example? The `.d.ts` files can be generated by rollup.\n- @johannchopin That did it, thanks! If you want to make this an answer, I'll accept and upvote it.\n- I'd a similar issue, and I was exporting enum from a separate file (eg. filter-status.enum.ts), but it didn't work; it only started working after I stopped and ran the npm run dev command again","metadata":{"transformedAt":"2026-08-18T18:33:40.713Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":154,"estimatedTokens":1122}}740{"id":"stack-69768575","source":"stackoverflow","questionId":69768575,"title":"Env vars in Svelte - __myapp is not defined","tags":["javascript","environment-variables","svelte"],"text":"Title: Env vars in Svelte - __myapp is not defined\nTags: javascript, environment-variables, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to set up env vars on my Svelte app to hide an API key.\n\nI followed the instructions in this article [https://medium.com/dev-cafe/how-to-setup-env-variables-to-your-svelte-js-app-c1579430f032].\n\nHere's the structure of my rollup.config.js\n\n```\nimport { config as configDotenv } from 'dotenv';\nimport replace from '@rollup/plugin-replace';\n\nconfigDotenv();\n\nexport default {\n...\nplugins: [\n replace({\n __myapp: JSON.stringify({\n env: {\n isProd: production,\n amplitude_api_key : process.env.amplitude_api_key\n } \n })\n }),\n]}\n```\n\nWhen I try to access the env var by calling: `__myapp.env.API_KEY`\n\nI get this error: `__myapp is not defined`\n\n========================================\n\nTop Answer:\nEven though this thread is solved, I want to point out that your remark **\"to hide an API key\" is invalid** because .env on clientside is **always parsing** right into your sourcecode. So in other words: your api-key is being parsed (and exposed) in the source once you build.\n\n========================================\n\nCode:\n```text\nimport { config as configDotenv } from 'dotenv';\nimport replace from '@rollup/plugin-replace';\n\nconfigDotenv();\n\nexport default {\n...\nplugins: [\n replace({\n __myapp: JSON.stringify({\n env: {\n isProd: production,\n amplitude_api_key : process.env.amplitude_api_key\n } \n })\n }),\n]}\n```\n\n```text\n__myapp.env.API_KEY\n```\n\n```text\n__myapp is not defined\n```\n\n```text\nreplace({\n 'process.env.isProd': production,\n 'process.env.amplitude_api_key': process.env.amplitude_api_key\n}),\n```\n\n```text\nprocess.env.isProd\n```\n\n```text\n__myapp\n```\n\n```text\n__myapp\n```\n\n```text\nprocess\n```\n\n```js\nimport { config } from 'dotenv';\nimport replace from '@rollup/plugin-replace';\n```\n\n```js\nreplace({\n \"process.env.config\": JSON.stringify(config().parsed)\n }),\n```\n\n```js\nconsole.log(process.env.config)\n/* Output on client:\n** $> { PUBLIC_API_KEY: 'WW91IHRob3VnaHQgSSB3YXMgc3R1cGlkIG9yIHdoYXQgPw==' }\n*/\n```\n\n```js\nreplace({\n \"log\": console.log(config()) && true,\n}),\n```\n\n```text\nnpm install @rollup/plugin-replace dotenv --save-dev\n```\n\n```text\nrollup.config.js\n```\n\n```text\nplugins\n```\n\n```text\nexport default {\n```\n\n```text\n.env\n```\n\n```text\nnpm run dev\n```\n\n```text\n.env\n```\n\n```text\nprocess.env.config.VARIABLE_NAME\n```\n\n```text\nrollup.config.js\n```\n\n```text\n.env\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.713Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":157,"estimatedTokens":626}}741{"id":"stack-68936950","source":"stackoverflow","questionId":68936950,"title":"Sveltekit fetch file from static folder","tags":["javascript","deployment","fetch","server-side-rendering","svelte"],"text":"Title: Sveltekit fetch file from static folder\nTags: javascript, deployment, fetch, server-side-rendering, svelte\nSource: Stack Overflow\n\nQuestion:\nIn sveltekit i have a static folder, in which i have .zip file,\nto get it locally i do something like:\n\n`const res = await fetch(\"/static/makeup.zip\")`\n\nIt works fine, but when i deployed my app i've got a 404 error\n\nI've tried putting this file to different directories, tried different urls like: `\"/makeup.zip\", \"./static/makeup.zip\", \"makeup.zip\"`\n\n(i think someone who knows gatsby/nuxt can help)\n\nWhere should i put this file or how the query should look like ? Thanks\n\n========================================\n\nCode:\n```text\nconst res = await fetch(\"/static/makeup.zip\")\n```\n\n```text\n\"/makeup.zip\", \"./static/makeup.zip\", \"makeup.zip\"\n```\n\n```text\nawait fetch(\"/makeup.zip\")\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.713Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":32,"estimatedTokens":209}}742{"id":"stack-62766324","source":"stackoverflow","questionId":62766324,"title":"Am getting an \"Error: Semicolons aren't allowed in the indented syntax\" when using svelte with sass","tags":["sass","svelte"],"text":"Title: Am getting an \"Error: Semicolons aren't allowed in the indented syntax\" when using svelte with sass\nTags: sass, svelte\nSource: Stack Overflow\n\nQuestion:\nTried to read the documentation and correct some issues relating to sass. Added \"lang=scss\" to the component, but not sure how to correct this issue. Any guidance will be helpful.\n\n```\nrollup v2.19.0\nbundles src/main.js → public\\build\\bundle.js...\n[!] (plugin svelte) Error: semicolons aren't allowed in the indented syntax. ╷\n2 │ $primary: hsl(180, 29%, 50%);\n │ ^\n ╵\n stdin 2:29 root stylesheet\n```\n\nWhen changing the code to reflect lang=\"sass\", I get the same:\n\n```\nbundles src/main.js → public\\build\\bundle.js...\n[!] (plugin svelte) Error: semicolons aren't allowed in the indented syntax.\n ╷\n2 │ $primary: hsl(180, 29%, 50%);\n │ ^\n ╵\n stdin 2:29 root stylesheet\nsrc\\App.svelte\nError: semicolons aren't allowed in the indented syntax.\n ╷\n2 │ $primary: hsl(180, 29%, 50%);\n │ ^\n ╵\n stdin 2:29 root stylesheet\n```\n\n========================================\n\nTop Answer:\nI stumbled across this post having seen the same error in a Vue project, but my issue was that I simply hadn't read the code properly: there was a block written by another dev that specified `` and within that block I found a semicolon. Removing the semi colon (as you'd expect from the error message) fixed the problem. Equally, I could have changed the `lang` to `scss` and re-written that block in SCSS style.\n\nI hope that's of assistance to someone else who looks here before they read the code!\n\n========================================\n\nCode:\n```text\nrollup v2.19.0\nbundles src/main.js → public\\build\\bundle.js...\n[!] (plugin svelte) Error: semicolons aren't allowed in the indented syntax. ╷\n2 │ $primary: hsl(180, 29%, 50%);\n │ ^\n ╵\n stdin 2:29 root stylesheet\n```\n\n```text\nbundles src/main.js → public\\build\\bundle.js...\n[!] (plugin svelte) Error: semicolons aren't allowed in the indented syntax.\n ╷\n2 │ $primary: hsl(180, 29%, 50%);\n │ ^\n ╵\n stdin 2:29 root stylesheet\nsrc\\App.svelte\nError: semicolons aren't allowed in the indented syntax.\n ╷\n2 │ $primary: hsl(180, 29%, 50%);\n │ ^\n ╵\n stdin 2:29 root stylesheet\n```\n\n```text\n<style lang='sass'>\n```\n\n```text\nlang\n```\n\n```text\nscss\n```\n\n========================================\n\nComments:\n- scss and sass use a slighly different syntax (one of them is the use of semicolons), change your type to `lang=\"sass\"` and it should work","metadata":{"transformedAt":"2026-08-18T18:33:40.715Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":89,"estimatedTokens":631}}743{"id":"stack-64924517","source":"stackoverflow","questionId":64924517,"title":"How to specify the path of index.html in Rollup config for Svelte","tags":["svelte","rollup","rollupjs"],"text":"Title: How to specify the path of index.html in Rollup config for Svelte\nTags: svelte, rollup, rollupjs\nSource: Stack Overflow\n\nQuestion:\nI am using the default Rollup config as my bundler for Svelte, but I want to use a different path for the bundle files and index.html\n\nI can successfully change the path for the bundle files with this:\n\n```\nexport default {\n input: \"src/main.ts\",\n output: {\n sourcemap: true,\n format: \"iife\",\n name: \"app\",\n file: \"../static/build/bundle.js\",\n},\n```\n\nBut it still looks for the `index.html` file in the original path. I would like to add that into the `static` folder as well, just like the build files.\n\nHow can I configure rollup to specify the path of the single `index.html` file?\n\n========================================\n\nCode:\n```js\nexport default {\n input: \"src/main.ts\",\n output: {\n sourcemap: true,\n format: \"iife\",\n name: \"app\",\n file: \"../static/build/bundle.js\",\n},\n```\n\n```text\nindex.html\n```\n\n```text\nstatic\n```\n\n```text\nindex.html\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":49,"estimatedTokens":251}}744{"id":"stack-63814432","source":"stackoverflow","questionId":63814432,"title":"TypeScript typing of non-standard window event in Svelte","tags":["typescript","visual-studio-code","progressive-web-apps","svelte","svelte-3"],"text":"Title: TypeScript typing of non-standard window event in Svelte\nTags: typescript, visual-studio-code, progressive-web-apps, svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\nI'm using Svelte with TypeScript in vscode and I have the Svelte extension installed in vscode.\n\nIn my App.svelte I have\n\n```\n\n // a bunch of code that isn't relevant. This should just show that \n // `lang=\"ts\"` is set (above)\n\n// here comes the crucial part\n\n```\n\nAs you can see, in the `` tag I'm using the `on:beforeinstallprompt` event which is a non-standard event related to progressive web apps that works in some browsers (i.e. Chrome). Unfortunately but understandably, the TypeScript declarations that are active don't have `beforeinstallprompt` on the definition of the `Window` object. (The TypeScript declarations are most likely the ones coming from the Svelte vscode extension.)\n\nThe problem I have is that vscode shows an error at `on:beforeinstallprompt` because it thinks that the event does not exist.\n\nThe error message is:\n\n```\nType '{ onbeforeinstallprompt: (e: any) => void; }' is not assignable to type 'HTMLProps & SvelteWindowProps'.\nProperty 'onbeforeinstallprompt' does not exist on type 'HTMLProps & SvelteWindowProps'.ts(2322)\n```\n\nTo get rid of the error message I've tried adding a `*.d.ts` file to extend what needs to be extended but I haven't found out what to extend (e.g. an interface) or how that's done.\n\n(Note: I'm aware of the option to use `onMount()` to attach the handler to the `window.beforeinstallprompt` event but I want to know how/if it works with ``.)\n\n========================================\n\nCode:\n```text\n<script lang=\"ts\">\n // a bunch of code that isn't relevant. This should just show that \n // `lang=\"ts\"` is set (above)\n</script>\n\n// here comes the crucial part\n<svelte:window on:beforeinstallprompt={functionDeclaredInTheScript} />\n```\n\n```text\nType '{ onbeforeinstallprompt: (e: any) => void; }' is not assignable to type 'HTMLProps<Window> & SvelteWindowProps'.\nProperty 'onbeforeinstallprompt' does not exist on type 'HTMLProps<Window> & SvelteWindowProps'.ts(2322)\n```\n\n```text\n<svelte:window>\n```\n\n```text\non:beforeinstallprompt\n```\n\n```text\nbeforeinstallprompt\n```\n\n```text\nWindow\n```\n\n```text\non:beforeinstallprompt\n```\n\n```text\n*.d.ts\n```\n\n```text\nonMount()\n```\n\n```text\nwindow.beforeinstallprompt\n```\n\n```text\n<svelte:window>\n```\n\n```text\ndeclare namespace svelte.JSX {\n interface HTMLAttributes<T> {\n // You can replace any with something more specific if you like\n onbeforeinstallprompt?: (event: any) => any;\n }\n}\n```\n\n```text\nd.ts\n```\n\n```text\nd.ts\n```\n\n```text\ntsconfig.json\n```\n\n```text\n\"include\": [\"src/**/*\"]\n```\n\n```text\nd.ts\n```\n\n```text\nsrc\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":119,"estimatedTokens":678}}745{"id":"stack-69113480","source":"stackoverflow","questionId":69113480,"title":"Sveltekit: Cannot find module 'swiper'","tags":["svelte","swiper.js","vite","codesandbox","sveltekit"],"text":"Title: Sveltekit: Cannot find module 'swiper'\nTags: svelte, swiper.js, vite, codesandbox, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI tried the sveltekit-swiper example from\nhttps://swiperjs.com/svelte\n\n```\n08:07:51 [vite] Error when evaluating SSR module /src/routes/s.svelte: Error: Cannot find module 'swiper' from 'C:/Svelte/tw09swipe/src/routes'\n at Function.resolveSync [as sync] (C:\\Svelte\\tw09swipe\\node_modules\\resolve\\lib\\sync.js:102:15)\n at resolveFrom$3 (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:4081:29)\n at resolve (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:75136:22)\n at nodeRequire (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:75115:25)\n at ssrImport (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:75057:20)\n at eval (/src/routes/s.svelte:7:37)\n at async instantiateModule (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:75100:9)\n```\n\nI have installed new copies of sveltekit and swiper. Versions:\n\n```\nswiper@7.0.4\nvite@2.5.6\n@sveltejs/kit@1.0.0-next.165\n```\n\nA working example with Swiper 7 can be found in the codesandbox: https://codesandbox.io/s/3dxrg\nIt uses Swiper 7.0.3 and SvelteKit v1.0.0-next.104\n\nI have installed svelte/kit and swiper without any changes:\n\n```\nmkdir tw09swipe\ncd tw09swipe\nnpm init svelte@next\nnpm install\nnpm i swiper\n```\n\nThis is **my** package.json:\n\n```\n{\n \"name\": \"~TODO~\",\n \"version\": \"0.0.1\",\n \"scripts\": {\n \"dev\": \"svelte-kit dev\",\n \"build\": \"svelte-kit build\",\n \"preview\": \"svelte-kit preview\",\n \"check\": \"svelte-check --tsconfig ./tsconfig.json\",\n \"check:watch\": \"svelte-check --tsconfig ./tsconfig.json --watch\"\n },\n \"devDependencies\": {\n \"@sveltejs/kit\": \"next\",\n \"svelte\": \"^3.34.0\",\n \"svelte-check\": \"^2.0.0\",\n \"svelte-preprocess\": \"^4.9.4\",\n \"tslib\": \"^2.0.0\",\n \"typescript\": \"^4.0.0\"\n },\n \"type\": \"module\",\n \"dependencies\": {\n \"swiper\": \"^7.0.5\"\n }\n}\n```\n\nAnd here is tsconfig.json:\n\n```\n{\n \"compilerOptions\": {\n \"moduleResolution\": \"node\",\n \"module\": \"es2020\",\n \"lib\": [\"es2020\", \"DOM\"],\n \"target\": \"es2019\",\n /**\n svelte-preprocess cannot figure out whether you have a value or a type, so tell TypeScript\n to enforce using \\`import type\\` instead of \\`import\\` for Types.\n */\n \"importsNotUsedAsValues\": \"error\",\n \"isolatedModules\": true,\n \"resolveJsonModule\": true,\n /**\n To have warnings/errors of the Svelte compiler at the correct position,\n enable source maps by default.\n */\n \"sourceMap\": true,\n \"esModuleInterop\": true,\n \"skipLibCheck\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"baseUrl\": \".\",\n \"allowJs\": true,\n \"checkJs\": true,\n \"paths\": {\n \"$lib\": [\"src/lib\"],\n \"$lib/*\": [\"src/lib/*\"]\n }\n },\n \"include\": [\"src/**/*.d.ts\", \"src/**/*.js\", \"src/**/*.ts\", \"src/**/*.svelte\"]\n}\n```\n\nAnd svelte.config.js:\n\n```\nimport preprocess from 'svelte-preprocess';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: preprocess(),\n\n kit: {\n // hydrate the element in src/app.html\n target: '#svelte'\n }\n};\n\nexport default config;\n```\n\nroutes/s.svelte\n\n```\n\n // Import Swiper Svelte components \n import { Navigation, Pagination, Scrollbar, A11y } from \"swiper\";\n import { Swiper, SwiperSlide } from \"swiper/svelte\"; \n\n // Import Swiper styles\n import \"swiper/css\";\n import \"swiper/css/navigation\";\n import \"swiper/css/pagination\";\n import \"swiper/css/scrollbar\";\n\n console.log(\"slide change\")}\n on:swiper={(e) => console.log(e.detail[0])}\n>\n Slide 1\n Slide 2\n Slide 3\n Slide 4\n ...\n\n```\n\n========================================\n\nCode:\n```text\n08:07:51 [vite] Error when evaluating SSR module /src/routes/s.svelte: Error: Cannot find module 'swiper' from 'C:/Svelte/tw09swipe/src/routes'\n at Function.resolveSync [as sync] (C:\\Svelte\\tw09swipe\\node_modules\\resolve\\lib\\sync.js:102:15)\n at resolveFrom$3 (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:4081:29)\n at resolve (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:75136:22)\n at nodeRequire (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:75115:25)\n at ssrImport (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:75057:20)\n at eval (/src/routes/s.svelte:7:37)\n at async instantiateModule (C:\\Svelte\\tw09swipe\\node_modules\\vite\\dist\\node\\chunks\\dep-9f74b403.js:75100:9)\n```\n\n```text\nswiper@7.0.4\nvite@2.5.6\n@sveltejs/kit@1.0.0-next.165\n```\n\n```text\nmkdir tw09swipe\ncd tw09swipe\nnpm init svelte@next\nnpm install\nnpm i swiper\n```\n\n```text\n{\n \"name\": \"~TODO~\",\n \"version\": \"0.0.1\",\n \"scripts\": {\n \"dev\": \"svelte-kit dev\",\n \"build\": \"svelte-kit build\",\n \"preview\": \"svelte-kit preview\",\n \"check\": \"svelte-check --tsconfig ./tsconfig.json\",\n \"check:watch\": \"svelte-check --tsconfig ./tsconfig.json --watch\"\n },\n \"devDependencies\": {\n \"@sveltejs/kit\": \"next\",\n \"svelte\": \"^3.34.0\",\n \"svelte-check\": \"^2.0.0\",\n \"svelte-preprocess\": \"^4.9.4\",\n \"tslib\": \"^2.0.0\",\n \"typescript\": \"^4.0.0\"\n },\n \"type\": \"module\",\n \"dependencies\": {\n \"swiper\": \"^7.0.5\"\n }\n}\n```\n\n```text\n{\n \"compilerOptions\": {\n \"moduleResolution\": \"node\",\n \"module\": \"es2020\",\n \"lib\": [\"es2020\", \"DOM\"],\n \"target\": \"es2019\",\n /**\n svelte-preprocess cannot figure out whether you have a value or a type, so tell TypeScript\n to enforce using \\`import type\\` instead of \\`import\\` for Types.\n */\n \"importsNotUsedAsValues\": \"error\",\n \"isolatedModules\": true,\n \"resolveJsonModule\": true,\n /**\n To have warnings/errors of the Svelte compiler at the correct position,\n enable source maps by default.\n */\n \"sourceMap\": true,\n \"esModuleInterop\": true,\n \"skipLibCheck\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"baseUrl\": \".\",\n \"allowJs\": true,\n \"checkJs\": true,\n \"paths\": {\n \"$lib\": [\"src/lib\"],\n \"$lib/*\": [\"src/lib/*\"]\n }\n },\n \"include\": [\"src/**/*.d.ts\", \"src/**/*.js\", \"src/**/*.ts\", \"src/**/*.svelte\"]\n}\n```\n\n```text\nimport preprocess from 'svelte-preprocess';\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: preprocess(),\n\n kit: {\n // hydrate the <div id=\"svelte\"> element in src/app.html\n target: '#svelte'\n }\n};\n\nexport default config;\n```\n\n```text\n<script>\n\n // Import Swiper Svelte components \n import { Navigation, Pagination, Scrollbar, A11y } from \"swiper\";\n import { Swiper, SwiperSlide } from \"swiper/svelte\"; \n\n // Import Swiper styles\n import \"swiper/css\";\n import \"swiper/css/navigation\";\n import \"swiper/css/pagination\";\n import \"swiper/css/scrollbar\";\n</script>\n\n<Swiper\n modules={[Navigation, Pagination, Scrollbar, A11y]}\n spaceBetween={50}\n slidesPerView={3}\n navigation\n pagination={{ clickable: true }}\n scrollbar={{ draggable: true }}\n on:slideChange={() => console.log(\"slide change\")}\n on:swiper={(e) => console.log(e.detail[0])}\n>\n <SwiperSlide>Slide 1</SwiperSlide>\n <SwiperSlide>Slide 2</SwiperSlide>\n <SwiperSlide>Slide 3</SwiperSlide>\n <SwiperSlide>Slide 4</SwiperSlide>\n ...\n</Swiper>\n```\n\n```text\n<script>\n import { Swiper, SwiperSlide } from 'swiper/svelte';\n import SwiperCore, { Mousewheel, Pagination } from 'swiper';\n import 'swiper/css';\n import 'swiper/css/pagination';\n\n ...\n\n SwiperCore.use([Mousewheel, Pagination]);\n</script>\n\n...\n <Swiper\n direction='vertical'\n mousewheel={true}\n pagination={true}\n slidesPerView={1}\n on:slideChange={onSlideChange}\n on:swiper={(e) => console.log(e.detail[0])}\n >\n <SwiperSlide>\n </Swiper>\n...\n```\n\n```text\n<script>\n ...\n let Slider;\n onMount(async () => {\n const module = await import('./components/Slider.svelte');\n Slider = module.default;\n });\n ...\n</script>\n\n<svelte:component this={Slider}/>\n\n...\n```\n\n```text\nonMount\n```\n\n```text\nonMount\n```\n\n========================================\n\nComments:\n- The new swiper@7.0.5 did not solve this problem.\n- Weird response here. I created skeleton Sveltekit with TS. When I go to `localhost:3000/s` the browser shows error `Cannot find module 'swiper' from 'M:/Temp/swiper_test/src/routes'` while in VSCode, import clearly points to `module \"m:/Temp/swiper_test/node_modules/swiper/svelte/swiper-svelt‌​e\"` as it should. Essentially same failure as you.\n- When I do a search for `sync.js:102:15` I do see issues out there. Check out github.com/sveltejs/kit/issues/2237 Pretty good analysis of what is driving the error. And they say 1.0.0-next.160 release fixes it. sigh.\n- Sorry for asking again. I have tried `import { Swiper, SwiperSlide } from 'swiper/swiper-svelte.cjs.js';` And `npm run build`. Nothing worked. Any hints?\n- Thank you! This is how it works. I don't understand why the detour via a component is necessary. Maybe someone in the know can explain it. But anyway - it works, also with SvelteKit v1.0.0-next.173. In Slider.svelte is missing `import './style.css';` `style.css` can be found for example here codesandbox.io/s/mop0u\n- But this is a really interesting solution, best thanks!\n- When SvelteKit bundles files (even for dev server), it simulates server-side like environment, to run and optimize code faster (and other things like supporting pre-rendering out of box). Some of modules don't expect this and trying to access `window/document` variable (there is none in server-side JS) - so we need to load these modules `onMount`, because code there executes only in client side environment, where `window` object exists.\n- Thank you for this explanation. I believed that an \"onMount\" in \"index.svelte\" would be sufficient. But I understand now why a separate module is necessary.","metadata":{"transformedAt":"2026-08-18T18:33:40.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":348,"estimatedTokens":2540}}746{"id":"stack-65992267","source":"stackoverflow","questionId":65992267,"title":"Keeping extra script tags in compiled svelte code","tags":["javascript","visual-studio-code","svelte","rollupjs"],"text":"Title: Keeping extra script tags in compiled svelte code\nTags: javascript, visual-studio-code, svelte, rollupjs\nSource: Stack Overflow\n\nQuestion:\nI am currently having a svelte program that gets compiled to the corresponding, js and css files, which I am using in a separate html template string. That is getting used as part of an application's webview - it basically gets put into a iframe at the end inside that application.\n\n```\n\n \n \n \n \n \n \n \n \n const vscode = acquireVsCodeApi();\n \n \n \n \n \n \n \n\n```\n\nI have my rollup config setup such that whatever is in my svelte folders gets compiled to js and css as said above which I import in the lines.\n\nThe line `` and `` are the places where I am importing the compiled code. Similarly, my css gets imported.\n\n**Notice** that I am using the tag as the place to mount my app like so,\n\n```\nimport App from \"../components/MainPanel.svelte\";\n\nconst app = new App({\n target: document.getElementsByTagName(\"App\")[0],\n});\n\nexport default app;\n```\n\n### The Issue\n\nIt all works perfectly fine - it renders fine and all. But, the issue I am facing is that, the `` that I have in the `body` of the `html` code above, is not seen finally. Is it that `svelte` removes all other tags? I have seen this normally if I have other `p`, `h1` or other `html` tags in the `body`, they get removed - but I have targeted `App` here, so it should not get removed yeah?\n\nIf not is there any other way to include my script in that html? Maybe include it inside the pre-compiled files so that it stays even after the compiling?\n\n**Note** That extra script import is itself a minified script as it is node and some reason I am not able to use it within svelte.\n\n**--Update 1--**\n\nAfter inspecting the rendered HTML, I have found that the extra script tag `` gets shifted inside the script tag ``. I do not understand why, more like any other tags in the html gets pushed into the script that references the compiled svelte code.\n\n========================================\n\nCode:\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta chatset='UTF-8\">\n <meta http-equiv=\"Content-Security-Policy\" content=\"default-src img-src https: data:; style-src 'unsafe-inline' ${webview.cspSource}; script-src 'nonce-${nonce}';\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <link href=\"${styleResetUri}\" rel=\"stylesheet\">\n <link href=\"${styleMainUri}\" rel=\"stylesheet\">\n <link href=\"${styleMainPanel}\" rel=\"stylesheet\">\n <script nonce=\"${nonce}\">\n const vscode = acquireVsCodeApi();\n </script>\n </head>\n <body>\n <main><App/></main>\n <script src=\"${scriptMainPanel}\" nonce=\"${nonce}\" />\n <script src=\"${gramJS}\" nonce=\"${nonce}\" />\n </body>\n</html>\n```\n\n```js\nimport App from \"../components/MainPanel.svelte\";\n\nconst app = new App({\n target: document.getElementsByTagName(\"App\")[0],\n});\n\nexport default app;\n```\n\n```text\n<script src=\"${scriptMainPanel}\" nonce=\"${nonce}\" />\n```\n\n```text\n<link href=\"${styleMainPanel}\" rel=\"stylesheet\">\n```\n\n```text\n<script src=\"${gramJS}\" nonce=\"${nonce}\" />\n```\n\n```text\nbody\n```\n\n```text\nhtml\n```\n\n```text\nsvelte\n```\n\n```text\np\n```\n\n```text\nh1\n```\n\n```text\nhtml\n```\n\n```text\nbody\n```\n\n```text\nApp\n```\n\n```text\n<script src=\"${gramJS}\" nonce=\"${nonce}\" />\n```\n\n```text\n<script src=\"${scriptMainPanel}\" nonce=\"${nonce}\" />\n```\n\n```text\n<script src=\"${scriptMainPanel}\" nonce=\"${nonce}\"></script>\n<script src=\"${gramJS}\" nonce=\"${nonce}\"></script>\n```\n\n```text\n<script>\n```\n\n========================================\n\nComments:\n- You are not showing how you actually \"render\" the HTML template, but I don't think svelte is doing anything with it. The problem is likely that you are self-closing the `` elements. Those are not self-closing elements, you always need a proper end tag: ``. Give that a try.\n- Oh! great I will try that out. But I do not render it. I just return this html template string which gets passed onto the vscode extension webview. I don't control it much. But, you see if I just enter normal html elements inside that body tag without the compiled svelte scripts, it works perfectly fine.\n- I found out something after inspecting the rendered html, which I have update.\n- Hey @FelixKling. You literally solved my problem. I converted them to `` tags and it works like charm. Feel free to add an answer and I would be able to mark it up. Thank you so much. You just cleared the issue I had for 3 days now. <3","metadata":{"transformedAt":"2026-08-18T18:33:40.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":159,"estimatedTokens":1125}}747{"id":"stack-62830561","source":"stackoverflow","questionId":62830561,"title":"Installing mermaid on svelte","tags":["svelte","mermaid"],"text":"Title: Installing mermaid on svelte\nTags: svelte, mermaid\nSource: Stack Overflow\n\nQuestion:\nI'm trying to install Mermaid with Svelte to make graphs. So I did the following:\n\n`npm install mermaid`\n\nThen I get the following:\n\n```\nnpm WARN svelte-app@1.0.0 No repository field.\nnpm WARN svelte-app@1.0.0 No license field.\n\n+ mermaid@8.5.2\nupdated 1 package and audited 142 packages in 5.939s\n```\n\nAnd then when I try to run my server, I get:\n\n```\nbundles src/main.js → public/build/bundle.js...\n[!] Error: Could not resolve './Mermaid.svelte' from src/pages/Statistics.svelte\nError: Could not resolve './Mermaid.svelte' from src/pages/Statistics.svelte\n at error (/Users/evgeniyanagornaya/projects/anyhow/node_modules/rollup/dist/shared/node-entry.js:5400:30)\n at ModuleLoader.handleResolveId (/Users/evgeniyanagornaya/projects/anyhow/node_modules/rollup/dist/shared/node-entry.js:12410:24)\n at ModuleLoader. (/Users/evgeniyanagornaya/projects/anyhow/node_modules/rollup/dist/shared/node-entry.js:12298:30)\n at Generator.next ()\n at fulfilled (/Users/evgeniyanagornaya/projects/anyhow/node_modules/rollup/dist/shared/node-entry.js:38:28)\n```\n\nCan anybody please tell me what is going on and how I can fix this? Thank you!\n\n========================================\n\nCode:\n```text\nnpm WARN svelte-app@1.0.0 No repository field.\nnpm WARN svelte-app@1.0.0 No license field.\n\n+ mermaid@8.5.2\nupdated 1 package and audited 142 packages in 5.939s\n```\n\n```text\nbundles src/main.js → public/build/bundle.js...\n[!] Error: Could not resolve './Mermaid.svelte' from src/pages/Statistics.svelte\nError: Could not resolve './Mermaid.svelte' from src/pages/Statistics.svelte\n at error (/Users/evgeniyanagornaya/projects/anyhow/node_modules/rollup/dist/shared/node-entry.js:5400:30)\n at ModuleLoader.handleResolveId (/Users/evgeniyanagornaya/projects/anyhow/node_modules/rollup/dist/shared/node-entry.js:12410:24)\n at ModuleLoader.<anonymous> (/Users/evgeniyanagornaya/projects/anyhow/node_modules/rollup/dist/shared/node-entry.js:12298:30)\n at Generator.next (<anonymous>)\n at fulfilled (/Users/evgeniyanagornaya/projects/anyhow/node_modules/rollup/dist/shared/node-entry.js:38:28)\n```\n\n```text\nnpm install mermaid\n```\n\n```text\n<script>\n import mermaid from 'mermaid';\n import { onMount } from 'svelte';\n\n let graph = null;\n let gantt = null;\n\n mermaid.initialize({\n startOnLoad: false,\n\n theme: 'forest',\n gantt: { axisFormatter: [\n ['%Y-%m-%d', (d) => {\n return d.getDay() === 1\n }]\n ] }\n });\n\n onMount(() => {\n mermaid.init([ graph, gantt ]);\n });\n</script>\n\n<main>\n <pre bind:this={graph}>\ngraph LR\nA-->B\n </pre>\n <pre bind:this={gantt}>\ngantt\ntitle A Gantt Diagram\ndateFormat YYYY-MM-DD\nsection Section\nA task :a1, 2014-01-01, 30d\nAnother task :after a1 , 20d\nsection Another\nTask in sec :2014-01-12 , 12d\nanother task : 24d\n </pre>\n</main>\n```\n\n========================================\n\nComments:\n- your error indicates there is no such file as `./Mermaid.svelte`","metadata":{"transformedAt":"2026-08-18T18:33:40.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":107,"estimatedTokens":777}}748{"id":"stack-67941539","source":"stackoverflow","questionId":67941539,"title":"Svelte reversing table of 500 rows feels slow?","tags":["svelte"],"text":"Title: Svelte reversing table of 500 rows feels slow?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI created table of 500 rows, and reversing it on click feels slow, subjectively like 500ms or so.\n\nIs it reasonable performance? I have a feeling that reversing table of 500 lines in JS should be faster.\n\nSvelte demo and Pure JS demo.\n\nPure JS feels much faster than Svelte\n\nTable.svelte\n\n```\n\n import Cell from \"./Cell.svelte\"\n \n const template = {\n name: \"Barrick Gold Corp\",\n symbol: \"ABX\",\n has_options: true,\n ib_symbol: \"GOLD NYSE USD\",\n ib_osymbol: \"GOLD CBOE USD\",\n risk: 0,\n quality: 0,\n brand: 0\n }\n\n let rows = []\n let id = 0\n for (let i = 0; i \n\n rows = rows.reverse()}>change order\n {#each rows as row (row[0])}\n \n {#each row as cell, j (`${row[0]},${j}`)}\n \n {/each}\n \n {/each}\n\n```\n\n```\n\n import StringView from \"./StringView.svelte\"\n \n export let value\n\n```\n\n```\n\n export let value\n\n{value}\n```\n\nP.S.\n\nSvelte demo with additional Row element performance feels same as for original svelte version.\n\nAnd a version with just single table element without Row and Cell elements, feels a bit faster\n\n========================================\n\nCode:\n```svelte\n<script>\n import Cell from \"./Cell.svelte\"\n \n const template = {\n name: \"Barrick Gold Corp\",\n symbol: \"ABX\",\n has_options: true,\n ib_symbol: \"GOLD NYSE USD\",\n ib_osymbol: \"GOLD CBOE USD\",\n risk: 0,\n quality: 0,\n brand: 0\n }\n\n let rows = []\n let id = 0\n for (let i = 0; i < 500; i++) {\n let row = [id++]\n for (let key in template) row.push((\"\" + template[key]) + i)\n rows.push(row)\n } \n</script>\n\n<table>\n <button on:click={() => rows = rows.reverse()}>change order</button>\n {#each rows as row (row[0])}\n <tr>\n {#each row as cell, j (`${row[0]},${j}`)}\n <Cell value={cell} />\n {/each}\n </tr>\n {/each}\n</table>\n```\n\n```svelte\n<script>\n import StringView from \"./StringView.svelte\"\n \n export let value\n</script>\n\n<svelte:component this={StringView} value={value}/>\n```\n\n```svelte\n<script>\n export let value\n</script>\n\n<td>{value}</td>\n```\n\n```svelte\n<script>\n function reverse(list) { \n list = [...list]\n list.reverse()\n return list\n }\n</script>\n<button on:click={() => rows = reverse(rows)}>change order</button>\n```\n\n```svelte\n<script>\n function reverseRows() { \n rows = rows.reverse()\n }\n</script>\n<button on:click={reverseRows}>change order</button>\n```\n\n```svelte\n<!--[App.svelte]-->\n<script>\n import { beforeUpdate, afterUpdate } from 'svelte';\n import TableRow from './TableRow.svelte';\n \n beforeUpdate(() => {\n// console.log('before Update')\n console.time('time to update');\n });\n afterUpdate(() => {\n// console.log('after Update')\n console.timeEnd('time to update')\n });\n \n const template = {\n name: \"Barrick Gold Corp\",\n symbol: \"ABX\",\n has_options: true,\n ib_symbol: \"GOLD NYSE USD\",\n ib_osymbol: \"GOLD CBOE USD\",\n risk: 0,\n quality: 0,\n brand: 0\n }\n\n let rowsAsObj = []\n \n for(let i = 0; i< 500; i++){\n let row = {id: i,}\n for( let key in template){\n row[key] = `${template[key]}${i}` \n }\n rowsAsObj.push(row)\n } \n function reverse() { \n rowsAsObj = rowsAsObj.reverse();\n }\n function slice(){\n rowsAsObj = rowsAsObj.slice(1)\n }\n</script>\n\n <button on:click={reverse}>change order</button>\n <button on:click={slice}>slice</button>\n\n<table>\n {#each rowsAsObj as row (row.id)}\n <TableRow {row}/>\n {/each}\n</table>\n\n<style>\n table {\n border-collapse: collapse;\n width: 100%;\n }\n</style>\n```\n\n```svelte\n<!--[TableRow.svelte]-->\n<script>\n import { fade } from 'svelte/transition'\n \n import { afterUpdate } from 'svelte';\n afterUpdate(() => {\n// console.log('TableRow updated')\n });\n \n export let row;\n</script>\n\n<tr transition:fade=\"{{duration: 800, delay: 800}}\">\n {#each Object.values(row) as cell}\n <td>\n {cell}\n </td>\n {/each}\n</tr>\n\n<style>\n \n td {\n padding: 5px;\n border-bottom: 1px solid grey;\n }\n \n</style>\n```\n\n========================================\n\nComments:\n- Why do you copy the list first instead of just return the reverse immediately: `function reverse(list) { return list.reverse() }` ? That skips about half of your operation\n- @StephaneVanraes thanks I updated, but it didn't affected the performance\n- Thanks, good advice about non-unique indexes for nested loop!\n- If you interested, I made a pure-JS version, it feels way faster codepen.io/alexey-petrushin/pen/KKWGJXR?editors=1010","metadata":{"transformedAt":"2026-08-18T18:33:40.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":241,"estimatedTokens":1170}}749{"id":"stack-62767633","source":"stackoverflow","questionId":62767633,"title":"Sapper: is it safe to render sensitive data, based on user rights?","tags":["svelte","sapper"],"text":"Title: Sapper: is it safe to render sensitive data, based on user rights?\nTags: svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI want to render 500 error's traceback came from server only for admin, so:\n\n- In `server.js`, session is populated with user retrieved from http_only cookie, just something like `{'username': 'admin'}`\n\n```\npolka()\n .use(\n sapper.middleware({\n session: (req, res) => {\n return { 'user': parseCookie('user') }\n }\n })\n )\n .listen(PORT);\n```\n\n- In some `index.js` there is a global variable to store possible traceback of 500 error came from server:\n\n```\nimport { writable } from 'svelte/store';\n\nexport const error = writable();\n```\n\n- In `index.html` article is preloaded, and in case of 500 error, traceback is rendered below if current user is admin:\n\n```\n\n import { error } from 'index.js';\n\n export async function preload(page, session) {\n return { article : await this.fetch('/api/article/').then(response => {\n if (response.status == 500 && session.user.username === 'admin') {\n error.set(response);\n }\n return response.json();\n })}\n }\n\n export let article\n\n### { article.title }\n\n{ article.text }\n\n{#if $error}\n {@html $error}\n{/if}\n```\n\nSo, if `$error` is set via `preload` function, will it be safe and rendered only server-side?\nIf not, how can it be improved?\nMaybe `if (process.browser)` could help somehow?\nThx\n\n========================================\n\nTop Answer:\n### Update\n\nCheck the below answer by Rich Harris\n\n### Original\n\nIf you have used one of the templates with either webpack or rollup you will see that `process.browser` is replaced with `true` meaning that unreachable code will be tree shaked.\n\nSo short answer would be yes, you should be fine to use it as long as you surround that code with `process.browser` in appropriate place\n\nBut with that being said you are better off relying on server logs when it comes to 500 error code. Returning just error code to all of the users and nothing more, and pushing stack traces to log system instead for debugging.\n\n========================================\n\nCode:\n```text\npolka()\n .use(\n sapper.middleware({\n session: (req, res) => {\n return { 'user': parseCookie('user') }\n }\n })\n )\n .listen(PORT);\n```\n\n```text\nimport { writable } from 'svelte/store';\n\nexport const error = writable();\n```\n\n```text\n<script context=\"module\">\n\n import { error } from 'index.js';\n\n export async function preload(page, session) {\n return { article : await this.fetch('/api/article/').then(response => {\n if (response.status == 500 && session.user.username === 'admin') {\n error.set(response);\n }\n return response.json();\n })}\n }\n</script>\n\n<script>\n export let article\n</script>\n\n<h1>{ article.title }</h1>\n<div>{ article.text }</div>\n\n<!-- 500 ERROR TRACEBACK --->\n{#if $error}\n {@html $error}\n{/if}\n```\n\n```text\nserver.js\n```\n\n```text\n{'username': 'admin'}\n```\n\n```text\nindex.js\n```\n\n```text\nindex.html\n```\n\n```text\n$error\n```\n\n```text\npreload\n```\n\n```text\nif (process.browser)\n```\n\n```html\n<script context=\"module\">\n export async function preload(page, session) {\n const response = await this.fetch('/api/article/');\n\n return {\n article: await response.json(),\n error: response.status === 500 && session.user.username === 'admin'\n ? response\n : null\n };\n }\n</script>\n\n<script>\n export let article;\n export let error;\n</script>\n\n<h1>{ article.title }</h1>\n<div>{ article.text }</div>\n\n<!-- 500 ERROR TRACEBACK --->\n{#if error}\n {@html error}\n{/if}\n```\n\n```text\nresponse.json()\n```\n\n```text\nerror\n```\n\n```text\nerror\n```\n\n```text\nsession\n```\n\n```text\nprocess.browser\n```\n\n```text\ntrue\n```\n\n```text\nprocess.browser\n```\n\n========================================\n\nComments:\n- Oh, big thx, did not know that stores are unique for whole process among all users. Sure such thing must be controlled by server, just wanted to understand sapper lifecycle deeper. Can you clarify please, \"sufficiently dedicated\" - is a man who can use some frontend vulnerability like csrf/xss or it can be accessed somehow event without any vulnerabilities?\n- I basically mean someone exploiting a vulnerability of some sort (which could be as simple as you or a coworker putting `window.session = stores().session` in a component somewhere to help you debug, then forgetting to take it out","metadata":{"transformedAt":"2026-08-18T18:33:40.715Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":213,"estimatedTokens":1119}}750{"id":"stack-61814926","source":"stackoverflow","questionId":61814926,"title":"Svelte (routify) + rollup: not watching for css changes in /static","tags":["svelte","rollup"],"text":"Title: Svelte (routify) + rollup: not watching for css changes in /static\nTags: svelte, rollup\nSource: Stack Overflow\n\nQuestion:\nI want to be able to watch for changes in /static (for example, on global.css)\n\nI am using the following code to watch for changes on my static directory:\n\n```\nwatch: {\n clearScreen: false,\n include: [\"static/**\", \"src/**\"]\n },\n```\n\nI also tried calling add \"css\" to the --extensions option in routify cli:\n`routify -D --extensions svelte,html,md,css`\n\nHowever nothing works, and I can't seem to trigger a rebuild on changes to css files... Any advice?\n\nThanks!\n\n========================================\n\nCode:\n```text\nwatch: {\n clearScreen: false,\n include: [\"static/**\", \"src/**\"]\n },\n```\n\n```text\nroutify -D --extensions svelte,html,md,css\n```\n\n```sh\nyarn add -D rollup-plugin-copy-watch\n```\n\n```js\n// import copy from 'rollup-plugin-copy'\nimport copy from 'rollup-plugin-copy-watch'\n```\n\n```js\ncopy({\n targets: [\n { src: staticDir + '/**/!(__index.html)', dest: distDir },\n { src: `${staticDir}/__index.html`, dest: distDir, rename: '__app.html', transform },\n ],\n copyOnce: true,\n flatten: false,\n\n watch: staticDir,\n verbose: true,\n }),\n```\n\n```text\nimport\n```\n\n```text\ninput\n```\n\n```text\nindex.html\n```\n\n```text\nrollup-plugin-postcss\n```\n\n```text\nimport './global.css'\n```\n\n```text\nmain.js\n```\n\n```text\nstatic\n```\n\n```text\nglobal.css\n```\n\n```text\nrollup.config.js\n```\n\n```text\nwatch\n```\n\n```text\ncopy\n```\n\n```text\nverbose\n```\n\n========================================\n\nComments:\n- Changes to assets located in `static/` shouldn't require a full rebuild anyway, so there's really no need to watch these files. You don't see the changes after doing a browser clear cache + reload?\n- Routify copies the contents of /static/ to /build/static, so any changed files must be copied. I am aware that rollup-plugin-copy is performing that operation at the beginning of each build, but then it stops watching and updating files from /static. I tried setting copyOnce: false in the options for rollup-plugin-copy, but that didn't help, and furthermore it made the ordinary svelte files not being updated properly.\n- That's excellent, thank you so much!! This is exactly what I was looking for. Both options seem reasonable, I'll try and see which one adjusts better to my setup. I assume that copy-watch is more useful when I have many assets in static that I want to watch for, while importing the .css in my main.js seems a fair solution for simply one file... am I correct?\n- The copy watch option is easier to setup and will handle more cases, if you have images, fonts, etc. in your static folder. The postcss option will actually slow your (re)build a little (since now css is part of the bundle), BUT it can support advanced usage, like SASS, autoprefixing, etc. I think this is on this last point that I would base my decision. FWIW both solutions are not incompatible or exclusive of each other.","metadata":{"transformedAt":"2026-08-18T18:33:40.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":115,"estimatedTokens":757}}751{"id":"stack-61987559","source":"stackoverflow","questionId":61987559,"title":"Grouping over an {#each} loop in Svelte","tags":["javascript","svelte"],"text":"Title: Grouping over an {#each} loop in Svelte\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI have an array of non-homogeneous objects that are each rendered in a loop using a `` component, and I would like to group adjacent things that are of the same type within a div.\n\nFor example, I have some code similar to this:\n\n```\n\nlet things = [\n {type: A, content: \"One\"},\n {type: B, content: \"Two\"},\n {type: B, content: \"Three\"},\n {type: A, content: \"Four\"}\n];\n\n{#each things as thing, i}\n {()=>someMagicHere1(things, thing, i)}\n \n {()=>someMagicHere2(things, thing, i)}\n{/each}\n```\n\nAnd I want the output to group the things like so:\n\n```\n\n One\n\n Two\n Three\n\n Four\n\n```\n\nIn the `things` array, the things are not sorted (actually, they are, but by date, unrelated to their type), but the idea is to visually group together the ones that are the same type. Ideally, I'd be able to group only certain types (like group all of type A, but type B's would remain separate), but I feel like I would be able to derive a separate solution if I could group at all. There are also more than two types; this is just a minimal sample.\n\nIn Svelte, the individual A and B components can't have partial HTML elements like this inside, because Svelte won't allow conditionals around unclosed elements:\n\n```\n{#if groupStart}\n\n{/if}\n```\n\nFrom within each `someMagicHereX()` I could output some HTML with `{@html customTags}` to get the DOM output that I want, but then I lose the style encapsulation and other Svelte component benefits.\n\nWhat I'd really like is a more \"sveltian\" solution. Perhaps I need to create something new with `use`? Anyone have any good ideas?\n\n*Update:* A key feature I seem to have left out is that any controls must ultimately bind to the original dataset. So even if the data is transformed somehow, the original data must be updated at runtime and vice-versa on any bound controls.\n\n========================================\n\nCode:\n```text\n<script>\nlet things = [\n {type: A, content: \"One\"},\n {type: B, content: \"Two\"},\n {type: B, content: \"Three\"},\n {type: A, content: \"Four\"}\n];\n</script>\n\n{#each things as thing, i}\n {()=>someMagicHere1(things, thing, i)}\n <svelte:component this={thing.type}>\n {()=>someMagicHere2(things, thing, i)}\n{/each}\n```\n\n```text\n<div class=\"group type-A\">\n <div class=\"thing type-A\">One</div>\n</div>\n<div class=\"group type-B\">\n <div class=\"thing type-B\">Two</div>\n <div class=\"thing type-B\">Three</div>\n</div>\n<div class=\"group type-A\">\n <div class=\"thing type-A\">Four</div>\n</div>\n```\n\n```text\n{#if groupStart}\n<div class=\"group\">\n{/if}\n```\n\n```text\n<svelte:component this={type}>\n```\n\n```text\nthings\n```\n\n```text\nsomeMagicHereX()\n```\n\n```text\n{@html customTags}\n```\n\n```text\nuse\n```\n\n```js\n[\n {\n cssClass: 'type-A',\n values: [ /* all objects of type 'A' */ ],\n },\n {\n cssClass: 'type-B',\n values: [ /* all objects of type 'B' */ ],\n },\n // etc.\n]\n```\n\n```js\nlet groups = things.reduce((curr, val) => {\n let group = curr.find(g => g.cssClass === `type-${val.type}`)\n if (group)\n group.values.push(val)\n } else {\n curr.push({ cssClass: `type-${val.type}`, values: [ val ] }) \n }\n return curr\n}, [])\n```\n\n```js\n{#each groups as group}\n <div class=\"group {group.cssClass}\">\n {#each group.values as value}\n <div class=\"thing {group.cssClass}\">\n {value.content}\n </div>\n {/each}\n </div>\n{/each}\n```\n\n```js\nlet groups = things.reduce((curr, val) => {\n let group = curr.length ? curr[curr.length - 1] : undefined \n if (group && group.cssClass === `type-${val.type}`) {\n group.values.push(val)\n } else {\n curr.push({ cssClass: `type-${val.type}`, values: [ val ] }) \n }\n return curr\n}, [])\n```\n\n```text\n#each\n```\n\n========================================\n\nComments:\n- I was all set to call this a working solution, even though I thought I'd tried this before, but then I remembered why what I did didn't work. The new group array doesn't bind to the original data, and it *must*. See this: svelte.dev/repl/46757f90b10546f292287770231b0c07?version=3.2‌​2.3\n- Making the transformed data bound is as easy as turning it into a Svelte reactive declaration, replacing `let groups = things.reduce(...)` with `$: groups = things.reduce(...)`. See svelte.dev/repl/de1b8912d4554855a7be13319d7ce7e6?version=3.2‌​2.3.\n- Note that this is valid for any data transformation you would choose to apply, which imo is the beauty of it - leaving the layout structure untouched but changing the data transformation to fit your needs, and making it reactive or not depending on your binding requirements.\n- That's amazing. And amazingly simple. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:40.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":174,"estimatedTokens":1169}}752{"id":"stack-57330459","source":"stackoverflow","questionId":57330459,"title":"How do i debug svelte compiler?","tags":["svelte"],"text":"Title: How do i debug svelte compiler?\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to build and debug svelte source code to learn svelte internal better.\n\nThe code runs as expected.\nThe problem appears when I use the svelte compiler on a plain old JavaScript file and trying to debug it with VSCode.\n\nIt seems that the debugger fails to read the source map file. \n\nThe debugger highlights / read compiler.js (compiled one) but I want to debug the .ts one instead of the compiled file.\n\nHere's the code :\n\n```\n// playsv.js\nconst sv = require('./compiler')\nconst str = '\n\n### text\n\n'\n// get ast\nconst ast = sv.parse(str)\n```\n\nThanks\n\n========================================\n\nCode:\n```js\n// playsv.js\nconst sv = require('./compiler')\nconst str = '<h1>text</h1>'\n// get ast\nconst ast = sv.parse(str)\n```\n\n```text\nsveltejs/svelte\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm link\n```\n\n```text\nnpm link svelte\n```\n\n========================================\n\nComments:\n- Try using `npm link` like this to use the local svelte package gist.github.com/unlocomqx/175225cedafc2b8c3d06686915f94930\n- Thank you, i will try and report as soon as possible.\n- @UnLoCo it work like a charm.","metadata":{"transformedAt":"2026-08-18T18:33:40.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":63,"estimatedTokens":297}}753{"id":"stack-57066539","source":"stackoverflow","questionId":57066539,"title":"Hide Routes in Svelte-Routing when logged out","tags":["svelte"],"text":"Title: Hide Routes in Svelte-Routing when logged out\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nWhen I try to hide the pages of certain routes when the user is not logged in it works well. But once the user is logged in the pages no longer show the content when I navigate to the page with `svelte-routing`'s `navigate` method. But once I click on the route they are rendered fine. Am I doing something wrong? Below is the basic set up. You can also find it on github.\n\n`App.svelte`\n\nYou can see in the example below that I hide the `Route`s in the `if-else` clause under the `main` HTML tag. When I'm on page `/somewhere` and am also already logged out and then click login and then click submit it is supposed to take me back to `/somewhere` which is does. But the text `Somewhere` doesn't show like it should until I click the link `Somewhere`. The expected result would be that it shows up.\n\n```\n\nimport { Router, Link, Route, navigate } from \"svelte-routing\"\nimport Login from \"./Login.svelte\"\nimport Somewhere from \"./Somewhere.svelte\"\nimport Home from \"./Home.svelte\"\n\nlet user = null\nvar previousPath\n\n$: user\n\nfunction logout() {\n localStorage.clear()\n user = null\n navigate(\"/\")\n}\n\nfunction loggedIn (event) {\n if (event) {\n user = { name: \"George\" }\n navigate(previousPath, { replace: true })\n }\n}\n\nfunction loggingIn() {\n previousPath = window.location.pathname\n}\n\n \n\n### Test Login\n\n \n Home\n {#if user === null}\n Login\n {:else}\n Somewhere\n \n \n \n {/if}\n \n \n {#if user !== null}\n \n \n {:else}\n Please login\n\n \n {/if}\n \n\n```\n\nHere's the other pages:\n\n`Home.svelte`\n\n```\nYellow!\n\n```\n\n`Login.svelte`\n\n```\n\nimport { createEventDispatcher } from \"svelte\";\n\nconst dispatch = createEventDispatcher()\n\nfunction submit() {\n dispatch(\"loggedIn\", true)\n}\n\n \n\n```\n\n`Somewhere.svelte`\n\n```\nSomewhere!\n\n```\n\n========================================\n\nCode:\n```html\n<script>\nimport { Router, Link, Route, navigate } from \"svelte-routing\"\nimport Login from \"./Login.svelte\"\nimport Somewhere from \"./Somewhere.svelte\"\nimport Home from \"./Home.svelte\"\n\nlet user = null\nvar previousPath\n\n$: user\n\nfunction logout() {\n localStorage.clear()\n user = null\n navigate(\"/\")\n}\n\nfunction loggedIn (event) {\n if (event) {\n user = { name: \"George\" }\n navigate(previousPath, { replace: true })\n }\n}\n\nfunction loggingIn() {\n previousPath = window.location.pathname\n}\n\n</script>\n\n<Router>\n <h1>Test Login</h1>\n <nav>\n <Link to=\"/\">Home</Link>\n {#if user === null}\n <Link to=\"/login\" on:click={loggingIn}>Login</Link>\n {:else}\n <Link to=\"/somewhere\">Somewhere</Link>\n <form on:submit={logout}>\n <input type=\"submit\" value=\"Logout\" />\n </form>\n {/if}\n </nav>\n <main>\n {#if user !== null}\n <Route path=\"/somewhere\"><Somewhere /></Route>\n <Route path=\"/\"><Home /></Route>\n {:else}\n <p>Please login</p>\n <Route path=\"/login\"><Login on:loggedIn={loggedIn} /></Route>\n {/if}\n </main>\n</Router>\n```\n\n```html\n<p>Yellow!</p>\n```\n\n```html\n<script>\nimport { createEventDispatcher } from \"svelte\";\n\nconst dispatch = createEventDispatcher()\n\nfunction submit() {\n dispatch(\"loggedIn\", true)\n}\n</script>\n\n<form on:submit={submit}>\n <input type=\"submit\" value=\"Submit\" />\n</form>\n```\n\n```html\n<p>Somewhere!</p>\n```\n\n```text\nsvelte-routing\n```\n\n```text\nnavigate\n```\n\n```text\nApp.svelte\n```\n\n```text\nRoute\n```\n\n```text\nif-else\n```\n\n```text\nmain\n```\n\n```text\n/somewhere\n```\n\n```text\n/somewhere\n```\n\n```text\nSomewhere\n```\n\n```text\nSomewhere\n```\n\n```text\nHome.svelte\n```\n\n```text\nLogin.svelte\n```\n\n```text\nSomewhere.svelte\n```\n\n```js\nimport { tick } from \"svelte\"\n\n...\n\nasync function loggedIn (event) {\n if (event) {\n user = { name: \"George\" }\n await tick()\n navigate(previousPath, { replace: true })\n }\n}\n```\n\n```text\ntick\n```\n\n```text\ntick\n```\n\n```text\nuser\n```\n\n```text\n{:else}\n```\n\n```text\nRoute\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":268,"estimatedTokens":990}}754{"id":"stack-58148126","source":"stackoverflow","questionId":58148126,"title":"Passing props from a component and the components in a slot","tags":["svelte"],"text":"Title: Passing props from a component and the components in a slot\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nA responsive NavBar component uses NavLink components like this:\n\n```\n\n import NavBar from './nav/NavBar.svelte';\n import NavLink from './nav/NavLink.svelte';\n let barsMenu = false;\n\n \n \n\n```\n\nThe NavLink components require the barsMenu prop. The NavLink components are part of the NavBar slot like this:\n\n```\n\n export let logo = '';\n export let barsMenu = false;\n\n {logo}\n \n barsMenu = !barsMenu}\">\n **\n \n\n```\n\nIs it possible for the NavBar component to pass the barsMenu prop straight down the slot to the NavLink components?\n\n========================================\n\nCode:\n```html\n<script>\n import NavBar from './nav/NavBar.svelte';\n import NavLink from './nav/NavLink.svelte';\n let barsMenu = false;\n</script>\n\n<NavBar logo=\"LOGO\" bind:barsMenu={barsMenu}>\n <NavLink text=\"About\" barsMenu={barsMenu}></NavLink>\n <NavLink text=\"Contact\" barsMenu={barsMenu}></NavLink>\n</NavBar>\n```\n\n```html\n<script>\n export let logo = '';\n export let barsMenu = false;\n</script>\n\n<div class=\"navbar\" class:responsive=\"{barsMenu}\">\n <a class=\"logo\" href=\"javascript:;\">{logo}</a>\n <slot></slot>\n <a class=\"bars\" href=\"....\" on:click=\"{() => barsMenu = !barsMenu}\">\n <i class=\"fa fa-bars\"></i>\n </a>\n</div>\n```\n\n```html\n<slot barsMenu={ barsMenu }></slot>\n```\n\n```html\n<NavBar logo=\"LOGO\" let:barsMenu={ barsMenu }>\n```\n\n```text\nslot\n```\n\n```text\nlet:\n```\n\n========================================\n\nComments:\n- Thnx. I missed the : after the let:... before.","metadata":{"transformedAt":"2026-08-18T18:33:40.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":86,"estimatedTokens":393}}755{"id":"stack-77346263","source":"stackoverflow","questionId":77346263,"title":"How to use $app/navigation inside the vitest unit test","tags":["reactjs","svelte","vite","sveltekit","vitest"],"text":"Title: How to use $app/navigation inside the vitest unit test\nTags: reactjs, svelte, vite, sveltekit, vitest\nSource: Stack Overflow\n\nQuestion:\nGetting this error in files where I am using $app/navigation:\n`Error: Failed to resolve import \"$app/navigation\" from \"src/utils/navigationUtils.js\". Does the file exist?`.\n\nHere is my setupTests.js file but now getting the same error in this file.\n\n```\nimport \"@testing-library/jest-dom\";\nimport { vi } from \"vitest\";\nimport * as navigation from \"$app/navigation\";\n\n// Mock SvelteKit runtime module $app/navigation\nvi.mock(\"$app/navigation\", () => ({\n afterNavigate: () => {},\n beforeNavigate: () => {},\n disableScrollHandling: () => {},\n goto: () => Promise.resolve(),\n invalidate: () => Promise.resolve(),\n invalidateAll: () => Promise.resolve(),\n prefetch: () => Promise.resolve(),\n prefetchRoutes: () => Promise.resolve(),\n}));\n```\n\nAfter this configration now getting:\n`Error: Failed to resolve import \"$app/navigation\" from \"setupTests.js\". Does the file exist?`\n\nI have tried to mock the `$app/navigation` module in setupTests.js file but no success.\n\n========================================\n\nTop Answer:\nThx this worked for me! @possum\nMy folder-structure is:\n\n**mocks**/app/navigation.js\n\nAnd this is the code i wrote to mock:\n\n\r\n\r\n\n```\nimport { vi } from 'vitest';\n\nconst goto = vi.fn();\nconst invalidate = vi.fn();\nconst invalidateAll = vi.fn();\n\nmodule.exports = {\n goto,\n invalidate,\n invalidateAll\n};\n```\n\n========================================\n\nCode:\n```text\nimport \"@testing-library/jest-dom\";\nimport { vi } from \"vitest\";\nimport * as navigation from \"$app/navigation\";\n\n\n// Mock SvelteKit runtime module $app/navigation\nvi.mock(\"$app/navigation\", () => ({\n afterNavigate: () => {},\n beforeNavigate: () => {},\n disableScrollHandling: () => {},\n goto: () => Promise.resolve(),\n invalidate: () => Promise.resolve(),\n invalidateAll: () => Promise.resolve(),\n prefetch: () => Promise.resolve(),\n prefetchRoutes: () => Promise.resolve(),\n}));\n```\n\n```text\nError: Failed to resolve import \"$app/navigation\" from \"src/utils/navigationUtils.js\". Does the file exist?\n```\n\n```text\nError: Failed to resolve import \"$app/navigation\" from \"setupTests.js\". Does the file exist?\n```\n\n```text\n$app/navigation\n```\n\n```text\nresolve: {\n alias: {\n $app: path.resolve(__dirname, '__mocks__/app')\n }\n}\n```\n\n```text\n$xxx\n```\n\n```text\n$env\n```\n\n```text\n$app\n```\n\n```text\n$lib\n```\n\n```text\n__mocks__/xxx\n```\n\n```text\n__mocks__/app\n```\n\n```text\nnavigation.ts\n```\n\n```text\nvitest.config.ts\n```\n\n```js\nimport { vi } from 'vitest';\n\nconst goto = vi.fn();\nconst invalidate = vi.fn();\nconst invalidateAll = vi.fn();\n\nmodule.exports = {\n goto,\n invalidate,\n invalidateAll\n};\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.715Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":147,"estimatedTokens":685}}756{"id":"stack-59981747","source":"stackoverflow","questionId":59981747,"title":"Svelte: How to bind a formatted input field to a property","tags":["binding","number-formatting","getter-setter","svelte","input-field"],"text":"Title: Svelte: How to bind a formatted input field to a property\nTags: binding, number-formatting, getter-setter, svelte, input-field\nSource: Stack Overflow\n\nQuestion:\nFirst of all: Svelte is still new to me. I hope the question is not too trivial. \n\nWithin a simple component I want to use the content of a **formatted input field** for a calculation.\n\nFor example: \n\nIn the input field a Euro amount should be displayed formatted (1.000).\nNext to it a text with the amount plus VAT should be displayed (1.190).\n\nHow I do this **without formatting** is clear to me. The example looks like this:\n\n```\nexport let net;\n export let vat;\n\n $: gross = net + (net * vat / 100);\n $: grossPretty = gross.toLocaleString('de-DE',{ minimumFractionDigits: 0, maximumFractionDigits: 0 });\n```\n\nwith a simple markup like this:\n\n```\n\n Net amount\n \n \n \n Gros = {grossPretty} €\n \n```\n\nIn **vue** i used a computed property. Its **getter** delivers the formatted string and its **setter** takes the formatted string and saves the raw value.\n*(In data() I define net, in the computed properties i define netInput. The input field uses netInput as v-model)*.\n\nIt looks like this:\n\n```\nnetInput: {\n get(){\n return this.net.toLocaleString('de-DE',{ minimumFractionDigits: 0, maximumFractionDigits: 0 });\n },\n set(s){\n s = s.replace(/[\\D\\s._-]+/g, \"\");\n this.net = Number(s);\n }\n}\n```\n\n**How can I handle it in svelte?**\n\n========================================\n\nTop Answer:\nThanks to Stephane Vanraes I found a solution.\n\nIt has not the charm of the vue approach but it's ok. First I inserted 'net_plain'. To have the input field formatted during input, I added an event listener for the keyup event.\n\n```\n\n```\n\nThe event is handled from the function handleKeyUp as follows:\n\n```\nfunction handleKeyUp(event){\n if ( window.getSelection().toString() !== '' ) {\n return;\n }\n // ignore arrow keys\n let arrows = [38,40,37,39];\n if ( arrows.includes( event.keyCode)) {\n return;\n }\n let input = event.target.value.replace(/[\\D\\s._-]+/g, \"\");\n input = input ? parseInt( input, 10 ) : 0;\n event.target.value = ( input === 0 ) ? \"\" : input.toLocaleString( \"de-DE\" );\n }\n```\n\n**BUT**: If anyone has a solution using getter and setter I would appreciate the anwer!\n\n========================================\n\nCode:\n```text\nexport let net;\n export let vat;\n\n $: gross = net + (net * vat / 100);\n $: grossPretty = gross.toLocaleString('de-DE',{ minimumFractionDigits: 0, maximumFractionDigits: 0 });\n```\n\n```text\n<form>\n <label>Net amount</label>\n <input type=\"text\" step=\"any\" bind:value={net} placeholder=\"Net amount\">\n </form>\n <div>\n Gros = {grossPretty} €\n </div>\n```\n\n```text\nnetInput: {\n get(){\n return this.net.toLocaleString('de-DE',{ minimumFractionDigits: 0, maximumFractionDigits: 0 });\n },\n set(s){\n s = s.replace(/[\\D\\s._-]+/g, \"\");\n this.net = Number(s);\n }\n}\n```\n\n```js\nexport let net;\n export let vat;\n $: net_plain = Number(net.replace(/[\\D\\s._-]+/g, \"\"));\n $: gross = net_plain + (net_plain * vat / 100);\n $: grossPretty = gross.toLocaleString('de-DE',{ minimumFractionDigits: 0, maximumFractionDigits: 0 });\n```\n\n```text\n<input type=\"text\" step=\"any\" bind:value={net} on:keyup={handleKeyUp} placeholder=\"Net amount\">\n```\n\n```text\nfunction handleKeyUp(event){\n if ( window.getSelection().toString() !== '' ) {\n return;\n }\n // ignore arrow keys\n let arrows = [38,40,37,39];\n if ( arrows.includes( event.keyCode)) {\n return;\n }\n let input = event.target.value.replace(/[\\D\\s._-]+/g, \"\");\n input = input ? parseInt( input, 10 ) : 0;\n event.target.value = ( input === 0 ) ? \"\" : input.toLocaleString( \"de-DE\" );\n }\n```\n\n========================================\n\nComments:\n- Here's an example using actions that may be helpful: svelte.dev/repl/5c1abf5d24c94960a267124662e11a8d?version=3.4‌​4.2","metadata":{"transformedAt":"2026-08-18T18:33:40.715Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":151,"estimatedTokens":983}}757{"id":"stack-63343948","source":"stackoverflow","questionId":63343948,"title":"How to test svelte input reactivity?","tags":["javascript","jestjs","svelte","svelte-testing-library"],"text":"Title: How to test svelte input reactivity?\nTags: javascript, jestjs, svelte, svelte-testing-library\nSource: Stack Overflow\n\nQuestion:\nI wrote a svelte component `App` in which you can write a sentence in an `input` and the sentence will be render in a `h1`.\n\n**App.svelte**\n\n```\n\n let sentence = \"Hello world\";\n\n \n\n### {sentence}\n\n {\n sentence = value.target.value\n }}\n />\n\n```\n\nBut when I tried to test this behaviour using @testing-library/svelte, the input is not reactive and the text in `h1` is still `\"Hello world\"` (but the value in the input has changed according to the first `expect`).\n\n**App.test.js**\n\n```\nimport { render, fireEvent } from \"@testing-library/svelte\";\nimport App from \"./App.svelte\";\n\nit(\"should write in input\", async () => {\n const { container } = render(App);\n const input = container.querySelector(\"input[type=text]\");\n\n await fireEvent.change(input, { target: { value: \"test\" } });\n\n expect(input.value).toBe(\"test\"); // ✅\n expect(container.querySelector(\"h1\").textContent).toBe(\"test\"); // ❌\n});\n```\n\n**Jest error message:**\n\n```\nExpected: \"test\"\nReceived: \"Hello world\"\n\n 8 | await fireEvent.change(input, { target: { value: \"test\" } });\n 10 | expect(input.value).toBe(\"test\");\n> 11 | expect(container.querySelector(\"h1\").textContent).toBe(\"test\");\n 12 | });\n```\n\nYou can check this behaviour using the codesandbox.\n\nHas someone an idea why this test is failing?\n\n========================================\n\nTop Answer:\nAnd if you import at the beginning of the file:\n\n```\nimport { screen } from '@testing-library/dom'\n```\n\nand at the end you put this:\n\n```\nexpect(\n await screen.findByText('test'),\n ).toBeVisible()\n```\n\n========================================\n\nCode:\n```html\n<script>\n let sentence = \"Hello world\";\n</script>\n\n<main>\n <h1>{sentence}</h1>\n <input\n value={sentence}\n type=\"text\"\n on:input={(value) => {\n sentence = value.target.value\n }}\n />\n\n</main>\n```\n\n```js\nimport { render, fireEvent } from \"@testing-library/svelte\";\nimport App from \"./App.svelte\";\n\nit(\"should write in input\", async () => {\n const { container } = render(App);\n const input = container.querySelector(\"input[type=text]\");\n\n await fireEvent.change(input, { target: { value: \"test\" } });\n\n expect(input.value).toBe(\"test\"); // ✅\n expect(container.querySelector(\"h1\").textContent).toBe(\"test\"); // ❌\n});\n```\n\n```text\nExpected: \"test\"\nReceived: \"Hello world\"\n\n 8 | await fireEvent.change(input, { target: { value: \"test\" } });\n 10 | expect(input.value).toBe(\"test\");\n> 11 | expect(container.querySelector(\"h1\").textContent).toBe(\"test\");\n 12 | });\n```\n\n```text\nApp\n```\n\n```text\ninput\n```\n\n```text\nh1\n```\n\n```text\nh1\n```\n\n```text\n\"Hello world\"\n```\n\n```text\nexpect\n```\n\n```text\nfireEvent.input(...)\n```\n\n```text\nchange\n```\n\n```text\ninput\n```\n\n```text\non:change\n```\n\n```text\nfireEvent\n```\n\n```text\n'input'\n```\n\n```text\nimport { screen } from '@testing-library/dom'\n```\n\n```text\nexpect(\n await screen.findByText('test'),\n ).toBeVisible()\n```\n\n========================================\n\nComments:\n- Just wondering, do you get the same behavior if you use ``?\n- @CarlosRoso Yes I get the same behaviour see here\n- I wonder if that's related to the fact that it's triggering a `change` event when Svelte is subscribed to the `input` event. Try changing it to `on:change` and you'll see the test passing. Now, the ideal situation would be to have `fireEvent` triggering an `'input'` event.\n- @CarlosRoso You're right it's working using `fireEvent.input(...)`. Thanks for your help please write it as an answer so I can validate and upvote it ;)","metadata":{"transformedAt":"2026-08-18T18:33:40.716Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":187,"estimatedTokens":900}}758{"id":"stack-79761922","source":"stackoverflow","questionId":79761922,"title":"Mouse Event Propagation in SvelteUI","tags":["javascript","html","svelte"],"text":"Title: Mouse Event Propagation in SvelteUI\nTags: javascript, html, svelte\nSource: Stack Overflow\n\nQuestion:\nMy Svelte app (SvelteUI) displays a series of elements in grid rows. When you click on a row, it expands using the CSS `display` property. Some rows have controls that are visible whether or not the row is expanded -- buttons, sliders, etc. The issue arises when a `mousedown` occurs on a control and `mouseup` occurs outside the control (clicking on a button and releasing outside the button). The button properly ignores the event, but the event causes the containing row to expand/collapse (which I don't want). I know this is a common issue with mouse events, but with SvelteUI there is a wrinkle because of the way it handles click events. This is also exacerbated by the structure of the app. If someone can point me to a dup that actually has an answer that works, I will happily delete this question.\n\nAn MRE is tough because of the size of the proprietary project, but here's the gist.\n\n### buttonGroup.svelte\n\n```\n\n import {Button, Group} from '@svelteuidev/core'; // SvelteUI `` not html ``\n\n \n {\"do stuff\"}>\n My Button\n \n \n\n```\n\n### objectRows.svelte\n\n```\n\n import Grid from '@svelteuidev/core';\n import buttonGroup from \"./buttonGroup.svelte\";\n import anotherGroup from \"./anotherGroup.svelte\";\n\n function toggleVisibility() {\n if (myElement.style.display === '') {\n myElement.style.display = 'none';\n } else {\n myElement.style.display = '';\n }\n }\n\n \n {toggleVisibility(); open = !open}} on:keydown={() => \"\"}>\n \n Stuff\n \n \n \n \n \n \n \n \n \n ...\n \n \n \n\n```\n\nSo when I click on My Button and drag out before release, it toggles visibility of id `list`.\n\n### What I've Tried\n\n**Stop Propagation:**\nSvelteUI does not honor `stopPropagation` when you try to use it on SvelteUI components -- `on:click|stopPropagation` -- doesn't work, so I tried wrapping the `Button` in a div and tried to capture and stop propagation there. That didn't work either.\n\n**Handling Mouse Events:**\nI've tried adding a series of mouse event handlers to successive divs up the food chain. Didn't work.\n\n**Ignoring Mouse Events:**\nI've tried adding dummy functions to mouse events to have them go nowhere like `on:mouseup={() => {}}`. Didn't work.\n\n### What I Think is Happening\n\nI think the enclosing grid row is seeing the release event as a unique click event which is causing the visibility prop to toggle.\n\n### What I Want to Happen\n\nI want to stop the mouse release event from causing\n\n- the parent grid row from expanding unless the mouse event originated there. Or,\n\n- anything to happen unless the mouse release event occurs within the button (control) SvelteUI component.\n\n========================================\n\nTop Answer:\nSince using `stopPropagation()` is considered bad practice (unless for testing, debugging), there's several ways (I would suggest) to achieve the desired:\n\n### Check if Event landed on an *Action* element\n\none is to check for if the `Event.target.closest()` matches a desired list of action elements selectors and prevent a callback to trigger if it does\n\n```\nconst getActionElementFromEvent = evt => evt.target.closest(`a, button, input, select, textarea, [role=\"button\"]`);\n\nconst rowAction = (evt) => {\n if (getActionElementFromEvent(evt)) return; // Do nothing! an action element was clicked\n evt.currentTarget.classList.toggle(\"is-active\");\n};\n\nconst btnAction = (evt) => {\n evt.currentTarget.classList.toggle(\"is-active\");\n};\n\ndocument.querySelectorAll(\".row\").forEach((elRow) => {\n elRow.addEventListener(\"click\", rowAction);\n});\n\ndocument.querySelectorAll(\".row button\").forEach((elBtn) => {\n elBtn.addEventListener(\"click\", btnAction);\n});\n```\n\n```\n.row {\n background: #eee;\n padding: 1rem;\n margin-bottom: 0.5rem;\n\n &.is-active {\n height: 5rem;\n background: gold;\n }\n \n button {\n &.is-active {\n background: #0bf;\n }\n }\n}\n```\n\n```\n\n 1. Row click (toggles)\n 1. Button click\n\n 2. Row click (toggles)\n 2. Button click\n\n```\n\n### Separate the elements into different (not nested) \"*action zones/areas*\"\n\ndon't nest your button into another action element, just like you would never nest `` inside an `` and *vice-versa*\n\n```\n\n Row toggle\n Button click\n \n\n```\n\nwith one of the two examples above, your problem of:\n\n- the parent grid row from expanding unless the mouse event originated there. Or,\n\n- anything to happen unless the mouse release event occurs within the button\n\nwould be solved.\n\n========================================\n\nCode:\n```js\n<script lang='ts'>\n import {Button, Group} from '@svelteuidev/core'; // SvelteUI `<Button>` not html `<button>`\n</script>\n\n<div>\n <Group>\n <Button on:click={() => {\"do stuff\"}>\n My Button\n </Button>\n </Group>\n</div>\n```\n\n```js\n<script lang='ts'>\n import Grid from '@svelteuidev/core';\n import buttonGroup from \"./buttonGroup.svelte\";\n import anotherGroup from \"./anotherGroup.svelte\";\n\n function toggleVisibility() {\n if (myElement.style.display === '') {\n myElement.style.display = 'none';\n } else {\n myElement.style.display = '';\n }\n }\n</script>\n\n<div>\n <Grid>\n <div id=\"list\" on:click={() => {toggleVisibility(); open = !open}} on:keydown={() => \"\"}>\n <Grid.Col>\n Stuff\n </Grid.Col>\n <Grid.Col>\n <div id=\"controls\">\n <div class=\"button-group\">\n <buttonGroup bind:deviceStore bind:objectStore />\n </div>\n <div class=\"another-group\">\n <anotherGroup bind:deviceStore bind:objectStore />\n </div>\n ...\n </div>\n </Grid.Col>\n </Grid>\n</div>\n```\n\n```text\ndisplay\n```\n\n```text\nmousedown\n```\n\n```text\nmouseup\n```\n\n```text\nlist\n```\n\n```text\nstopPropagation\n```\n\n```text\non:click|stopPropagation\n```\n\n```text\nButton\n```\n\n```text\non:mouseup={() => {}}\n```\n\n```html\n<fieldset onclick=\"out.value+=', wrapper clicked'\">\n <legend>Untreated</legend>\n <button onclick=\"out.value+=', button clicked'\">\n Mouse down here\n </button>\n mouse up here\n</fieldset>\n\n<fieldset\n onclick=\"\n if(this.cancelClick) {\n out.value += ', wrapper IGNORING click'\n this.cancelClick = false\n } else {\n out.value+=', wrapper clicked'\n }\n \">\n <legend>\"Treated\"</legend>\n <button\n onmousedown=\"\n out.value += ', button down'\n this.parentNode.cancelClick = true\n \"\n onclick=\"\n out.value+=', button clicked'\n event.stopPropagation() // this is mainly for for *keyboard* users\n setTimeout(()=>{\n this.parentNode.cancelClick = false\n }, 1)\n \">Mouse down here\n </button>\n mouse up here\n</fieldset>\n\n<output id=\"out\">Events:</output>\n```\n\n```css\n[onclick*=\"\\\\'wrapper\\\\' clicked\"] {\n /*\n Make the container and *other* elements in here containing blocks\n to be raised above the \"glass\":\n */\n :has(> &) ,\n :has(> &) > :not(&) {\n position: relative;\n z-index: 1;\n }\n /*\n The \"glass underlay\":\n */\n &::before {\n content: '';\n position: absolute;\n inset: 0;\n background-color: color-mix(in srgb, mark 20%, transparent); \n }\n &::after {\n content: ' on whole wrapper';\n }\n /*\n Some effects:\n (!) Do *not* use anything what establishes\n containing block (filter, transform, etc) here.\n */\n &:hover {\n background-color: mark;\n color: marktext;\n outline: 5px solid mark;\n }\n &:hover:active {\n background-color: marktext;\n color: mark;\n }\n}\n```\n\n```html\n<fieldset>\n <legend>\n Clickable wrapper without nesting (CSS ~hack)\n </legend>\n <button onclick=\"out.value+=', button clicked'\">\n Mouse down here\n </button>\n mouse up here\n <button onclick=\"out.value+=', \\'wrapper\\' clicked'\"\n aria-label=\"Expand/collapse\">\n ▽/△\n </button>\n</fieldset>\n\n<output id=\"out\">Events:</output>\n```\n\n```text\ncancelClick\n```\n\n```text\ncancelClick\n```\n\n```text\n▽/△\n```\n\n```js\nconst getActionElementFromEvent = evt => evt.target.closest(`a, button, input, select, textarea, [role=\"button\"]`);\n\nconst rowAction = (evt) => {\n if (getActionElementFromEvent(evt)) return; // Do nothing! an action element was clicked\n evt.currentTarget.classList.toggle(\"is-active\");\n};\n\nconst btnAction = (evt) => {\n evt.currentTarget.classList.toggle(\"is-active\");\n};\n\n\ndocument.querySelectorAll(\".row\").forEach((elRow) => {\n elRow.addEventListener(\"click\", rowAction);\n});\n\ndocument.querySelectorAll(\".row button\").forEach((elBtn) => {\n elBtn.addEventListener(\"click\", btnAction);\n});\n```\n\n```css\n.row {\n background: #eee;\n padding: 1rem;\n margin-bottom: 0.5rem;\n\n &.is-active {\n height: 5rem;\n background: gold;\n }\n \n button {\n &.is-active {\n background: #0bf;\n }\n }\n}\n```\n\n```html\n<div class=\"row\">\n 1. Row click (toggles)\n <button type=\"button\">1. Button click</button>\n</div>\n<div class=\"row\">\n 2. Row click (toggles)\n <button type=\"button\">2. Button click</button>\n</div>\n```\n\n```html\n<div class=\"row\">\n <button type=\"button\" class=\"row-toggle-btn\">Row toggle</button>\n <button type=\"button\" class=\"something-else-btn\">Button click</button>\n <!-- ...other markup -->\n</div>\n```\n\n```text\nstopPropagation()\n```\n\n```text\nEvent.target.closest()\n```\n\n```text\n<button>\n```\n\n```text\n<a>\n```\n\n========================================\n\nComments:\n- ``)? If I'm guessing right, here: `` - which is not in your example.\n- Also, your 5 lines of `myElement.style.display` code are an antipattern. You should avoid toggling CSS properties from JavaScript, instead a better practice is by using just 1 single line of JS: `myElement.classList.toggle(\"someClass\", optionalBooleanState)` - and you set the styles where expected, and that's in your stylesheet `.someClass {}` rules.\n- Also, (as suggested in an answer) avoid the use of `stopPropagation()` (unless for debugging). In web development almost no-one will use the Event's capturing phase, therefore `Event.stopPropagation()` can only lead to issues globally and app-wise. Imagine that on app click you want to close an opened modal. And say a user clicked an element that used stopPropagation(). Congrats!: It'll never close. An app, its code, and third party JavaScript should be always aware, able to register, Events happening during their lifecycle.\n- @RokoC.Buljan Thanks for the feedback. With respect to your first one, that is actually a `class` in my code (not an `id`). I changed it in an edit to help direct the reader to the line in question.\n- Thanks for taking the time to provide an answer; I'm grateful. Your code snippet behaves precisely the way I need (ignoring the click outside the element). I understand completely the point you're making about accessibility and I will take your advice to heart about refactoring. It will come at a styling cost, but that might be unavoidable.\n- FYI - I decided to add a sibling button to control the visibility of the parent element and this has solved my issue. I can click and drag off a button (nothing happens), click and release on top of the sibling button (nothing happens), but when I click the sibling button, the element expands. I went with a chevron for the button so it's both non-intrusive and hopefully intuitive.\n- @DaveL17 Thanks, I'm really glad it helped. For completeness, I've added some CSS-based demo emulating (\"restoring\") the original \"click anywhere in the row to trigger some action\" functionality with that latter advised \"sibling buttons\" approach, that could possibly come in handy. (Well, it is maybe more a hack, but I thought it could be worth mentioning.)\n- The snippet does not seem to address the pesky \"drag\" border-case of expected cancellation of the \"row\" click handler when performed by mouse pressed on the button, moved out, and released in the row OP needed.\n- Thanks for taking the time to provide a solution. I accepted @myf 's answer because it was helpful in finding a solution. That solution was to avoid the nested event handlers and instead use a button to trigger the expansion--which is what I have done.","metadata":{"transformedAt":"2026-08-18T18:33:40.716Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":444,"estimatedTokens":2972}}759{"id":"stack-78427221","source":"stackoverflow","questionId":78427221,"title":"Unit testing code that fires at the end of the intro animation in Svelte","tags":["svelte","jsdom","vitest","testing-library","svelte-testing-library"],"text":"Title: Unit testing code that fires at the end of the intro animation in Svelte\nTags: svelte, jsdom, vitest, testing-library, svelte-testing-library\nSource: Stack Overflow\n\nQuestion:\nI created a Svelte component that is meant to show quickly and then disappear, merely to communicate that the action took place and how many records were touched by the action.\n\nThe component is very simple, and here is a simplified version:\n\n```\n\n import { type ShowStore } from \"my-library\";\n import { fade, blur } from 'svelte/transition';\n\n export let text: string;\n export let showStore: ShowStore;\n export let timeout = 500;\n\n function setExit() {\n console.log('setExit executed.');\n setTimeout(() => showStore.hide(), timeout);\n }\n\n {text}\n\n```\n\nThe CSS classes seen there are Bootstrap and are meant to show the element in the middle of the screen.\n\nNow, using **Vitest**, I would like to write a unit test that makes sure the component hides itself after the specified timeout via the `timeout` prop. This does not seem to be working. The `console.log()` line seen inside the `setExit()` function doesn't happen, which makes me question if, while in the test environment, transitions happen: If `setExit()` is not being called, then intro animation is not finishing, right?\n\nBefore I show the unit test, I'll say this much about `ShowStore`: It is a utility Svelte store that holds a Boolean value and has the specialized methods `show()`, `hide()`, and `toggle()`. Other than that, is a Svelte store created with `writable()`.\n\nThe unit test looks like this:\n\n```\ntest('Should hide itself after the specified timeout value.', async () => {\n // Arrange.\n const text = '+123';\n const store = showStore();\n store.show();\n const timeout = 300;\n render(SwiftScore, { text, showStore: store, timeout });\n const spy = vi.spyOn(store, 'hide');\n\n // Act.\n await vi.waitFor(() => {\n console.log('Show value: %s', get(store));\n if (get(store)) {\n return Promise.reject();\n }\n }, timeout + 300);\n\n // Assert.\n expect(spy).toHaveBeenCalledOnce();\n expect(get(store)).toEqual(false);\n });\n```\n\nI am using `@testing-library/svelte`, `jsDom` and `Vitest`.\n\n**Can code triggered by animation-related events be unit-tested?**\n\n========================================\n\nCode:\n```html\n<script lang=\"ts\">\n import { type ShowStore } from \"my-library\";\n import { fade, blur } from 'svelte/transition';\n\n export let text: string;\n export let showStore: ShowStore;\n export let timeout = 500;\n\n function setExit() {\n console.log('setExit executed.');\n setTimeout(() => showStore.hide(), timeout);\n }\n</script>\n\n<div\n class=\"rounded-5 display-2 p-5 translate-middle fw-bold top-50 start-50\"\n in:blur={{ duration: 200 }}\n out:fade\n on:introend={setExit}\n>\n {text}\n</div>\n```\n\n```js\ntest('Should hide itself after the specified timeout value.', async () => {\n // Arrange.\n const text = '+123';\n const store = showStore();\n store.show();\n const timeout = 300;\n render(SwiftScore, { text, showStore: store, timeout });\n const spy = vi.spyOn(store, 'hide');\n\n // Act.\n await vi.waitFor(() => {\n console.log('Show value: %s', get(store));\n if (get(store)) {\n return Promise.reject();\n }\n }, timeout + 300);\n\n // Assert.\n expect(spy).toHaveBeenCalledOnce();\n expect(get(store)).toEqual(false);\n });\n```\n\n```text\ntimeout\n```\n\n```text\nconsole.log()\n```\n\n```text\nsetExit()\n```\n\n```text\nsetExit()\n```\n\n```text\nShowStore\n```\n\n```text\nshow()\n```\n\n```text\nhide()\n```\n\n```text\ntoggle()\n```\n\n```text\nwritable<boolean>()\n```\n\n```text\n@testing-library/svelte\n```\n\n```text\njsDom\n```\n\n```text\nVitest\n```\n\n```text\njsdom\n```\n\n```text\nenvironment\n```\n\n```text\nhappy-dom\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":174,"estimatedTokens":952}}760{"id":"stack-76066173","source":"stackoverflow","questionId":76066173,"title":"SvelteKit cookies disappearing upon site refresh, and returning the old value after an irrelevant API call","tags":["javascript","svelte","sveltekit"],"text":"Title: SvelteKit cookies disappearing upon site refresh, and returning the old value after an irrelevant API call\nTags: javascript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am revamping my website using svelte(kit), but running into a very strange issue, whenever /api/signup/delivercode is called with a correct code, an account cookie is set, with no time expiry, when I refresh the page, the cookie disappears, and then when I send a request to /api/signup after it disappeared, the OLD cookie reappears (at this point there isn't supposed to be any cookie yet (keep in mind it only appears when the signup api is called), only once the delivercode endpoint is triggered. Does anyone have any idea what could be going wrong and why?\n\nhttps://streamable.com/amc9t4\n/api/signup endpoint:\n\n```\nexport const POST = async (event) => {\n // more code\n let response = await schemas.account.create(info).then(() => apiConsts.mail(event.cookies, info)) // I made sure with ctrl+f, this is the ONLY line where cookies are mentioned\n // more code\n}\n```\n\napiConsts.mail function:\n\n```\nmail: async (cookies, data, signup) => { // should move entire mail-code system to redis instead of mongo\n // more code\n cookies.set(`concode`, browserCode, { httpOnly: true, sameSite: `strict`, maxAge: 1000 * 60 * 30 }) // same here, this is the only place where the cookies object is mentioned\n // more code\n },\n```\n\ndespite the fact that that those are the only locations where cookies are referenced in my code, the /api/signup sends an `account` cookie as well (see in first attached image), the cookie value is one that my code set beforehand (you can check the timeid, the first number in the start is the date in ms when it was created), it was just not visible in my browser nor with `event.cookies.get()` meanwhile, and it disappears again when I refresh (second attached video)\n\nhttps://streamable.com/v6a27g\n\nhttps://i.sstatic.net/1aXkF.png\n\nAm I doing something wrong? Or is this a SvelteKit bug?\n\n========================================\n\nCode:\n```js\nexport const POST = async (event) => {\n // more code\n let response = await schemas.account.create(info).then(() => apiConsts.mail(event.cookies, info)) // I made sure with ctrl+f, this is the ONLY line where cookies are mentioned\n // more code\n}\n```\n\n```js\nmail: async (cookies, data, signup) => { // should move entire mail-code system to redis instead of mongo\n // more code\n cookies.set(`concode`, browserCode, { httpOnly: true, sameSite: `strict`, maxAge: 1000 * 60 * 30 }) // same here, this is the only place where the cookies object is mentioned\n // more code\n },\n```\n\n```text\naccount\n```\n\n```text\nevent.cookies.get()\n```\n\n```text\npath\n```\n\n```text\n/\n```\n\n```text\ncookies.set\n```\n\n========================================\n\nComments:\n- Do you have a `hooks.server.js` file? The cookie is probably set there.\n- I do not have any such file, the only files that should be interacting at the time where the cookies suddenly re-appear are the `/api/signup` endpoint and the `apiConsts.mail` function.\n- Provided info is not adequate to diagnose the problem. Don't just rely on devtools' cookie panel, you should also find the network request with the cookie setting/unsetting header. Also, use incognito mode or another browser to test if you can reproduce, so to make sure this problem is caused by sveltekit, cus it could also be caused by a browser extension.\n- @hackape the behaviour is identical in incognito, the first time it works okay, but as soon as the page redirects/refreshes the cookies disappear. The next time one is logging in, the old account cookie reappears before it's interacted with by my code. (Also, note that I did check the requests that set the cookies, which you can see in my screenshot and my recordings)\n- I can’t see text clearly in the video. Anyway, I’m willing to help, but just don’t know how to proceed. Not enough info is all I said. Are you willing to your codebase or what?\n- And since you did look into the request, what have you found unusual after hitting the reload button? The first response after reload must have some http headers that reset your cookies.\n- Oh! I checked the opposite of that, not where they were reset, oops! However I found the issue, will leave it as an answer below.","metadata":{"transformedAt":"2026-08-18T18:33:40.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":85,"estimatedTokens":1083}}761{"id":"stack-74127146","source":"stackoverflow","questionId":74127146,"title":"How does a SvelteKit load function access local storage, when it runs on server side?","tags":["svelte","sveltekit"],"text":"Title: How does a SvelteKit load function access local storage, when it runs on server side?\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nWhen visiting a deep link in my app, the component related to the deep link is the first page to be rendered, so I think its SvelteKit load function must run **on server side**, is that correct?\n\nIf yes, I wonder how does the load function access local storage? It needs data from local storage like user credentials, tokens and so on.\n\nI tried, but it seems that it has access to load function **only when** it runs on **client side**, not on server side.\n\nThanks in advance!\n\n========================================\n\nCode:\n```text\nlocalStorage\n```\n\n```text\nload\n```\n\n```text\nLoadEvent\n```\n\n```text\nServerLoadEvent\n```\n\n```text\nclientAddress\n```\n\n```text\ncookies\n```\n\n```text\nlocals\n```\n\n```text\nplatform\n```\n\n```text\nrequest\n```\n\n```text\nRequestEvent\n```\n\n========================================\n\nComments:\n- So, the `load` function doesn't have access to local storage, but have access to `cookies`, is that correct? Sorry but I still don't understand how to access local storage. Could you elaborate a little further?\n- On the server it has access to cookies (`+page.server.js/ts`), if you define it in `+page.js/ts` it will run both on the client and on the server and it will not have access to cookies on the client. When it runs on the client you could access `localStorage`, but you should then make sure to not do so on the server. There probably is little point in doing so, though, because then the function behaves inconsistently.\n- To summerize it, as long as the `load` function runs on the server side, which is the case when visiting via a deep link, it does not have access to either cookies or local storage. Is this understanding correct?\n- You can simply ensure that it only runs on the server by defining it in `+page.server.js/ts`, that way it does not matter from where the page is accessed. And as stated, cookies can only be accessed on the server, local storage can only be accessed on the client.\n- Using HTTP-only cookies means you have to worry about CSRF attacks which you don't have to worry about if you store your tokens in localstorage. So it's a question of would you rather worry third party scripts stealing tokens or would you rather worry about protecting all of your endpoints against CSRF attacks. I wouldn't so adamantly say that storing tokens in localstorage is bad.\n- @hostingutilities.com CSRF is not that much of an issue any more. Most browsers will not just send credentials like they used to when the request comes from a different domain. (See `SameSite`, which should have reasonable defaults and can be set to be sure.)","metadata":{"transformedAt":"2026-08-18T18:33:40.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":65,"estimatedTokens":685}}762{"id":"stack-76979535","source":"stackoverflow","questionId":76979535,"title":"Images not showing in capacitor svelte app","tags":["javascript","svelte","capacitor"],"text":"Title: Images not showing in capacitor svelte app\nTags: javascript, svelte, capacitor\nSource: Stack Overflow\n\nQuestion:\nI'm trying to port my svelte app into capacitor to make it a mobile app. I was able to create an android build and run it on my phone and on my android emulator, the problem is that the images are not showing.\n\nhttps://i.sstatic.net/vjlOp.png\n\nTo give you some context my app is pretty much a random image generator, pulling a different image from a remote url every time you click a button. The images are showing on the web no problem, but for some reason in my phone and on android emulator they don't work.\n\nI don't know if this is relevant but the images come from an http address and not https, I think the issue is probably to do with permissions of some kind but I don't know what configuration to change. This is my `capacitor.config.ts` file:\n\n```\nimport { CapacitorConfig } from '@capacitor/cli';\n\nconst config: CapacitorConfig = {\n appId: 'com.moviesapp.chrispoulsen',\n appName: 'movies-app',\n webDir: 'build',\n};\n\nexport default config;\n```\n\nThanks to anyone who can help me.\n\n========================================\n\nCode:\n```js\nimport { CapacitorConfig } from '@capacitor/cli';\n\nconst config: CapacitorConfig = {\n appId: 'com.moviesapp.chrispoulsen',\n appName: 'movies-app',\n webDir: 'build',\n};\n\nexport default config;\n```\n\n```text\ncapacitor.config.ts\n```\n\n```text\nhttp\n```\n\n```text\nhttps\n```\n\n```text\nhttp\n```\n\n========================================\n\nComments:\n- Yeah I thought so, could you elavorate on how to allow http traffic?\n- I was able to change the request to https and it worked! But I would also like to know how to allow http requests for future reference\n- Well, that's not really Capacitor specific and there are several answers already in stack overflow. Android: stackoverflow.com/questions/45940861/… iOS: stackoverflow.com/a/57465110/19796642\n- Okay, so there's no way to configure that directly from capacitor?\n- no, there is no capacitor configuration for this since it's not a capacitor thing but a OS thing, at some point Apple and Google decided http was not secure and they will not load http content unless the app is explicitly configured to do it","metadata":{"transformedAt":"2026-08-18T18:33:40.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":66,"estimatedTokens":556}}763{"id":"stack-79425047","source":"stackoverflow","questionId":79425047,"title":"sv@0.6.21 not generating a tailwind.config.js file - problem with UI libraries","tags":["tailwind-css","svelte","sveltekit","shadcnui","svelte-5"],"text":"Title: sv@0.6.21 not generating a tailwind.config.js file - problem with UI libraries\nTags: tailwind-css, svelte, sveltekit, shadcnui, svelte-5\nSource: Stack Overflow\n\nQuestion:\nI created my Svelte project using `sv@0.6.21`\n\n```\nnpx sv@0.6.21 create app\n```\n\nAdded the TailwindCSS package\n\n```\nnpx sv@0.6.21 add tailwindcss\n```\n\nAnd then tried to install `shadcn-svelte`\n\n```\nnpx shadcn-svelte@next init\n```\n\nHowever couldn't because there was no `tailwind.config.js` file.\n\nI tried to run the `init` process for TailwindCSS to get a `tailwind.config.js` and it didn't work. I tried to create a config file manually and it didn't work either.\n\nHowever creating a project with `sv@0.6.18` and adding `-initializing` flag the TailwindCSS package solved the problem. I am curious why is that?\n\n========================================\n\nCode:\n```text\nnpx sv@0.6.21 create app\n```\n\n```text\nnpx sv@0.6.21 add tailwindcss\n```\n\n```text\nnpx shadcn-svelte@next init\n```\n\n```text\nsv@0.6.21\n```\n\n```text\nshadcn-svelte\n```\n\n```text\ntailwind.config.js\n```\n\n```text\ninit\n```\n\n```text\ntailwind.config.js\n```\n\n```text\nsv@0.6.18\n```\n\n```text\n-initializing\n```\n\n```text\nnpm install tailwindcss@3\n```\n\n```js\nimport { defineConfig } from 'vite'\nimport { sveltekit } from '@sveltejs/kit/vite'\nimport tailwindcss from '@tailwindcss/vite'\n\nexport default defineConfig({\n plugins: [\n tailwindcss(),\n sveltekit(),\n ],\n css: {\n transformer: 'lightningcss'\n }\n});\n```\n\n```css\n@import \"tailwindcss\";\n```\n\n```text\nnpm install tailwindcss\n```\n\n```text\nnpm install tailwindcss\n```\n\n```text\nnpm install tailwindcss@3\n```\n\n```text\nshadcn-ui/ui\n```\n\n========================================\n\nComments:\n- A few days ago, Shadcn officially started supporting TailwindCSS v4; See: `shadcn-ui/ui` #6427 and Shadcn UI with TailwindCSS v4","metadata":{"transformedAt":"2026-08-18T18:33:40.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":116,"estimatedTokens":454}}764{"id":"stack-78098588","source":"stackoverflow","questionId":78098588,"title":"How to animate Svelte component on page load without causing a layout shift","tags":["svelte","svelte-transition"],"text":"Title: How to animate Svelte component on page load without causing a layout shift\nTags: svelte, svelte-transition\nSource: Stack Overflow\n\nQuestion:\n### Problem\n\nI would like to animate a header once the landing page of my SvelteKit app is loaded, causing each letter of the heading to appear one slightly after the other, but all the solutions I've found for this either require some things that feel hacky and make TypeScript upset or result in layout shift.\n\n### Simplified Structure of heading I'm wanting to animate\n\n```\n\n CAT\n \n```\n\n### Solutions so far:\n\n- \"Translation\" of how I would do it in vanilla JS (seems hacky)\n\n- Svelte transitions (causes layout shift)\n\n- pure CSS (seems like the simplest and most effective to me)\n\n**I'm hoping to see if there's a more \"Svelte-y\" way of achieving the effect without negative side-effects.**\n\n### How I would do this in vanilla JS\n\nIn vanilla JS, I would simply use css to set the `` element's opacity to zero and give its opacity a transition value. Then I would define a class that sets opacity to 1. In my script, I would my set an interval on page load that incrementally adds a class to the `` elements within the heading. That way, each letter would appear in succession and fade into view, and there would be no layout shift.\n\n### Svelte \"translation\" of above approach makes TypeScript upset\n\nTransferring the above vanilla JS approach to Svelte introduces a few weird things:\n\n- I have to bind the Component's top-most element to a variable (`root`) in order to query things inside it (seems hacky, so there's got to be something I don't understand; normally I would just use `document.querySelectorAll()`, but that apparently isn't the way to do it in Svelte).\n\n- TypeScript gets mad at the `root` variable, but I wouldn't begin to know what type to assign it.\n\n### Component's Code\n\n```\n\n import { onMount } from \"svelte\";\n let root;\n \n const lettersWithClasses = { C: 'red', A: 'green', T: 'orange' };\n \n const animateHeading = function(letters) {\n letters.forEach((span, i) => {\n setTimeout(() => {\n span.classList.add(\"viz\")\n }, i * 400 + 1000);\n });\n }\n \n onMount(() => {\n let headingLetters = root.querySelectorAll(\"#heading > span\");\n animateHeading(headingLetters);\n });\n \n \n \n \n {#each Object.entries(lettersWithClasses) as [key, value], i}\n {key}\n {/each}\n \n \n \n \n h1 > span {\n opacity: 0;\n transition: opacity 1s ease-in;\n }\n .viz {\n opacity: 1 !important;\n }\n .red { color: red; }\n .green { color: green; }\n .orange { color: orange; }\n \n```\n\n### Using Svelte Transitions (causes layout shift)\n\nThis seems like a more Svelte-y way of achieving my goal (see use of the `fade` Svelte transition), but it results in layout shift :(\n\nAlso, it seems really hacky the way I'm changing the value of this `ready` variable via `onMount` but it's necessary in order to get the transition to run once the page is loaded (maybe it shouldn't be considered \"hacky\" though since Rich Harris is who suggested this method).\n\nWhat is for sure is that layout shift = bad\n\n```\n\n import { onMount } from \"svelte\";\n import { fade } from \"svelte/transition\";\n const lettersWithClasses = { C: 'red', A: 'green', T: 'orange' };\n\n let ready = false;\n onMount(() => ready = true);\n \n \n \n {#if}\n \n {#each Object.entries(lettersWithClasses) as [key, value], i}\n {key}\n {/each}\n \n {/if}\n \n \n \n .red {\n color: #f70702;\n }\n .green {\n color: #398c31;\n }\n .orange {\n color: #f27202;\n }\n \n```\n\nI've thought about adding a hard-coded `` after the closing `{/each}` tag and giving it a class that makes it have a visibility of \"hidden\", but that seems hacky to me too.\n\n### Just CSS\n\nWould it be better to just use CSS keyframes to do all this? By \"better\" I mean both less complicated for me as the developer and less computationally expensive for the client. Or is there a \"better\" way that is sort of more baked-in to Svelte?\n\n### example of how to do all this with CSS\n\nJust assign each `` a different class and then @keyframes and animation to run the transition. Btw, this CSS method was the only method to fetch a perfect 100 lighthouse score in all categories.\n\n```\n\n const lettersWithClasses = { C: 'red', A: 'green', T: 'orange' };\n \n \n \n \n {#each Object.entries(lettersWithClasses) as [key, value], i}\n {key}\n {/each}\n \n \n \n \n @keyframes fadeinto-red {\n from { opacity: 0; color: #white; }\n to { opacity: 1; color: red; }\n }\n @keyframes fadeinto-green {\n from { opacity: 0; color: white; }\n to { opacity: 1; color: green; }\n }\n @keyframes fadeinto-orange {\n from { opacity: 0; color: white; }\n to { opacity: 1; color: orange; }\n }\n span.red{\n animation: fadeinto-red 1.8s ease-in-out both;\n }\n span.green{\n animation: fadeinto-green 1.8s ease-in-out 0.4s both;\n }\n span.orange{\n animation: fadeinto-orange 1.8s ease-in-out 0.8s both;\n }\n \n```\n\n========================================\n\nCode:\n```html\n<h1>\n <span>C</span><span>A</span><span>T</span>\n </h1>\n```\n\n```html\n<script>\n import { onMount } from \"svelte\";\n let root;\n \n const lettersWithClasses = { C: 'red', A: 'green', T: 'orange' };\n \n const animateHeading = function(letters) {\n letters.forEach((span, i) => {\n setTimeout(() => {\n span.classList.add(\"viz\")\n }, i * 400 + 1000);\n });\n }\n \n onMount(() => {\n let headingLetters = root.querySelectorAll(\"#heading > span\");\n animateHeading(headingLetters);\n });\n </script>\n \n <div bind:this={root}>\n <h1 id=\"heading\" class=\"h1 text-center text-[12rem] font-extrabold\">\n {#each Object.entries(lettersWithClasses) as [key, value], i}\n <span\n class=\"{value}\"\n >{key}</span>\n {/each}\n </h1>\n </div>\n \n <style>\n h1 > span {\n opacity: 0;\n transition: opacity 1s ease-in;\n }\n .viz {\n opacity: 1 !important;\n }\n .red { color: red; }\n .green { color: green; }\n .orange { color: orange; }\n </style>\n```\n\n```html\n<script>\n import { onMount } from \"svelte\";\n import { fade } from \"svelte/transition\";\n const lettersWithClasses = { C: 'red', A: 'green', T: 'orange' };\n\n let ready = false;\n onMount(() => ready = true);\n </script>\n \n <div>\n {#if}\n <h1 id=\"heading\" class=\"h1 text-center text-[12rem] font-extrabold\">\n {#each Object.entries(lettersWithClasses) as [key, value], i}\n <span\n in:fade|global={{ delay: 1000 + i * 400, duration: 1000 }}\n class=\"{value}\"\n >{key}</span>\n {/each}\n </h1>\n {/if}\n </div>\n \n <style>\n .red {\n color: #f70702;\n }\n .green {\n color: #398c31;\n }\n .orange {\n color: #f27202;\n }\n </style>\n```\n\n```html\n<script>\n const lettersWithClasses = { C: 'red', A: 'green', T: 'orange' };\n </script>\n \n <div>\n <h1 id=\"heading\" class=\"h1 text-center text-[12rem] font-extrabold\">\n {#each Object.entries(lettersWithClasses) as [key, value], i}\n <span\n class=\"{value}\"\n >{key}</span>\n {/each}\n </h1>\n </div>\n \n <style>\n @keyframes fadeinto-red {\n from { opacity: 0; color: #white; }\n to { opacity: 1; color: red; }\n }\n @keyframes fadeinto-green {\n from { opacity: 0; color: white; }\n to { opacity: 1; color: green; }\n }\n @keyframes fadeinto-orange {\n from { opacity: 0; color: white; }\n to { opacity: 1; color: orange; }\n }\n span.red{\n animation: fadeinto-red 1.8s ease-in-out both;\n }\n span.green{\n animation: fadeinto-green 1.8s ease-in-out 0.4s both;\n }\n span.orange{\n animation: fadeinto-orange 1.8s ease-in-out 0.8s both;\n }\n </style>\n```\n\n```text\n<h1>\n```\n\n```text\n<span>\n```\n\n```text\nroot\n```\n\n```text\ndocument.querySelectorAll()\n```\n\n```text\nroot\n```\n\n```text\nfade\n```\n\n```text\nready\n```\n\n```text\nonMount\n```\n\n```text\n<span>\n```\n\n```text\n{/each}\n```\n\n```text\n<span>\n```\n\n```text\n<script>\n const lettersWithClasses = { C: 'red', A: 'green', T: 'orange' };\n\n function fadeIn(spanElement, index) {\n setTimeout(() => {\n spanElement.style.opacity = 1\n }, index * 400 + 1000);\n }\n</script>\n\n<div>\n <h1 id=\"heading\" class=\"h1 text-center text-[12rem] font-extrabold\">\n {#each Object.entries(lettersWithClasses) as [letter, color], index}\n <span\n style:color={color}\n use:fadeIn={index}\n >\n {letter}\n </span>\n {/each}\n </h1>\n</div>\n\n<style>\n h1 > span {\n opacity: 0;\n transition: opacity 1s ease-in;\n }\n</style>\n```\n\n```text\n<script>\n const lettersWithClasses = { C: 'red', A: 'green', T: 'orange' };\n</script>\n\n<div>\n <h1 id=\"heading\" class=\"h1 text-center text-[12rem] font-extrabold\">\n {#each Object.entries(lettersWithClasses) as [letter, color], i}\n <span\n style=\"--end-color: {color}; --delay: {i*400}ms;\"\n class=\"animate\"\n >{letter}</span>\n {/each}\n </h1>\n</div>\n\n<style>\n @keyframes fadeinto {\n from { opacity: 0; color: white; }\n to { opacity: 1; color: var(--end-color); }\n }\n .animate {\n animation: fadeinto 1.8s ease-in-out var(--delay) both;\n }\n</style>\n```\n\n```text\nstyle:\n```\n\n========================================\n\nComments:\n- This very simple solution resulted in a perfect 100 lighthouse score in all categories just like the pure CSS method I showed in my question, but it is gratefully much less verbose. Thanks! I do wonder how to write the `fadeIn()` function in a way that makes TypeScript happy, but I suppose that's a question for another day.\n- @DevinGilbert I just added a different solution\n- thanks for the pure CSS revision! Works great and still achieves perfect 100 lighthouse score in all categories :)","metadata":{"transformedAt":"2026-08-18T18:33:40.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":416,"estimatedTokens":2565}}765{"id":"stack-77024868","source":"stackoverflow","questionId":77024868,"title":"I don't understand what Svelte docs is trying to say about reactive statements","tags":["svelte","svelte-3"],"text":"Title: I don't understand what Svelte docs is trying to say about reactive statements\nTags: svelte, svelte-3\nSource: Stack Overflow\n\nQuestion:\n### I have taken this from Svelte docs\n\nIt is important to note that the reactive blocks are ordered via simple static analysis at compile time, and all the compiler looks at are the variables that are assigned to and used within the block itself, not in any functions called by them. This means that yDependent will not be updated when x is updated in the following example:\n\n```\n\n let x = 0;\n let y = 0;\n\n /** @param {number} value */\n function setY(value) {\n y = value;\n }\n\n $: yDependent = y;\n $: setY(x);\n\n```\n\nMoving the line $: yDependent = y below $: setY(x) will cause yDependent to be updated when x is updated.\n\n### Refer the Svelte components section in this link https://svelte.dev/docs/svelte-components\n\n### Can someone explain me in detail what the docs is trying to say.\n\nIn the first case when x is changed setY(x) is triggered, which leads to y being changed but yDependent wont change because I understand that compiler will only look at the variables in the reactive blocks and not inside functions the block is calling.\n\nThe same must be true for 2nd case also right ?\n\nI tried both the case and I see that in the first case yDependent stays a constant when x is changing. In the second case yDependent changes when x changes.\n\n========================================\n\nTop Answer:\n```\n$$self.$$.update = () => {\n if ($$self.$$.dirty & /*y*/ 2) {\n $: $$invalidate(2, yD = y);\n }\n if ($$self.$$.dirty & /*x*/ 1) {\n $: setY(x);\n // cant affect yD because of order of compiler output\n }\n };\n\nvs\n\n $$self.$$.update = () => {\n if ($$self.$$.dirty & /*x*/ 1) {\n $: setY(x);\n }\n // y was marked dirty before this so the block can react\n if ($$self.$$.dirty & /*y*/ 2) {\n $: $$invalidate(2, yD = y);\n }\n };\n```\n\nsince the checks happen serially\none dirty marked variable has the power to\naffect the dirty status of all who it\nby running its onupdate statement/expression\nthrough $$invalidate calls\n\n========================================\n\nCode:\n```text\n<script>\n let x = 0;\n let y = 0;\n\n /** @param {number} value */\n function setY(value) {\n y = value;\n }\n\n $: yDependent = y;\n $: setY(x);\n</script>\n```\n\n```text\n$: setY(x); // Dependent on x\n$: yDependent = y; // Dependent on y\n```\n\n```text\nyDependent = y; comes before setY(x);\n```\n\n```js\n$$self.$$.update = () => {\n if ($$self.$$.dirty & /*y*/ 2) {\n $: $$invalidate(2, yD = y);\n }\n if ($$self.$$.dirty & /*x*/ 1) {\n $: setY(x);\n // cant affect yD because of order of compiler output\n }\n };\n\nvs\n\n $$self.$$.update = () => {\n if ($$self.$$.dirty & /*x*/ 1) {\n $: setY(x);\n }\n // y was marked dirty before this so the block can react\n if ($$self.$$.dirty & /*y*/ 2) {\n $: $$invalidate(2, yD = y);\n }\n };\n```\n\n========================================\n\nComments:\n- So if a function changes the dependency, then the dependent reactive block will run only if it comes below the reactive block that triggered the function. Right ?","metadata":{"transformedAt":"2026-08-18T18:33:40.716Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":124,"estimatedTokens":786}}766{"id":"stack-75120277","source":"stackoverflow","questionId":75120277,"title":"Is there is way to preserve the state in astro","tags":["routes","svelte","astrojs"],"text":"Title: Is there is way to preserve the state in astro\nTags: routes, svelte, astrojs\nSource: Stack Overflow\n\nQuestion:\nI would really like to know if there is a way of preserving states such as user data between routes in astro. I am also using the svelte framework.\n\nI tried to use svelte stores but does not seem to work. I also tried to implement nano stores but that does not work either.\n\n========================================\n\nCode:\n```text\n@nanostores/persistent\n```\n\n========================================\n\nComments:\n- documentation says that svelte stores actually should work, did you find a solution using it?","metadata":{"transformedAt":"2026-08-18T18:33:40.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":20,"estimatedTokens":156}}767{"id":"stack-77332977","source":"stackoverflow","questionId":77332977,"title":"Empty parameters in SvelteKit load function","tags":["javascript","parameter-passing","svelte"],"text":"Title: Empty parameters in SvelteKit load function\nTags: javascript, parameter-passing, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to build a art portfolio in SvelteKit, following the SvelteKit tutorial. I have a page called `art/`, which has a subdirectory called `[collections]/` for various different collections of art pieces.\n\nI'm temporarily loading data from a file called `data.js` which has the following structure:\n\n```\nexport const collections = [\n {\n title: 'Crisis Vision',\n id: 'crisis-vision',\n content: 'crisis vision content\n\n'\n },\n\n {\n title: 'From the Garden',\n id: 'from-the-garden',\n content: 'from the garden content\n\n'\n },\n \n {\n title: 'As Lost Through Collision',\n id: 'as-lost',\n content: 'as lost content\n\n'\n }\n];\n```\n\nThe `+page.server.js` file in `[collections]/` has the following contents:\n\n```\nimport { error } from '@sveltejs/kit';\nimport { collections } from '../data.js';\n\nexport function load( {params} ) {\n const ret = collections.find((c) => c.id === params.id);\n return { \n ret \n };\n}\n```\n\nThe `+page.svelte` file has the following contents:\n\n```\n\n export let data;\n console.log(JSON.stringify(data))\n\n### {data.ret.title}\n\n{@html data.ret.content}\n```\n\nWhen I try to run this, I get `TypeError: Cannot read properties of undefined (reading 'title')`.\n\nI believe I have narrowed this down to the `params` variable. When I take out `params.id` in the `+page.server.js` file, and directly replace it with an example from the data, say `'as-lost'`, it works as intended as shown here (granted, every collection shows the same content). When I add `console.log(JSON.stringify(data))` to the script portion of the page file, it shows that the params object is empty.\n\nWhat am I doing wrong here? I have tried to the tutorial at every step, and it's still not working. Please help.\n\n========================================\n\nCode:\n```text\nexport const collections = [\n {\n title: 'Crisis Vision',\n id: 'crisis-vision',\n content: '<p>crisis vision content</p>'\n },\n\n {\n title: 'From the Garden',\n id: 'from-the-garden',\n content: '<p>from the garden content</p>'\n },\n \n {\n title: 'As Lost Through Collision',\n id: 'as-lost',\n content: '<p>as lost content</p>'\n }\n];\n```\n\n```text\nimport { error } from '@sveltejs/kit';\nimport { collections } from '../data.js';\n\nexport function load( {params} ) {\n const ret = collections.find((c) => c.id === params.id);\n return { \n ret \n };\n}\n```\n\n```text\n<script>\n export let data;\n console.log(JSON.stringify(data))\n</script>\n\n<h1>{data.ret.title}</h1>\n<div>{@html data.ret.content}</div>\n```\n\n```text\nart/\n```\n\n```text\n[collections]/\n```\n\n```text\ndata.js\n```\n\n```text\n+page.server.js\n```\n\n```text\n[collections]/\n```\n\n```text\n+page.svelte\n```\n\n```text\nTypeError: Cannot read properties of undefined (reading 'title')\n```\n\n```text\nparams\n```\n\n```text\nparams.id\n```\n\n```text\n+page.server.js\n```\n\n```text\n'as-lost'\n```\n\n```text\nconsole.log(JSON.stringify(data))\n```\n\n```text\n[collections]\n```\n\n```text\nparams.collections\n```\n\n========================================\n\nComments:\n- I was bashing my head into the wall trying to figure this out for an hour! Thank you so much!\n- Would recommend using a debugger, then you just inspect all objects in scope. (You can accept answers using the checkmark outline to the side.)","metadata":{"transformedAt":"2026-08-18T18:33:40.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":177,"estimatedTokens":850}}768{"id":"stack-75623586","source":"stackoverflow","questionId":75623586,"title":"Animate elements outside an each block","tags":["css-animations","svelte"],"text":"Title: Animate elements outside an each block\nTags: css-animations, svelte\nSource: Stack Overflow\n\nQuestion:\nI have a simple \"todo list\" style app that uses an `{#each}` block to render a list of `` elements. I'm using Svelte's `animate` directive to make the list items slide up or down when items are added or removed. This works great.\n\nThe issue is that I also have a `` component that's fixed to the bottom of the list of items. Because this is outside the each block, it doesn't get the animation effect, so it immediately jumps up and down when items are added or deleted rather than moving in sync with the list items above.\n\nI tried adding the `animate` directive to the `` but per the Svelte docs, animate can only be used on an element that's the immediate child of a keyed each block, so this doesn't work.\n\nIs there a way to do this using animation in Svelte? And if not, can this effect be achieved using vanilla CSS/JS?\n\nExample REPL (animate duration slowed down to better show the issue)\n\n```\n\n {#each $items as item (item.id)}\n \n \n \n {/each}\n \n\n```\n\nScreenshot of item list with Footer\n\n========================================\n\nCode:\n```text\n<div class=\"items-container\">\n {#each $items as item (item.id)}\n <div animate:flip={{ duration: 200 }}>\n <Item id={item.id} text={item.text} />\n </div>\n {/each}\n <Footer />\n</div>\n```\n\n```text\n{#each}\n```\n\n```text\n<Item />\n```\n\n```text\nanimate\n```\n\n```text\n<Footer />\n```\n\n```text\nanimate\n```\n\n```text\n<Footer />\n```\n\n```text\ntransition:slide\n```\n\n```text\nanimate:flip\n```\n\n```text\ncrossfade\n```\n\n```text\nanimate:flip\n```\n\n```text\n#each\n```\n\n```text\nanimate:flip\n```\n\n========================================\n\nComments:\n- autoAnimate looks like a better fit for my use case. Thanks for the suggestion!","metadata":{"transformedAt":"2026-08-18T18:33:40.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":94,"estimatedTokens":449}}769{"id":"stack-75281283","source":"stackoverflow","questionId":75281283,"title":"Do I have to write catch error in all script when fetching data from server?","tags":["javascript","svelte"],"text":"Title: Do I have to write catch error in all script when fetching data from server?\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI got some question about try, catch of data that is thrown from server using await.\n\nfor example\n\nscript A\n\n```\ntry{\n let a = await get_user_data()\n}\ncatch(err){\n console.log(err)\n}\n```\n\nscript B\n\n```\ntry{\n let b = await get_something()\n}\ncatch(err){\n console.log(err)\n}\n```\n\nLet's just see we have a code like this to get user data, and another script to get something from the server.\nIf the user token is expired, the two scripts will get 401 error(Logged in is required) and If no action is made, it will just end with it.\n\nSo here's my question. Do I have to write all codes on each scripts to do some actions? like if error.respond.status is 401 go to login page, if error.respond.status is 500 do something...\nIs there a better way to know the error has occured in App(.svelte)? or something like global error variable?\n\n========================================\n\nCode:\n```text\ntry{\n let a = await get_user_data()\n}\ncatch(err){\n console.log(err)\n}\n```\n\n```text\ntry{\n let b = await get_something()\n}\ncatch(err){\n console.log(err)\n}\n```\n\n========================================\n\nComments:\n- Are you using sveltekit?\n- no just svelte not svelte kit","metadata":{"transformedAt":"2026-08-18T18:33:40.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":63,"estimatedTokens":325}}770{"id":"stack-43536752","source":"stackoverflow","questionId":43536752,"title":"Svelte class based component example","tags":["javascript","svelte"],"text":"Title: Svelte class based component example\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI'm trying to learn Svelte and TypeScript. I was wondering if there is any pattern to include or program svelte component using ES6 classes. Currently file contains all the script, html and data, css. I want to make them separate files. Please help me!\n\n========================================\n\nCode:\n```text\n.message {\n font-size: 10pt;\n}\n```\n\n```text\n<div class=\"message\">{{message}}</div>\n```\n\n```text\nexport default {\n data: function () {\n return {\n message: 'Hello, world!'\n }\n }\n}\n```\n\n```text\n<style>\n.message {\n font-size: 10pt;\n}\n</style>\n\n<div class=\"message\">{{message}}</div>\n\n<script>\nexport default {\n data: function () {\n return {\n message: 'Hello, world!'\n }\n }\n}\n</script>\n```\n\n```text\nrollup\n```\n\n```text\nrollup-plugin-svelte\n```\n\n```text\nrollup-plugin-buble\n```\n\n========================================\n\nComments:\n- There's an issue to allow separation of input HTML, CSS and JS. The JS would still need to conform to the normal component structure, however — that's how the compiler is able to do its static analysis.\n- Hi @Zac, yeah I think above approach works pretty well. I didn't realize until now, we can combine using gulp different files while still be able to use the new syntax and converting to above format before passing to svelte plugin. Is it also possible to you `gulpfile.js` gulp config ? or `repository` on github ? Would be nice to learn more about it!\n- I would be happy to, I'll post it tomorrow. I ended up needed a few gulp plugins to get it to work well.\n- Awesome, Thanks @Zac. Also, it would be cool, once you upload the repo , better to add the link in the answer and I'll mark as accepted +1\n- @PiyushChauhan Just added the link to a gist. Its here: gist.github.com/ZacBrownBand/3be50d8c36c234960c73e6bdc3a44c6‌​c Let me know if you have any issues, I tried to remove some of the clutter and hope I did not break anything.\n- Thanks @Zac, appreciated :)","metadata":{"transformedAt":"2026-08-18T18:33:40.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":71,"estimatedTokens":512}}771{"id":"stack-76591480","source":"stackoverflow","questionId":76591480,"title":"How to serve a static JS file in SvelteKit?","tags":["javascript","node.js","svelte","sveltekit"],"text":"Title: How to serve a static JS file in SvelteKit?\nTags: javascript, node.js, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a JS file that creates an iframe element and appends it to the body. I am planning on having it be used by other websites as a widget. I have it stored in `src/lib/static/embed.js`. If I am running in dev mode (`yarn dev`) - I can access said script by going to the path name mentioned above. However, if I build this website using `yarn build` - I can no longer access it (it's no where to be found in `build` folder). How can I serve this JS file to the public? Or maybe I am having a wrong approach to begin with?\n\nPS. I am using a node adapter\n\n========================================\n\nCode:\n```text\nsrc/lib/static/embed.js\n```\n\n```text\nyarn dev\n```\n\n```text\nyarn build\n```\n\n```text\nbuild\n```\n\n```text\nstatic\n```\n\n```text\nsrc\n```\n\n```text\n/embed.js\n```\n\n```text\n/embed\n```\n\n========================================\n\nComments:\n- Thanks, this worked great for me! I somehow missed information about the 'static' directory","metadata":{"transformedAt":"2026-08-18T18:33:40.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":48,"estimatedTokens":266}}772{"id":"stack-57700959","source":"stackoverflow","questionId":57700959,"title":"Any way to call a javascript function after Svelte #await :then","tags":["javascript","svelte"],"text":"Title: Any way to call a javascript function after Svelte #await :then\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nIs there any way to call a javascript function after Svelte `#await :then`? What I wanted to do in following code is call a javascript table once I created empty Datatable with some id and then in the javascript just add the data in the Datable. So, basically I wanted to pass `data1` in the javascript function and the id of the DataTable or dataTable element itself. Is there any way I can do this?\n\n```\n\n \n\n### Title\n\n {#await promise}\n loading...\n {:then data}\n {#each data as data1, i}\n \n \n\n ---> I want to call javascript function here which would add data in the given data table. How can I do that?\n {/each}\n {:catch error}\n \n {/await}\n\n```\n\n========================================\n\nCode:\n```text\n<div>\n <h1> Title</h1>\n {#await promise}\n loading...\n {:then data}\n {#each data as data1, i}\n <DataTable id={data1.title}/>\n <br />\n ---> I want to call javascript function here which would add data in the given data table. How can I do that?\n {/each}\n {:catch error}\n <kat-alert header=\"Error\" description={error.message} variant=\"warning\" />\n {/await}\n</div>\n```\n\n```text\n#await :then\n```\n\n```text\ndata1\n```\n\n```text\n{#each data as data1, i}\n <DataTable id={data1.title} data={data1.actualdata}/>\n{/each}\n```\n\n```text\n{#each data as data1, i}\n <DataTable id={data1.title} use:fillTable{data1, data1.title}></DataTable>\n{/each}\n\n<script>\n const fillTable = (el, data, id) => () => {\n // el would be the created element\n // data and id were passed on in the #each\n }\n</script>\n```\n\n```text\nDataTable\n```\n\n========================================\n\nComments:\n- Simple trick if you want to modify the data: stackoverflow.com/a/66080028/9157799","metadata":{"transformedAt":"2026-08-18T18:33:40.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":83,"estimatedTokens":456}}773{"id":"stack-76328274","source":"stackoverflow","questionId":76328274,"title":"Typescript error with SvelteKit and Supabase data fetching (Type 'null' is not assignable to type 'ArrayLike')","tags":["typescript","svelte","sveltekit","supabase"],"text":"Title: Typescript error with SvelteKit and Supabase data fetching (Type 'null' is not assignable to type 'ArrayLike')\nTags: typescript, svelte, sveltekit, supabase\nSource: Stack Overflow\n\nQuestion:\nI have a SvelteKit project set up which authenticates with supabase. I used this guide for that. The authentication and data fetching works fine so far. Actually, in terms of the app itself, everything works as expected. I’m just getting a nasty Typescript error which I can’t get rid of.\n\nI’m fetching the data in this file:\n\n```\n// \n\nimport type { PageLoad } from './$types';\nimport { redirect } from '@sveltejs/kit';\n\nexport const load: PageLoad = async ({ parent }) => {\n const { supabase, session } = await parent();\n if (!session) {\n throw redirect(303, '/');\n }\n\n const { data: playlist } = await supabase.from('playlist').select('*');\n\n return {\n user: session.user,\n playlist\n };\n};\n```\n\nAnd the corresponding svelte file to display it:\n\n```\n\n import type { PageData } from './$types';\n import { json } from '@sveltejs/kit';\n export let data: PageData;\n\n {data.user.email} \n\n \n {#each data.playlist as pl} \n \n {pl.spotify_uri} \n \n {/each}\n \n\n```\n\nNow these are the errors I’m getting:\n\n`'pl' is of type 'unknown'.`\n\nAnd\n\n```\nArgument of type '{ created_at: string; follower_count: number; last_auto_renewal: string; last_manual_renewal: string; playlist_id: number; spotify_uri: string; user_id: string | null; }[] | null' \nis not assignable to parameter of type 'ArrayLike'.\n\nType 'null' is not assignable to type 'ArrayLike'.\n```\n\nBut, as I said, on the webpage everything is displayed just as expected & I’m getting no other errors, it just seems that Typescript isn’t happy. What’s also weird is that the data.user.email thing throws no errors at all.\n\nThe auto-generated types from supabase look like this:\n\n```\n// $lib/supabase/schema.ts\n\nexport interface Database {\n public: {\n Tables: {\n playlist: {\n Row: {\n created_at: string\n follower_count: number\n last_auto_renewal: string\n last_manual_renewal: string\n playlist_id: number\n spotify_uri: string\n user_id: string | null\n }\n...\n```\n\nAnd they seem to get inferred correctly:\n\nIntellisense shows this.\n\nAnd this is my app.d.ts:\n\n```\nimport { SupabaseClient, Session } from '@supabase/supabase-js';\nimport { Database } from '$lib/supabase/schema';\n\ndeclare global {\n namespace App {\n interface Locals {\n supabase: SupabaseClient;\n getSession(): Promise;\n }\n interface PageData {\n session: Session | null;\n }\n // interface Error {}\n // interface Platform {}\n }\n}\n```\n\nWhen searching for the error I found this: https://github.com/sveltejs/language-tools/issues/732 and they talk about some bug in Typescript, but I’m a total Typescript beginner so I have no idea if this is related or what’s going on there.\n\nI expected SvelteKit/Typescript to infer the types for \"data.playlist\" from my schema within the #each loop as well, just like it’s doing within the script tag. Not sure why it’s giving me trouble. Thanks for reading!\n\n========================================\n\nCode:\n```text\n// <!-- routes/playlists/+page.ts -->\n\nimport type { PageLoad } from './$types';\nimport { redirect } from '@sveltejs/kit';\n\nexport const load: PageLoad = async ({ parent }) => {\n const { supabase, session } = await parent();\n if (!session) {\n throw redirect(303, '/');\n }\n\n const { data: playlist } = await supabase.from('playlist').select('*');\n\n return {\n user: session.user,\n playlist\n };\n};\n```\n\n```text\n<!-- routes/playlists/+page.svelte -->\n\n<script lang=\"ts\">\n import type { PageData } from './$types';\n import { json } from '@sveltejs/kit';\n export let data: PageData;\n</script>\n\n<main>\n <div>{data.user.email}</div> <!-- This works fine! -->\n\n <ul>\n {#each data.playlist as pl} <!-- Typescript complains about this -->\n <li>\n {pl.spotify_uri} <!-- and this -->\n </li>\n {/each}\n </ul>\n</main>\n```\n\n```text\nArgument of type '{ created_at: string; follower_count: number; last_auto_renewal: string; last_manual_renewal: string; playlist_id: number; spotify_uri: string; user_id: string | null; }[] | null' \nis not assignable to parameter of type 'ArrayLike<unknown>'.\n\nType 'null' is not assignable to type 'ArrayLike<unknown>'.\n```\n\n```text\n// $lib/supabase/schema.ts\n\nexport interface Database {\n public: {\n Tables: {\n playlist: {\n Row: {\n created_at: string\n follower_count: number\n last_auto_renewal: string\n last_manual_renewal: string\n playlist_id: number\n spotify_uri: string\n user_id: string | null\n }\n...\n```\n\n```text\nimport { SupabaseClient, Session } from '@supabase/supabase-js';\nimport { Database } from '$lib/supabase/schema';\n\ndeclare global {\n namespace App {\n interface Locals {\n supabase: SupabaseClient<Database>;\n getSession(): Promise<Session | null>;\n }\n interface PageData {\n session: Session | null;\n }\n // interface Error {}\n // interface Platform {}\n }\n}\n```\n\n```text\n'pl' is of type 'unknown'.\n```\n\n```js\nconst { data: playlist } = ...\nif (playlist == null)\n throw ...; // or make it a `let` and assign an empty array? \n\n// or\nreturn {\n user: session.user,\n playlist: playlist!,\n};\n```\n\n```text\nnull\n```\n\n```text\ndata\n```\n\n========================================\n\nComments:\n- Thank you so much! For your second solution I got an *A definite assignment assertion '!' is not permitted in this context.* error, but the first solution fixed it. What also works is wrapping the {#each} block in an {#if} block, but fixing it in the page.ts is probably preferrable. (Still no idea how I could’ve inferred that this was the problem from that cryptic error though, even without the *|null* I would’ve assumed that there’s some other mismatch between this *ArrayLike* thing and my data.)\n- The type errors are sometimes, maybe even most of the time, best read bottom to top, it says `Type 'null' is not assignable ...` which usually is an indication that something unexpectedly is returning `null`, you then can work up the tree to see where exactly it's coming from. Reading the errors takes some getting used to, of course.\n- That’s a great tip, thank you again. I’ll try that next time.","metadata":{"transformedAt":"2026-08-18T18:33:40.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":236,"estimatedTokens":1587}}774{"id":"stack-75818532","source":"stackoverflow","questionId":75818532,"title":"Dynamic social sharing cards populated in","tags":["javascript","html","svelte","sveltekit","supabase"],"text":"Title: Dynamic social sharing cards populated in\nTags: javascript, html, svelte, sveltekit, supabase\nSource: Stack Overflow\n\nQuestion:\nI've built a blog website and am trying to implement dynamic social cards for each individual blog. While everything appears to be working properly when I inspect the head element in developer tools, when I do a live test or run the link through social sharing preview tools (such as OpenGraph) my dynamic store variables are undefined.\n\nI'm pulling the data from Supabase and saving it to a store. Here's the code that I'm using in my svelte:head tag:\n\n```\n\n {#await $blogBeingViewed then blog}\n Website - {blog.title}\n \n \n\n \n \n \n \n \n \n\n \n \n \n \n \n \n {/await}\n\n```\n\nAny ideas why I'm experiencing this failure to properly populate my meta tags when attempting to on social media?\n\nI hope that I'm using the proper terminology (I'm just a hobbyist). Feel free to ask any -up questions that would help me to clarify my question.\n\nThank you for your time and assistance.\n\nI've tried multiple variations on the code block shown above, i.e. without \"#await,\" using \"#if,\" etc.\n\n========================================\n\nCode:\n```text\n<svelte:head>\n {#await $blogBeingViewed then blog}\n <title>Website - {blog.title}</title>\n <meta name=\"title\" content=\"{blog.title}\">\n <meta name=\"description\" content=\"{blog.subtitle}\">\n\n <!-- Open Graph / Facebook -->\n <meta property=\"og:type\" content=\"website\">\n <meta property=\"og:url\" content=\"https://www.website.com/article/{blog.id}\">\n <meta property=\"og:title\" content=\"{blog.title}\">\n <meta property=\"og:description\" content=\"{blog.subtitle}\">\n <meta property=\"og:image\" content=\"{blog.image_url}\">\n\n <!-- Twitter -->\n <meta name=\"twitter:card\" content=\"summary_large_image\">\n <meta name=\"twitter:url\" content=\"https://www.website.com/article/{blog.id}\">\n <meta name=\"twitter:title\" content=\"{blog.title}\">\n <meta name=\"twitter:description\" content=\"{blog.subtitle}\">\n <meta name=\"twitter:image\" content=\"{blog.image_url}\">\n {/await}\n</svelte:head>\n```\n\n========================================\n\nComments:\n- Are you using server-side rendering (ssr) or static side generation (ssg) ? When grabbing metadata (e.g. OpenGraph), crawlers don't always parse the javascript. They often only read the static html from the initial server response. The javascript created by Svelte needs to be parsed before those changes are reflected in the DOM. This is applies if you're not using SSR or SSG. If you are using SSR or SSG, it's probably a different issue.\n- Thanks for your response, Pete! I'm using SSR. It's strange to me that everything works properly in the browser, but not when sharing on social media or using a social tool. If it's working properly in the browser, shouldn't it also work properly under other circumstances?\n- No because it might just be a split second before the browser renders all the components, so what you see on the browser doesn't always represent the static HTML on the initial response. My guess would be that it's do with some kind of asynchronous task that's basically moving what would otherwise be rendered on the server to being rendered on the client. I'm not exactly sure of the nuance of that. There might be something in $blogBeingViewed that isn't properly SSR. What I would do is make that whole thing synchronous (remove {#await ...}), use dummy content instead, and see if it renders\n- Then work your way step by step until it stops working. Then hopefully you'll find the culprit. Maybe some kind of API call that isn't being done on the server or something.\n- @Pete, thank you for your assistance. I was able to figure out my error, as seen in my answer below. Your response likely put my thoughts on the right track; when I awoke this morning, the solution was in my head. I appreciate you taking the time to help me and others here on SO.","metadata":{"transformedAt":"2026-08-18T18:33:40.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":76,"estimatedTokens":992}}775{"id":"stack-58071552","source":"stackoverflow","questionId":58071552,"title":"Passing props to svelte component from laravel","tags":["laravel","laravel-blade","svelte"],"text":"Title: Passing props to svelte component from laravel\nTags: laravel, laravel-blade, svelte\nSource: Stack Overflow\n\nQuestion:\nI started learning `svelte` today and I have a problem. Is it possible to pass `props/data` to a `svelte` component through `laravel blade`?\n\nFor example this is how you pass it in `vuejs`:\n\n```\n\n```\n\nI don't understand from where my `svelte` component gets the data beside from `ajax`.\n\nI'm talking here about passing data outside an .svelte component. Not passing from 1 to another .svelte file component. İm asking if you can pass data from an .php file to an component.\n\n========================================\n\nCode:\n```text\n<blog-post post-title=\"hello!\"></blog-post>\n```\n\n```text\nsvelte\n```\n\n```text\nprops/data\n```\n\n```text\nsvelte\n```\n\n```text\nlaravel blade\n```\n\n```text\nvuejs\n```\n\n```text\nsvelte\n```\n\n```text\najax\n```\n\n```text\n<script>\n var data = @json($data);\n</script>\n```\n\n```text\nimport App from './App.svelte';\n\nconst app = new App({\n target: document.body,\n props: {\n name: data.name\n }\n});\n\nexport default app;\n```\n\n```text\n{!! json_encode($data) !!}\n```\n\n```text\nprops\n```\n\n========================================\n\nComments:\n- Try `` I don't think props can be hyphenated\n- Possible duplicate of Passing props down in Svelte","metadata":{"transformedAt":"2026-08-18T18:33:40.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":84,"estimatedTokens":322}}776{"id":"stack-68989872","source":"stackoverflow","questionId":68989872,"title":"Svelte keep default prop value of a child component","tags":["javascript","typescript","svelte","svelte-component"],"text":"Title: Svelte keep default prop value of a child component\nTags: javascript, typescript, svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI have component1 that takes `let text` as a prop and then component2 that does almost the same thing, but I'd like to keep component1 separate for better reusability.\n\nSo I wrapped the comp1 (`Child.svelte`) with comp2 (`Wrapper.svelte`). But how do I keep the default prop value of the Child component without writing it again?\n\nhere is an example:\n\n```\n//Wrapper.svelte\n\n import Child from \"./Child.svelte\";\n export let text = 'hello world'; //need to type the default value again\n\n```\n\n```\n//Child.svelte\n\n export let text = 'hello world';\n\n{text}\n\n```\n\n========================================\n\nTop Answer:\nUse `bind:prop` to create a two way binding. Docs: https://svelte.dev/tutorial/component-bindings\n\n```\n//Wrapper.svelte\n\nimport Child from \"./Child.svelte\";\nexport let text: string\n\n```\n\n========================================\n\nCode:\n```svelte\n//Wrapper.svelte\n<script lang=\"ts\">\n import Child from \"./Child.svelte\";\n export let text = 'hello world'; //need to type the default value again\n</script>\n\n<Child text={text} />\n```\n\n```svelte\n//Child.svelte\n<script lang=\"ts\">\n export let text = 'hello world';\n</script>\n\n<p>{text}</p>\n```\n\n```text\nlet text\n```\n\n```text\nChild.svelte\n```\n\n```text\nWrapper.svelte\n```\n\n```text\n//Wrapper.svelte\n<script lang=\"ts\">\n import Child from \"./Child.svelte\";\n export let text: string = undefined;\n</script>\n\n<Child bind:text />\n```\n\n```text\nProperty 'text' is missing in type '{}' but required in type '{ text: string; }'.ts(2322)\n```\n\n```text\n<Child text={text}/>\n```\n\n```html\n//Wrapper.svelte\n<script lang=\"ts\">\nimport Child from \"./Child.svelte\";\nexport let text: string\n</script>\n\n<Child bind:text />\n```\n\n```text\nbind:prop\n```\n\n========================================\n\nComments:\n- Why do you need this if you just `export let text;` in *Wrapper.svelte* it will be undefined and use the default in the Child.\n- Because if the text prop has no default value and I don't assign that prop from the outside, there will be a typescript error: `Type '{}' is not assignable to type 'IntrinsicAttributes & { text: string;}'. Property 'text' is missing in type '{}' but required in type '{ text: string; }'.ts(2322)`\n- In that case define the type as \"string or undefined\"","metadata":{"transformedAt":"2026-08-18T18:33:40.717Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":113,"estimatedTokens":595}}777{"id":"stack-75750161","source":"stackoverflow","questionId":75750161,"title":"Loading data from parent route fails in route with page using a layout reset","tags":["svelte","sveltekit"],"text":"Title: Loading data from parent route fails in route with page using a layout reset\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nUsing SvelteKit, I'm trying to load data from the parent route's *`+layout.server.ts`* into the current route's *`+page.server.ts`* load function that the *`+page.svelte`* file gets its data from.\n\nThe child route is a full-screen video player which needs the layout to be reset to the root layout since I don't want to render the footer, navbar and other elements on the player route. I do this using the `@` method as per the documentation.\n\nHowever, when using the layout reset, no data is received from the parent load function and the load function of the player route is not even executed. The data prop in the *`+page.svelte`* file is therefore `undefined`.\n\nThe directory tree for the player path is:\n\n```\n📦routes\n ┣ 📂(app)\n ┃ ┣ 📂films\n ┃ ┃ ┣ 📂[slug]\n ┃ ┃ ┃ ┣ 📂player\n ┃ ┃ ┃ ┃ ┣ 📜+page.server.ts (loads data from the parent at ./../)\n ┃ ┃ ┃ ┃ ┗ 📜+page.svelte (Renders data from the load functions)\n ┃ ┃ ┃ ┣ 📜+layout.server.ts (loads data from API)\n ┃ ┃ ┃ ┗ 📜+page.svelte\n ┃ ┃ ┣ 📜+page.server.ts\n ┃ ┃ ┗ 📜+page.svelte\n ┃ ┣ 📜+layout.svelte\n ┃ ┗ 📜+page.ts\n ┗ 📜+layout.svelte (root layout should be applied to the player route)\n```\n\nThe following function loads the data:\n\n```\n// (films/[slug]/+layout.server.ts)\n\nimport { error } from '@sveltejs/kit';\nimport type { LayoutServerLoad } from './$types';\n\nexport const load = (async ({ fetch, params }) => {\n const filmId = params.slug;\n const res = await fetch(`/api/films/${filmId}`);\n if (!res) throw error(404, 'Film not found');\n\n const filmData = await res.json();\n if (!filmData) throw error(404, 'Film not found in database');\n return { filmId, filmData };\n}) satisfies LayoutServerLoad;\n```\n\nAnd this function should get the data from the parent load function:\n\n```\n// (films/[slug]/player/+page.server.ts)\n\nimport type { PageServerLoad } from './$types';\n \nexport const load = (async ({ parent }) => {\n const { filmId, filmData } = await parent();\n console.log('playerlayout', { filmId, filmData });\n \n return { filmId, filmData };\n}) satisfies PageServerLoad;\n```\n\nThe code for the +page.svelte file:\n\n```\n\n import { onMount } from 'svelte';\n import { currentFilm } from '$lib/stores/films';\n import FilmPlayer from '$lib/components/Player/VimeoPlayer.svelte';\n import type { PageData } from './$types';\n\n export let data: PageData;\n console.log('player', data);\n \n if (!$currentFilm) {\n currentFilm.set(data);\n }\n \n const fd = data.filmData;\n if (!fd.vimeoId) throw new Error('No video found for film');\n const vimeoId = fd.vimeoId;\n\n let urls: {hls:string; lq:string;};\n\n async function videoUrls() {\n const response = await fetch('/api/films/videourls', {\n method: 'POST',\n body: JSON.stringify({ vimeoId }),\n headers: {\n 'content-type': 'application/json'\n }\n });\n urls = await response.json();\n }\n onMount(() => {\n videoUrls();\n });\n\n \n {#if urls}\n \n {/if}\n \n\n```\n\nThe project is on the latest versions of its dependencies. That being:\n\n```\n@sveltejs/kit@1.11.0\n@sveltejs/vite-plugin-svelte@2.0.3\n@sveltejs/adapter-auto@2.0.0\nsvelte@3.57.0\nvite@4.1.4\n```\n\nWhen I don't include the `@` character in the filename of the *`+page@.svelte`* file the loading of data works perfectly, returning the expected result, with the data prop in the player *`+page.svelte`* containing the data loaded from the load function in *`films/[slug]/+layout.server.ts`*. However, by not using the `@` method, the player route inherits the layout of the previous route, which is not wanted.\nResetting the layout with a *`+layout@.svelte`* gives the same result. I've also tried different combinations of *`+page.server.ts`* and *`+page.ts`* and *`+layout.ts`* files in both the player and parent route, to load the data, but it gives me the exact same error.\n\nOne the first load of the player route upon navigating from the slug, give me a blank page (the root layout), and the following is logged to the console:\n\n```\nplayerLoad { filmId: undefined, filmData: undefined }\n```\n\nIf I reload the page the following is logged to the console:\n\n```\nplayerLoad { filmId: undefined, filmData: undefined }\nplayer { filmId: undefined, filmData: undefined }\nTypeError: Cannot read properties of undefined (reading 'vimeoId')\n at +page@.svelte:17:9\n at Object.$$render (/node_modules/.pnpm/svelte@3.56.0/node_modules/svelte/internal/index.mjs:1974:22)\n at Object.default (root.svelte:55:41)\n at eval (/src/routes/+layout.svelte:11:81)\n at Object.$$render (/node_modules/.pnpm/svelte@3.56.0/node_modules/svelte/internal/index.mjs:1974:22)\n at root.svelte:43:39\n at $$render (/node_modules/.pnpm/svelte@3.56.0/node_modules/svelte/internal/index.mjs:1974:22)\n at Object.render (/node_modules/.pnpm/svelte@3.56.0/node_modules/svelte/internal/index.mjs:1982:26)\n at Module.render_response (/node_modules/.pnpm/@sveltejs+kit@1.11.0_svelte@3.56.0+vite@4.1.4/node_modules/@sveltejs/kit/src/runtime/server/page/render.js:180:29)\n at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n```\n\nI hope someone can point me in the right direction to fix this issue. I do have some workarounds like adding the player to the parent route, or using stores and coping the load function into the player route so the data can be loaded if the store is not set yet.\n\n========================================\n\nCode:\n```text\n📦routes\n ┣ 📂(app)\n ┃ ┣ 📂films\n ┃ ┃ ┣ 📂[slug]\n ┃ ┃ ┃ ┣ 📂player\n ┃ ┃ ┃ ┃ ┣ 📜+page.server.ts (loads data from the parent at ./../)\n ┃ ┃ ┃ ┃ ┗ 📜+page.svelte (Renders data from the load functions)\n ┃ ┃ ┃ ┣ 📜+layout.server.ts (loads data from API)\n ┃ ┃ ┃ ┗ 📜+page.svelte\n ┃ ┃ ┣ 📜+page.server.ts\n ┃ ┃ ┗ 📜+page.svelte\n ┃ ┣ 📜+layout.svelte\n ┃ ┗ 📜+page.ts\n ┗ 📜+layout.svelte (root layout should be applied to the player route)\n```\n\n```ts\n// (films/[slug]/+layout.server.ts)\n\nimport { error } from '@sveltejs/kit';\nimport type { LayoutServerLoad } from './$types';\n\nexport const load = (async ({ fetch, params }) => {\n const filmId = params.slug;\n const res = await fetch(`/api/films/${filmId}`);\n if (!res) throw error(404, 'Film not found');\n\n const filmData = await res.json();\n if (!filmData) throw error(404, 'Film not found in database');\n return { filmId, filmData };\n}) satisfies LayoutServerLoad;\n```\n\n```ts\n// (films/[slug]/player/+page.server.ts)\n\nimport type { PageServerLoad } from './$types';\n \nexport const load = (async ({ parent }) => {\n const { filmId, filmData } = await parent();\n console.log('playerlayout', { filmId, filmData });\n \n return { filmId, filmData };\n}) satisfies PageServerLoad;\n```\n\n```html\n<!-- (films/[slug]/player/+page.svelte) -->\n<script lang=\"ts\">\n import { onMount } from 'svelte';\n import { currentFilm } from '$lib/stores/films';\n import FilmPlayer from '$lib/components/Player/VimeoPlayer.svelte';\n import type { PageData } from './$types';\n\n export let data: PageData;\n console.log('player', data);\n \n if (!$currentFilm) {\n currentFilm.set(data);\n }\n \n const fd = data.filmData;\n if (!fd.vimeoId) throw new Error('No video found for film');\n const vimeoId = fd.vimeoId;\n\n let urls: {hls:string; lq:string;};\n\n async function videoUrls() {\n const response = await fetch('/api/films/videourls', {\n method: 'POST',\n body: JSON.stringify({ vimeoId }),\n headers: {\n 'content-type': 'application/json'\n }\n });\n urls = await response.json();\n }\n onMount(() => {\n videoUrls();\n });\n</script>\n\n<main>\n <div class=\"max-h-screen h-full player\">\n {#if urls}\n <FilmPlayer {vimeoId} filmTitle={`${fd.title} (${fd.courseYear-1} - ${fd.courseYear})`} {urls} fullscreen={true}/>\n {/if}\n </div>\n</main>\n```\n\n```text\n@sveltejs/kit@1.11.0\n@sveltejs/vite-plugin-svelte@2.0.3\n@sveltejs/adapter-auto@2.0.0\nsvelte@3.57.0\nvite@4.1.4\n```\n\n```text\nplayerLoad { filmId: undefined, filmData: undefined }\n```\n\n```text\nplayerLoad { filmId: undefined, filmData: undefined }\nplayer { filmId: undefined, filmData: undefined }\nTypeError: Cannot read properties of undefined (reading 'vimeoId')\n at +page@.svelte:17:9\n at Object.$$render (/node_modules/.pnpm/svelte@3.56.0/node_modules/svelte/internal/index.mjs:1974:22)\n at Object.default (root.svelte:55:41)\n at eval (/src/routes/+layout.svelte:11:81)\n at Object.$$render (/node_modules/.pnpm/svelte@3.56.0/node_modules/svelte/internal/index.mjs:1974:22)\n at root.svelte:43:39\n at $$render (/node_modules/.pnpm/svelte@3.56.0/node_modules/svelte/internal/index.mjs:1974:22)\n at Object.render (/node_modules/.pnpm/svelte@3.56.0/node_modules/svelte/internal/index.mjs:1982:26)\n at Module.render_response (/node_modules/.pnpm/@sveltejs+kit@1.11.0_svelte@3.56.0+vite@4.1.4/node_modules/@sveltejs/kit/src/runtime/server/page/render.js:180:29)\n at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n```\n\n```text\n+layout.server.ts\n```\n\n```text\n+page.server.ts\n```\n\n```text\n+page.svelte\n```\n\n```text\n@\n```\n\n```text\n+page.svelte\n```\n\n```text\nundefined\n```\n\n```text\n@\n```\n\n```text\n+page@.svelte\n```\n\n```text\n+page.svelte\n```\n\n```text\nfilms/[slug]/+layout.server.ts\n```\n\n```text\n@\n```\n\n```text\n+layout@.svelte\n```\n\n```text\n+page.server.ts\n```\n\n```text\n+page.ts\n```\n\n```text\n+layout.ts\n```\n\n```ts\n// (films/[slug]/player/+page.server.ts)\n\nimport { error } from '@sveltejs/kit';\nimport type { PageServerLoad } from './$types';\n\nexport const load = (async ({ fetch, params }) => {\n const filmId = params.slug;\n const res = await fetch(`/api/films/${filmId}`);\n if (!res) throw error(404, 'Film not found');\n\n const filmData = await res.json();\n if (!filmData) throw error(404, 'Film not found in database');\n return { filmId, filmData };\n}) satisfies PageServerLoad;\n```\n\n```ts\n// (/lib/load-functions.ts)\n\nimport { error } from '@sveltejs/kit';\n\nexport const loadFilms = (async ({ fetch, params }) => {\n const filmId = params.slug;\n const res = await fetch(`/api/films/${filmId}`);\n if (!res) throw error(404, 'Film not found');\n\n const filmData = await res.json();\n if (!filmData) throw error(404, 'Film not found in database');\n return { filmId, filmData };\n});\n```\n\n```ts\n// (films/[slug]/+layout.server.ts)\n\nimport { loadFilms } from '$lib/load-functions';\nimport type { LayoutServerLoad } from './$types';\n\nexport const load = (event) => {\n return loadFilms(event);\n}) satisfies LayoutServerLoad;\n```\n\n```ts\n// (films/[slug]/player/+page.server.ts)\n\nimport { loadFilms } from '$lib/load-functions';\nimport type { PageServerLoad } from './$types';\n\nexport const load = (event) => {\n return loadFilms(event);\n}) satisfies PageServerLoad;\n```\n\n```text\n/routes/(app)/films/[slug]/player/+page@.svelte\n```\n\n```text\n/routes/+layout.svelte\n```\n\n```text\n/routes/(app)/+layout.svelte\n```\n\n```text\nload\n```\n\n```text\n/routes/(app)/films/[slug]/+layout.server.ts\n```\n\n```text\n/routes/(app)/films/[slug]/player/+layout@.svelte\n```\n\n```text\n/routes/(app)/films/[slug]/+layout.svelte\n```\n\n```text\n/routes/(app)/films/[slug]/player/+page@[slug].svelte\n```\n\n```text\nload\n```\n\n```text\n/routes/(app)/films/[slug]/+layout.server.ts\n```\n\n```text\n/routes/(app)/films/[slug]/+page.svelte\n```\n\n```text\n<slot/>\n```\n\n```text\n/routes/(app)/films/[slug]/+layout.server.ts\n```\n\n```text\n/routes/(app)/films/[slug]/player/+page.server.ts\n```\n\n```text\n/lib/load-functions.ts\n```\n\n```text\n/routes/(app)/films/[slug]/+layout.server.ts\n```\n\n```text\n/routes/(app)/films/[slug]/player/+page.server.ts\n```\n\n```text\n/routes/(app)/films/[slug]/+layout.server.ts\n```\n\n```text\n@\n```\n\n```text\n/routes/(app)/films/[slug]/player/+page@.svelte\n```\n\n========================================\n\nComments:\n- For clarity, could you please include the various `+layout.svelte` files in your directory tree and point out which you want applied and which you don't? It's not clear to me whether the layout you wish to avoid is at the same level as the `+layout.server.ts` load function you want to use or if it is located one or more levels above that. Thanks!\n- Thanks for the edit. So just to be clear, in theory you would want to apply the root layout, escape the `(app)` layout, and apply the layout load function from `(app)/films/[slug]`, is that correct?\n- Yes exactly! As I wrote the loading of data from `(app)/films/[slug]` works when I'm not applying the root layout.\n- Thanks a lot for the help. I'll be using option two. Confusing that breaking out of the layout also breaks out of the loading flow.","metadata":{"transformedAt":"2026-08-18T18:33:40.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":46,"totalLines":472,"estimatedTokens":3156}}778{"id":"stack-72989668","source":"stackoverflow","questionId":72989668,"title":"Svelte selection based master/detail not updating correctly","tags":["svelte"],"text":"Title: Svelte selection based master/detail not updating correctly\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nBear with me, Svelte newbie question coming.\n\nI have a selection based Master/Detail view like the following simplified version:\n\n```\n\n let data = [{ x: 10},{ x: 20},{ x:30}]\n let selected = data[1];\n\n {#each data as row}\n \n selected = row}>Select\n \n \n {/each}\n\nDetail: \n\n .selected { background-color: #ff3e00; color: white; }\n\n```\n\nThis works correctly if you select different rows (the Detail updates with the selected row).\nUnfortunately, however, the Detail does not update if the value of the selected item in the top list is changed. Also, the list item value does not update if the Detail is changed. A side note: If you change the list value, then select a different item and switch back, the Detail view does show the correct value.\n\nTo fix it, I switched to an index based selection:\n\n```\n\n let data = [{ x: 10},{ x: 20},{ x:30}]\n let selectedIndex = 1;\n $: selected = data[selectedIndex];\n\n {#each data as row, i}\n \n selectedIndex = i}>Select\n \n \n {/each}\n\nDetail: \n\n .selected { background-color: #ff3e00; color: white; }\n\n```\n\nWhat I can’t figure out is why the first version doesn’t work? What magic am I missing? Further, why did the second version fix it? Both, to me, seem like they should behave the same.\n\nI really like Svelte, but before I can invest heavily I need to know it truly does handle all reactive updating correctly.\n\n========================================\n\nCode:\n```text\n<script>\n let data = [{ x: 10},{ x: 20},{ x:30}]\n let selected = data[1];\n</script>\n<table>\n {#each data as row}\n <tr>\n <button class=\"{selected === row ? 'selected' : ''}\"\n on:click={() => selected = row}>Select</button>\n <td><input type=\"number\" bind:value={row.x}/></td>\n </tr>\n {/each}\n</table>\n\n<br/><br/>\nDetail: <input type=\"number\" bind:value={selected.x}/>\n\n<style>\n .selected { background-color: #ff3e00; color: white; }\n</style>\n```\n\n```text\n<script>\n let data = [{ x: 10},{ x: 20},{ x:30}]\n let selectedIndex = 1;\n $: selected = data[selectedIndex];\n</script>\n<table>\n {#each data as row, i}\n <tr>\n <button class=\"{selectedIndex === i ? 'selected' : ''}\"\n on:click={() => selectedIndex = i}>Select</button>\n <td><input type=\"number\" bind:value={row.x}/></td>\n </tr>\n {/each}\n</table>\n\n<br/><br/>\nDetail: <input type=\"number\" bind:value={selected.x}/>\n\n\n<style>\n .selected { background-color: #ff3e00; color: white; }\n</style>\n```\n\n```js\n$: selected = data[selectedIndex];\n```\n\n```text\nrow.x\n```\n\n```text\nselected.x\n```\n\n```text\nrow.x\n```\n\n```text\ndata\n```\n\n```text\nselected.x\n```\n\n```text\nselected.x\n```\n\n```text\nrow.x\n```\n\n```text\ndata\n```\n\n```text\nselectedIndex\n```\n\n```text\nselected\n```\n\n```text\ndata\n```\n\n========================================\n\nComments:\n- The critical mindset shift (from React's approach) required to understand Svelte, is to construct a dependency graph in your mind when coding.\n- Ahh… I think I get it. Svelte applies reactivity at the code level (being a compiler) and not at the object level. I.e., it does not create a full dependency graph between object (or more correctly, their fields)—but instead compiles the Svelte input to Javascript that will invalidate pure JS objects based on the rules that can be inferred at compile time.\n- One more question/thought: Is the index based approach the right way to do this?\n- @EricHewitt Yes it's the right way to go. This resonates with \"single source of truth\" principle. If you want a selection from a collection, you better use a declarative selector (the `$` statement in svelte) that keeps in-sync the relationship between the selection and collection. If you do it imperatively, it'll probably go out-of-sync at some point.\n- @EricHewitt: I agree with hackape; I tried to think of alternatives but just using an index like this is probably the way to go.","metadata":{"transformedAt":"2026-08-18T18:33:40.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":162,"estimatedTokens":1007}}779{"id":"stack-71127407","source":"stackoverflow","questionId":71127407,"title":"I keep getting builder.rimraf is not a function when i build npm","tags":["javascript","svelte","netlify","vercel","sveltekit"],"text":"Title: I keep getting builder.rimraf is not a function when i build npm\nTags: javascript, svelte, netlify, vercel, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI am trying to make my svelteapp prodcution ready and therefor running `npm run build`\nI have tried with several adapters but i keep getting the same error saying\n\n```\n> Using @sveltejs/adapter-netlify\n> builder.rimraf is not a function\n```\n\nThe application itself runs fine with npm run dev.\n\nI have searched everywhere.\ntried the following\n\n- node version 16.14.0 also tried with older version and the newest 17.5.0\n\n- Deleting node_modules and ran npm i again\n\n- deleting package-lock.json\n\n- tried another adapter like adapter-vercel and adapter-auto that comes with sveltekit\n\n========================================\n\nCode:\n```text\n> Using @sveltejs/adapter-netlify\n> builder.rimraf is not a function\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm i @sveltejs/kit@next\nnpm i @sveltejs/adapter-netlify@next\n```\n\n```text\n@sveltejs/adapter-netlify\n```\n\n========================================\n\nComments:\n- could you some more details? What OS are you on? Can you a github repo with a reproduction?\n- Worked flawlessly, thank you\n- still fails with `$ npm i -D '@sveltejs/adapter-node@next'`","metadata":{"transformedAt":"2026-08-18T18:33:40.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":53,"estimatedTokens":314}}780{"id":"stack-74649521","source":"stackoverflow","questionId":74649521,"title":"Calling a function onclick in Svelte","tags":["javascript","svelte"],"text":"Title: Calling a function onclick in Svelte\nTags: javascript, svelte\nSource: Stack Overflow\n\nQuestion:\nI began using svelte for a recent project, and although I like the workflow of the framework so far, I've yet to get a single function to work successfully.\n\nCurrently, I'm trying to change the innerHTML of a series of objects using functions.\n\nBelow is my code:\n\n```\n\n \n export let question1() {\n document.getElementByClass(questionBox).innerHTML = \"True or False?\";\n document.getElementById(ans_1).innerHTML = \"True\";\n document.getElementById(ans_2).innerHTML = \"False\";}\n \n\n \n Start Game\n ...\n \n \n option1\n option2\n \n\n```\n\nThere is an error marked beneath my function when I call it on:click in the button, and that error reads as follows:\n\n`'question1' is not defined. Consider adding a block with 'export let question1' to declare a propsvelte(missing-declaration)`\n\nI am quite new to svelte and it's entirely possible I misunderstood something structurally within my code, but I've checked all over and can't seem to find anything that quite addresses my problem.\n\nAny help would be quite appreciated. Perhaps I just need some new eyes on this.\n\nThank you.\n\n========================================\n\nCode:\n```text\n<head>\n <script>\n export let question1() {\n document.getElementByClass(questionBox).innerHTML = \"True or False?\";\n document.getElementById(ans_1).innerHTML = \"True\";\n document.getElementById(ans_2).innerHTML = \"False\";}\n </script>\n</head>\n<body>\n <div class=\"container\">\n <button on:click={question1} class=\"startButton\">Start Game</button>\n <div class=\"box\"><span id=\"questionBox\">...</span></div>\n </div>\n <div class=\"option-container\">\n <button class=\"option\" id=\"ans_1\">option1</button>\n <button class=\"option\" id=\"ans_2\">option2</button>\n </div>\n</body>\n```\n\n```text\n'question1' is not defined. Consider adding a <script> block with 'export let question1' to declare a propsvelte(missing-declaration)\n```\n\n```text\nfunction question1() {\n //dosomething\n}\n```\n\n```text\nlet question1 = () => {\n //dosomething\n}\n```\n\n```text\nlet question1() {\n //dosomething\n}\n```\n\n```text\n//by class name\ndocument.querySelector(\".classname\")\n\n//by id\ndocument.querySelector(\"#id\")\n\n//by element type\ndocument.querySelector(\"div\")\n```\n\n```text\ngetElementByClass\n```\n\n```text\ngetElementsByClassName\n```\n\n```text\n<head>\n```\n\n```text\n<script>\n```\n\n```text\n<style>\n```\n\n========================================\n\nComments:\n- Where does the `` come from? Normally a `*.svelte` file has top-level `` block, a `` block, and other DOM elements to be rendered when the component mounts. If you put the `` inside ``, it's no longer a top-level script block, and it'll be treated as normal DOM elements to be rendered.\n- Thank you! These tips helped alot, expecially the repl! I think I understand quite a bit better now.","metadata":{"transformedAt":"2026-08-18T18:33:40.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":123,"estimatedTokens":721}}781{"id":"stack-72810338","source":"stackoverflow","questionId":72810338,"title":"Sveltekit returning a 404 on page load triggers an uncaught exception that breaks the page","tags":["javascript","svelte","sveltekit","uncaught-exception","custom-error-pages"],"text":"Title: Sveltekit returning a 404 on page load triggers an uncaught exception that breaks the page\nTags: javascript, svelte, sveltekit, uncaught-exception, custom-error-pages\nSource: Stack Overflow\n\nQuestion:\nTaken directly from the sveltekit docs. When returning a 404 on page load an uncaught exception will occur that breaks the page:\n\n```\n\n /** @type {import('./__types/[...path]').Load} */ \n export function load({ params }) {\n return {\n status: 404,\n error: new Error(`Not found: /marx-brothers/`)\n };\n }\n\n```\n\nThe above causes an uncaught error that shows up in the console:\n\nhttps://i.sstatic.net/pyGfQ.jpg\n\nThis will cause any other JS to not work such as on:click events etc.\n\nThe docs do not elaborate any further on the matter: https://kit.svelte.dev/docs/layouts#error-pages\n\nCan anyone explain why an uncaught exception is thrown when returning a 404 status for a page on page load? And how best can I solve the issue? Thank You.\n\nEdit: I return the 404 on a __layout.svelte page which is the default layout page that other pages inherit from. Is there an issue with doing it that way?\n\n========================================\n\nCode:\n```text\n<script context=\"module\">\n /** @type {import('./__types/[...path]').Load} */ \n export function load({ params }) {\n return {\n status: 404,\n error: new Error(`Not found: /marx-brothers/`)\n };\n }\n</script>\n```\n\n```text\n<script context=\"module\">\n /** @type {import('./__types/[...path]').Load} */ \n export function load({ params }) {\n return {\n status: 404,\n error: new Error(`Not found: /marx-brothers/`)\n };\n }\n</script>\n```\n\n```text\nerror: new Error(...)\n```\n\n```text\nnpm init svelte load404\n```\n\n```text\ncd load404\n```\n\n```text\nyarn\n```\n\n```text\nyarn dev --open\n```\n\n========================================\n\nComments:\n- Thanks for trying this out. Can you try it with the test app instead of the skeleton project. My test above is done with the test app that can be chosen when doing the npm create svelte my-app step.\n- Also I should point out that I return the 404 from the __layout.svelte page @Leftium\n- @Mat70x7 You probably should not return a 404 response from a layout. I updated my answer with more details.\n- Ok that is fair. What I am trying to accomplish is throw a 404 if someone tries to access a page that requires authorization and they do not have the right permissions. I have multiple roles to account for so I need to make it dynamic. If I can't do the check and return in the load perhaps I can do it from the hooks.ts\n- 403 Forbidden seems like a better status code, but it still results in an uncaught exception. Perhaps it would be worth opening a SvelteKit bug? Otherwise, you could also try redirecting to an \"Unauthorized\" page and encoding the error/reason as a URL param. @Mat70x7\n- Ok thank you the redirect might be the fastest solution.","metadata":{"transformedAt":"2026-08-18T18:33:40.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":87,"estimatedTokens":724}}782{"id":"stack-75088046","source":"stackoverflow","questionId":75088046,"title":"How to pass data from +page.server.js to an underlying +page.svelte in Sveltekit","tags":["server","backend","svelte","sveltekit"],"text":"Title: How to pass data from +page.server.js to an underlying +page.svelte in Sveltekit\nTags: server, backend, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have recently started learning Sveltekit and am working on a very basic project to practise. Here is the structure of the project:\n\n```\n|-routes/\n| |-nextpage/\n| └ +page.svelte\n|+page.svelte\n|+page.server.js\n```\n\nI got stuck trying to pass data from the +page.server.js to the +page.svelte located inside the *nextpage/* route and I have no idea what to do.\n\nIn the main *+page.svelte* there is a component with a button that when pressed sends a FormData via POST request to the */results* endpoint, triggering a server action called *results* within the *+page.server.js*. Then redirects to */nextpage*.\n\nComponent in *+page.svelte*:\n\n```\nlet myObject = {\n //stuff\n}\n\nconst handleSubmit = () => {\n const formData = new FormData();\n\n for(const name in myObject){\n formData.append(name, myObject[name]);\n }\n \n let submit = fetch('?/results', {\n method: 'POST',\n body: formData\n })\n .finally(() => console.log(\"done\"))\n \n window.location = \"/nextpage\";\n}\n```\n\n*+page.server.js*:\n\n```\nlet myObject = {};\n\nexport const load = () => { \n return { \n myObject \n } \n}\n\nexport const actions = { \n results: async({ request }) => {\n const formData = await request.formData(); \n formData.forEach((value, key) => (myObject[key] = value));\n console.log(myObject); \n } \n}\n```\n\nNow I would like to be able to show myObject in the +page.svelte in /nextpage, but the usual `export let data` does not work:\n\n*/nextpage +page.svelte:*\n\n```\n\n export let data;\n\n{data.myObject} //undefined`\n```\n\nWhat can I do? Thank you for your help.\n\n========================================\n\nTop Answer:\nThat does not work. Pages are fully separate, you cannot load data from one page into another.\n\nIf you want to loaded data use a layout load function.\n\n========================================\n\nCode:\n```text\n|-routes/\n| |-nextpage/\n| └ +page.svelte\n|+page.svelte\n|+page.server.js\n```\n\n```js\nlet myObject = {\n //stuff\n}\n\nconst handleSubmit = () => {\n const formData = new FormData();\n\n for(const name in myObject){\n formData.append(name, myObject[name]);\n }\n \n let submit = fetch('?/results', {\n method: 'POST',\n body: formData\n })\n .finally(() => console.log(\"done\"))\n \n window.location = \"/nextpage\";\n}\n```\n\n```js\nlet myObject = {};\n\nexport const load = () => { \n return { \n myObject \n } \n}\n\nexport const actions = { \n results: async({ request }) => {\n const formData = await request.formData(); \n formData.forEach((value, key) => (myObject[key] = value));\n console.log(myObject); \n } \n}\n```\n\n```js\n<script>\n export let data;\n</script>\n\n{data.myObject} //undefined`\n```\n\n```text\nexport let data\n```\n\n```text\ncookies.set('name', JSON.stringify(obj));\n```\n\n```text\nconst obj = cookies.get('name');\n```\n\n```text\n+layout.js\n```\n\n```text\nsveltkit/stores\n```\n\n```text\nsveltekit/stores\n```\n\n```text\n+layout.js\n```\n\n```text\ncookies\n```\n\n```text\n<script>\n//import the 'objectStore' variable from the store\nimport {objectStore} from 'path/to/store'\n\nlet myObject = {\n //stuff\n}\n\nconst handleSubmit = () => {\n const formData = new FormData();\n\n for(const name in myObject){\n formData.append(name, myObject[name]);\n }\n \n let submit = fetch('?/results', {\n method: 'POST',\n body: formData\n })\n .finally(() => console.log(\"done\"))\n\n //set store value as your object\n $objectStore = myObject\n \n\n window.location = \"/nextpage\";\n}\n</script>\n```\n\n```text\n<script>\n//import the 'objectStore' variable from the store\nimport {objectStore} from 'path/to/store'\n</script>\n```\n\n========================================\n\nComments:\n- I have already tried, the problem is that you cannot use actions in +layout.server.js. So, practically speaking, how can I do?\n- You should probably restructure your code. Form data should be saved somewhere (e.g. a DB) and then loaded in a layout or page. To make a page reload its data, use invalidation.\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:40.717Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":218,"estimatedTokens":1099}}783{"id":"stack-69179898","source":"stackoverflow","questionId":69179898,"title":"Why doesn't my draggable svelte work properly after scaling it?","tags":["javascript","css","svelte"],"text":"Title: Why doesn't my draggable svelte work properly after scaling it?\nTags: javascript, css, svelte\nSource: Stack Overflow\n\nQuestion:\nI have created a svelte component to allow for draggable Dom elements:\n\n```\n\n export let posX = 0\n export let posY = 0\n\n let moving = false\n let offsetX\n let offsetY\n\n function dragStart(e) {\n const rect = e.currentTarget.getBoundingClientRect()\n\n offsetX = e.pageX - rect.left\n offsetY = e.pageY - rect.top\n\n moving = true\n }\n\n function dragStop() {\n moving = false\n }\n\n function dragMove(e) {\n if (moving) {\n posX = e.pageX - offsetX\n posY = e.pageY - offsetY\n }\n }\n\n .draggable {\n user-select: none;\n position: absolute;\n cursor: grab;\n }\n\n .draggable:active {\n cursor: grabbing;\n }\n\n \n\n```\n\nWhen I add the CSS property `transform: scale(0.5);` to a div containing draggable components the draggable components stop working as expected. Their positions get offset from the mouse position.\n\n```\n\n import Draggable from \"./Draggable.svelte\"\n\n .box {\n background: red;\n width: 150px;\n height: 150px;\n }\n \n .container {\n transform: scale(0.5);\n }\n\n \n \n \n \n \n \n \n\n```\n\nHere is a link to the svelte REPL: https://svelte.dev/repl/679692b94afc48b48a2a3ebd39875ea0?version=3.42.5\n\nHow would I go about fixing this?\n\nThanks in advance!\n\n========================================\n\nCode:\n```html\n<script>\n export let posX = 0\n export let posY = 0\n\n let moving = false\n let offsetX\n let offsetY\n\n function dragStart(e) {\n const rect = e.currentTarget.getBoundingClientRect()\n\n offsetX = e.pageX - rect.left\n offsetY = e.pageY - rect.top\n\n moving = true\n }\n\n function dragStop() {\n moving = false\n }\n\n function dragMove(e) {\n if (moving) {\n posX = e.pageX - offsetX\n posY = e.pageY - offsetY\n }\n }\n</script>\n\n<style>\n .draggable {\n user-select: none;\n position: absolute;\n cursor: grab;\n }\n\n .draggable:active {\n cursor: grabbing;\n }\n</style>\n\n<svelte:window on:mouseup={dragStop} on:mousemove={dragMove} />\n\n<div\n on:mousedown={dragStart}\n style=\"top: {posY}px; left: {posX}px;\"\n class=\"draggable\"\n>\n <slot/>\n</div>\n```\n\n```html\n<script>\n import Draggable from \"./Draggable.svelte\"\n</script>\n\n<style>\n .box {\n background: red;\n width: 150px;\n height: 150px;\n }\n \n .container {\n transform: scale(0.5);\n }\n</style>\n\n<div class=\"container\">\n <Draggable>\n <div class=\"box\"/>\n </Draggable>\n \n <Draggable posY={250}>\n <div class=\"box\"/>\n </Draggable>\n</div>\n```\n\n```text\ntransform: scale(0.5);\n```\n\n```html\n<!-- App.svelte -->\n<script>\n import {onMount} from \"svelte\"\n import Draggable from \"./Draggable.svelte\"\n \n let parent;\n let parentOffset = {x: 0, y:0}\n \n onMount(() => {\n let rect = parent.getBoundingClientRect()\n parentOffset = {x: rect.x, y: rect.y}\n })\n</script>\n\n<style>\n .box {\n background: red;\n width: 150px;\n height: 150px;\n }\n \n .container {\n transform: scale(0.5);\n }\n</style>\n\n<div class=\"container\" bind:this={parent}>\n <Draggable {parentOffset} scale={0.5}>\n <div class=\"box\"/>\n </Draggable>\n \n <Draggable posY={250} {parentOffset} scale={0.5}>\n <div class=\"box\"/>\n </Draggable>\n</div>\n```\n\n```text\n<!-- Draggable.svelte -->\n<script>\n export let posX = 0\n export let posY = 0\n \n export let parentOffset;\n export let scale;\n\n let moving = false\n let offsetX\n let offsetY\n\n function dragStart(e) {\n const rect = e.currentTarget.getBoundingClientRect()\n\n offsetX = e.pageX - rect.left\n offsetY = e.pageY - rect.top\n\n moving = true\n }\n\n function dragStop() {\n moving = false\n }\n\n function dragMove(e) {\n if (moving) {\n // new math! we subtract the parent offset to correct the parent shift\n // and also divide by the scale to correct the scale multiplication\n posX = ((e.pageX - offsetX)-parentOffset.x)/scale\n posY = ((e.pageY - offsetY)-parentOffset.y)/scale\n }\n }\n</script>\n\n<style>\n .draggable {\n user-select: none;\n position: absolute;\n cursor: grab;\n }\n\n .draggable:active {\n cursor: grabbing;\n }\n</style>\n\n<svelte:window on:mouseup={dragStop} on:mousemove={dragMove} />\n\n<div\n on:mousedown={dragStart}\n style=\"top: {posY}px; left: {posX}px;\"\n class=\"draggable\"\n>\n <slot/>\n</div>\n```\n\n```text\ntop\n```\n\n```text\nleft\n```\n\n```text\n<Draggable>\n```\n\n========================================\n\nComments:\n- What are you trying to achieve with this? Why would you want to scale down the container? I could understand scaling down the individual draggable elements for effect but why the container?\n- I'm building a node-based editor, similar to this. I need to implement a pan and zoom feature. It seems unnecessary to scale down each individual element inside the container if you can just scale the container.","metadata":{"transformedAt":"2026-08-18T18:33:40.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":284,"estimatedTokens":1270}}784{"id":"stack-70826406","source":"stackoverflow","questionId":70826406,"title":"Dynamic routing svelte","tags":["svelte"],"text":"Title: Dynamic routing svelte\nTags: svelte\nSource: Stack Overflow\n\nQuestion:\nI am trying to build a simple blog with Svelte and Strapi v4 as backend.\nI have 2 pages : list of all posts page (no problem here) and the post page (problem here).\nFor the list of posts, I manage to fetch my datas from Strapi using onMount. Works fine.\n\n```\n\nimport { onMount } from \"svelte\";\n\nlet posts = []\n\nonMount(async() => {\n const response = await fetch('http://localhost:1337/api/blogs') \n posts = await response.json()\n}) //etc...\n```\n\nThe link to go to the specific post page [id].svelte works :\n\n```\nEn savoir plus >>>\n\n```\n\nBut I get then an error. I don't manage to tell Svelte : fetch this specific id datas in the [id].svelte page.\nUsing the below code in [id].svelte does not work, I get a 404 in the console.\n\n```\n\nimport { page } from '$app/stores';\nconsole.log(page)\n```\n\nI also tried with this method with no success :\n\n```\n\nexport async function load(context = useContext(contextValue)) {\n console.log(context);\n```\n\nI am blocked and don't know how to move forward. Getting also lost between SvelteKit, Svelte...\nThanks for your great help.\n\nHere is the file tree of the route :\n\nhttps://i.sstatic.net/AnLpE.png\n\nI am also using svelte-routing in my App.svelte file. I use this below code trying to tell Svelte to find my [id] page. But I always get a return saying the page is not found on the server...\n\n```\n\n import { Router, Route } from \"svelte-routing\";\n\n import Index from \"./App.svelte\";\n import id from \"./blog/[id].svelte\";\n \n export let url = \"\";\n\n \n \n \n`\n```\n\n========================================\n\nTop Answer:\nin sveltekit you can get the route param `id` in the special load function and then fetch your content:\n\n```\n\n export async function load({ params, fetch, stuff }) {\n const blogId = params.id\n const url = `/your-api/blogs/${blogId}`;\n const res = await fetch(url)\n\n if (res.ok) {\n return {\n props: {\n content: await res.json()\n }\n }\n }\n\n return {\n status: res.status,\n error: new Error(\n `Error by fetching blog with id: ${blogId}!`\n )\n }\n }\n\n```\n\n========================================\n\nCode:\n```text\n<script>\nimport { onMount } from \"svelte\";\n\nlet posts = []\n\nonMount(async() => {\n const response = await fetch('http://localhost:1337/api/blogs') \n posts = await response.json()\n}) //etc...\n```\n\n```text\n<p class=\"link\"><a href={`/blog/${post.id}`}>En savoir plus >>></a></p>\n```\n\n```text\n<script>\nimport { page } from '$app/stores';\nconsole.log(page)\n```\n\n```text\n<script context=\"module\">\nexport async function load(context = useContext(contextValue)) {\n console.log(context);\n```\n\n```text\n<!-- App.svelte -->\n<script>\n import { Router, Route } from \"svelte-routing\";\n\n import Index from \"./App.svelte\";\n import id from \"./blog/[id].svelte\";\n \n export let url = \"\";\n</script>\n\n<Router url=\"{url}\">\n\n <Route path=\"blog/:id\" let:params>\n <posteid id=\"{params.id}\" /></Route>\n <Route path=\"/\" component=\"{Index}\" />\n</Router>`\n```\n\n```text\n<Route\n path=\"property/:propertyId\"\n let:params={propertyId}\n component={ViewProperty}\n />\n```\n\n```text\nexport let property;\n```\n\n```html\n<script context=\"module\">\n export async function load({ params, fetch, stuff }) {\n const blogId = params.id\n const url = `/your-api/blogs/${blogId}`;\n const res = await fetch(url)\n\n if (res.ok) {\n return {\n props: {\n content: await res.json()\n }\n }\n }\n\n return {\n status: res.status,\n error: new Error(\n `Error by fetching blog with id: ${blogId}!`\n )\n }\n }\n</script>\n```\n\n```text\nid\n```\n\n```text\n<Route path=\"blog/:id\" let:params/>\n```\n\n```text\n<script>\n export const load = async context => {\nconsole.log('context', context)} \n</script>\n```\n\n```text\n<script context = \"module\">\n export async function load({ fetch, page }) {\n const id = page.params.id \n const res = await fetch(`http://localhost:1337/api/blogs/${id}`)\n const blogpost = await res.json()\n\n if (res.ok) {\n return {\n props: {\n blogpost\n }\n }\n }\n}\n```\n\n```text\n<script>\n import { onMount } from \"svelte\";\n\nlet blogpost = []\n \n onMount(async () => {\n const response = await fetch('http://localhost:1337/api/blogs/${id}')\n blogpost = await response.json()\n console.log(blogpost)\n } )\n\n</script>\n```\n\n========================================\n\nComments:\n- can you show us the file tree of the routes ?\n- Hi OmG3r, I have added the above picture. Am quite new in programming, sorry for that.\n- Probably related to stackoverflow.com/questions/58809240/… You can watch `id` changes and fetch there and not in `onMount`.\n- export let propertyId* basically, bind the params to a variable and access that variable to access the path params passed\n- Just \"let:params\" (without the property object) works for me.","metadata":{"transformedAt":"2026-08-18T18:33:40.718Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":241,"estimatedTokens":1218}}785{"id":"stack-62722443","source":"stackoverflow","questionId":62722443,"title":"Reference to \"this\" component in Svelte","tags":["svelte","svelte-3","svelte-component"],"text":"Title: Reference to \"this\" component in Svelte\nTags: svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nFrom what I've read this seems like currently it's not possible: https://github.com/sveltejs/svelte/pull/4523#issuecomment-596232030\n\nI want to build a tree structure, and want to highlight an active node anywhere on the tree. If I use a store to write/read the currently active node ID, it's pretty easy, just check if the ID matches the component's.\n\nBut if I have thousands of nodes, I'm afraid this might get pretty slow as each node checks when current ID changes.\n\nSo I thought I could instead store a reference to the currently active node so I could deactivate/activate any node easily. For example:\n\n```\nimport { activeNode } from './stores'\n\nlet active = false\n\nexport function activate() {\n $activeNode.deactivate()\n activeNode.set(this) // I believe something like this would be much faster, as I could call the `activate` method as necessary on any node.\n\nSo how can I reference a component instance? Or is there a better approach?\n\n========================================\n\nCode:\n```js\nimport { activeNode } from './stores'\n\nlet active = false\n\nexport function activate() {\n $activeNode.deactivate()\n activeNode.set(this) // <- this is undefined\n active = true\n}\n\nexport function deactivate() {\n active = false\n}\n```\n\n```text\nactivate\n```\n\n```html\n<script>\n import { activeNode } from './stores.js'\n\n let active = false\n\n const api = {\n activate() {\n if ($activeNode) $activeNode.deactivate()\n $activeNode = api // sugar for: activeNode.set(api)\n active = true\n },\n deactivate() {\n active = false\n }\n }\n</script>\n\n<div class:active>\n Node\n</div>\n\n<style>\n .active {\n font-weight: bold;\n }\n</style>\n```\n\n```text\nthis\n```\n\n```text\neval\n```\n\n```text\nbind:this\n```\n\n========================================\n\nComments:\n- Thanks for the input, though I'm not entirely sure how would I use this `api` for a specific node, could you help with an example? (just a couple days into svelte so far)\n- It's your own example updated to not use `this`. You don't actually need `this`, you need to access some methods on `this`. So you can just put those functions you need in an object, and send this object through the pipes, instead of `this`. I've updated the example to make it more clear how you would use it in a component.\n- Thanks a lot, this helped me get to where I wanted.","metadata":{"transformedAt":"2026-08-18T18:33:40.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":94,"estimatedTokens":627}}786{"id":"stack-68028238","source":"stackoverflow","questionId":68028238,"title":"Run a sveltekit app from file:// with no server","tags":["svelte","same-origin-policy","svelte-3","sveltekit"],"text":"Title: Run a sveltekit app from file:// with no server\nTags: svelte, same-origin-policy, svelte-3, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI basically am wondering the same things as in this post except I need it for sveltekit with `adapter-static` not just svelte with rollup. There are basically 2 issues:\n\n- SvelteKit doesn't allow you to use `./` in the `paths.base` config option and\n\n- SvelteKit comiles to js modules which don't work from `file` because of `CORS`.\n\nAny idea how to fix those issues?\n\n========================================\n\nCode:\n```text\nadapter-static\n```\n\n```text\n./\n```\n\n```text\npaths.base\n```\n\n```text\nfile\n```\n\n```text\nCORS\n```\n\n========================================\n\nComments:\n- May I ask why you want to run SvelteKit without a server, as this could affect how you would fix the problem?\n- My client wants to be able to open it with a double click on the html file\n- Unfortunately, it seems that `http` or a localhost server (`npm run preview`) is needed to run SveteKit apps.","metadata":{"transformedAt":"2026-08-18T18:33:40.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":42,"estimatedTokens":254}}787{"id":"stack-67559597","source":"stackoverflow","questionId":67559597,"title":"SvelteKit req.body undefined","tags":["svelte","sveltekit"],"text":"Title: SvelteKit req.body undefined\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI'm trying to set up SvelteKit to use it with my CMS.\n\nI'm fetching data from my CMS in `api/query.js`, and fetching data from `api/query` in `index.svelte`.\n\nIt works great and I can get the whole data, but I get an error \"Cannot read property 'split' of undefined\" if I include body in the fetch request. Code:\n\n```\n// api/query.js\nexport async function post(req) {\n const url = API_URL;\n const auth = Buffer.from(`${API_USER_EMAIL}:${API_USER_PASSWORD}`).toString('base64');\n\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Basic ${auth}`,\n },\n body: JSON.stringify(req.body),\n });\n const data = await res.json();\n\n return {\n status: data.code,\n body: data\n }\n}\n```\n\n```\n// index.svelte\nexport async function load({ fetch }) {\n const res = await fetch('/api/query', {\n method: 'POST',\n // body: JSON.stringify({\n // query: 'site.title',\n // }),\n });\n const data = await res.json();\n\n return {\n status: data.status || 200,\n props: data\n }\n}\n```\n\nThe commented out portion of code is one that's causing an error. If I `console.log(req.body)` in `api/query.js` it returns `undefined`.\n\nIs there a way I could use Express.js body-parser? Or is there any other way to resolve this error?\n\n========================================\n\nCode:\n```js\n// api/query.js\nexport async function post(req) {\n const url = API_URL;\n const auth = Buffer.from(`${API_USER_EMAIL}:${API_USER_PASSWORD}`).toString('base64');\n\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Basic ${auth}`,\n },\n body: JSON.stringify(req.body),\n });\n const data = await res.json();\n\n return {\n status: data.code,\n body: data\n }\n}\n```\n\n```js\n// index.svelte\nexport async function load({ fetch }) {\n const res = await fetch('/api/query', {\n method: 'POST',\n // body: JSON.stringify({\n // query: 'site.title',\n // }),\n });\n const data = await res.json();\n\n return {\n status: data.status || 200,\n props: data\n }\n}\n```\n\n```text\napi/query.js\n```\n\n```text\napi/query\n```\n\n```text\nindex.svelte\n```\n\n```text\nconsole.log(req.body)\n```\n\n```text\napi/query.js\n```\n\n```text\nundefined\n```\n\n```js\n...\n headers: {\n 'authorization': `Basic ${auth}`,\n 'content-type': 'application/json'\n },\n...\n```\n\n```text\ncontent-type\n```\n\n========================================\n\nComments:\n- Thank you! I had been trying to parse the request.body with middleware in hooks.ts and StreamReaders for an hour, but this just made it possible to use request.body and be done with it.","metadata":{"transformedAt":"2026-08-18T18:33:40.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":139,"estimatedTokens":668}}788{"id":"stack-68574554","source":"stackoverflow","questionId":68574554,"title":"Svelte iterate over array of objects","tags":["javascript","loops","svelte"],"text":"Title: Svelte iterate over array of objects\nTags: javascript, loops, svelte\nSource: Stack Overflow\n\nQuestion:\nHaving this fixed array of objects like this:\n\n```\nexport let items = [\n {\n name: 'package',\n subname: 'test'\n },\n {\n name: 'package',\n subname: 'test1'\n },\n {\n name: 'pack',\n subname: 'test2'\n }\n]\n```\n\nit is possible to use iterate using each or anything else to get something like this?\n\n```\n\n package\n test\n test1\n\n pack\n test2\n\n```\n\n========================================\n\nCode:\n```js\nexport let items = [\n {\n name: 'package',\n subname: 'test'\n },\n {\n name: 'package',\n subname: 'test1'\n },\n {\n name: 'pack',\n subname: 'test2'\n }\n]\n```\n\n```html\n<div class='item'>\n <div class='name'>package</span>\n <div class='subname'>test</span>\n <div class='subname'>test1</span>\n</div>\n\n<div class='item'>\n <div class='name'>pack</span>\n <div class='subname'>test2</span>\n</div>\n```\n\n```json\n{\n \"package\": [\n \"test\",\n \"test1\"\n ],\n \"pack\": [\n \"test2\"\n ]\n}\n```\n\n```js\nconst getSubnamesByName = (items) => {\n const mergedItems = {}\n items.forEach(({name, subname}) => {\n if (mergedItems[name]) mergedItems[name].push(subname)\n else mergedItems[name] = [subname]\n })\n \n return mergedItems\n }\n```\n\n```html\n<script>\n import { onMount } from 'svelte';\n\n const ITEMS = [ /* ... */ ];\n \n let mergedItems = {}\n \n const getSubnamesByName = (items) => { /* ... */}\n \n onMount(async () => {\n mergedItems = getSubnamesByName(ITEMS)\n })\n</script>\n```\n\n```html\n{#each Object.keys(mergedItems) as name}\n <div class='item'>\n <div class='name'>{name}</div>\n \n {#each mergedItems[name] as subname}\n <div class='subname'>{subname}</div>\n {/each}\n </div>\n{/each}\n```\n\n```text\nname\n```\n\n```text\nsubname\n```\n\n```text\ngetSubnamesByName\n```\n\n```text\nmergedItems\n```\n\n```text\n#each\n```\n\n========================================\n\nComments:\n- You should first do the grouping, and then each over these groups. I don't know a good way to do such grouping directly with an each block","metadata":{"transformedAt":"2026-08-18T18:33:40.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":146,"estimatedTokens":540}}789{"id":"stack-67799952","source":"stackoverflow","questionId":67799952,"title":"Golang gin proxy to handle svelte frontend and Golang api","tags":["go","proxy","svelte","go-gin"],"text":"Title: Golang gin proxy to handle svelte frontend and Golang api\nTags: go, proxy, svelte, go-gin\nSource: Stack Overflow\n\nQuestion:\nI am trying to write a proxy for my api and frontend using Golang and gin. If the request goes to anything except \"/api\" I want to proxy to svelte server. If goes the \"/api/something\" I want to handle it in gin. Currently my code is like this.\n\n```\nfunc proxy(c *gin.Context) {\n remote, err := url.Parse(\"http://localhost:3000\")\n if err != nil {\n panic(err)\n }\n\n proxy := httputil.NewSingleHostReverseProxy(remote)\n proxy.Director = func(req *http.Request) {\n req.Header = c.Request.Header\n req.Host = remote.Host\n req.URL.Scheme = remote.Scheme\n req.URL.Host = remote.Host\n req.URL.Path = c.Param(\"proxyPath\")\n }\n\n proxy.ServeHTTP(c.Writer, c.Request)\n}\n\nfunc main() {\n r := gin.Default()\n\n r.Any(\"/*proxyPath\", proxy)\n\n r.Run(\":8080\")\n}\n```\n\nNow if I go to `http://localhost:8080` I am seeing my svelte app. But if a want to add any other route I get an error saying `panic: catch-all conflicts with existing handle for the path segment root in path '/*proxyPath'`\n\n========================================\n\nCode:\n```golang\nfunc proxy(c *gin.Context) {\n remote, err := url.Parse(\"http://localhost:3000\")\n if err != nil {\n panic(err)\n }\n\n proxy := httputil.NewSingleHostReverseProxy(remote)\n proxy.Director = func(req *http.Request) {\n req.Header = c.Request.Header\n req.Host = remote.Host\n req.URL.Scheme = remote.Scheme\n req.URL.Host = remote.Host\n req.URL.Path = c.Param(\"proxyPath\")\n }\n\n proxy.ServeHTTP(c.Writer, c.Request)\n}\n\nfunc main() {\n r := gin.Default()\n\n r.Any(\"/*proxyPath\", proxy)\n\n r.Run(\":8080\")\n}\n```\n\n```text\nhttp://localhost:8080\n```\n\n```text\npanic: catch-all conflicts with existing handle for the path segment root in path '/*proxyPath'\n```\n\n```text\nr.NoRoute(proxy)\n```\n\n========================================\n\nComments:\n- I would use that but I also need to access proxyPath variable. Without that everything will go to the same address.\n- You can access the path with c.Request.Path.Url in your proxy function","metadata":{"transformedAt":"2026-08-18T18:33:40.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":85,"estimatedTokens":535}}790{"id":"stack-59250545","source":"stackoverflow","questionId":59250545,"title":"Computed values in a object | Svelte","tags":["javascript","spreadsheet","svelte","svelte-component"],"text":"Title: Computed values in a object | Svelte\nTags: javascript, spreadsheet, svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI am coding some projects to learn Svelte and I have been trying to make something similar to a spreadsheet where a user type or change numbers and that reactively make some calculus with a predefined formula (the user can not change the formula). I have tried but I can not do it reactively.\n\nFor this I have created a component call Spreadsheet that has two props, the data and the columns, similar to how Quasar do it for Tables.\n\nHere is the REPL with the example.\n\nThe idea is that a user change the values on the `females, males and area` columns and that change the value of the `density` column reactively with `poblationDensity` formula.\n\n```\n/* App.svelte */\n\n import Spreadsheet from \"./Spreadsheet.svelte\";\n\n const poblationDensity = (females, males, area) => {\n return (females + males) / area;\n };\n\n let data = [\n {\n \"id\": 1,\n \"animal\": \"White-mantled colobus\",\n \"females\": 13,\n \"males\": 33,\n \"area\": 109\n },\n {\n \"id\": 2,\n \"animal\": \"Woodpecker, red-headed\",\n \"females\": 99,\n \"males\": 88,\n \"area\": 252\n },\n {\n \"id\": 3,\n \"animal\": \"White-necked raven\",\n \"females\": 34,\n \"males\": 36,\n \"area\": 362\n },\n {\n \"id\": 4,\n \"animal\": \"Baleen whale\",\n \"females\": 24,\n \"males\": 67,\n \"area\": 457\n },\n {\n \"id\": 5,\n \"animal\": \"Tiger\",\n \"females\": 89,\n \"males\": 20,\n \"area\": 476\n },\n {\n \"id\": 6,\n \"animal\": \"White spoonbill\",\n \"females\": 56,\n \"males\": 85,\n \"area\": 358\n },\n {\n \"id\": 7,\n \"animal\": \"Giant anteater\",\n \"females\": 83,\n \"males\": 98,\n \"area\": 236\n },\n {\n \"id\": 8,\n \"animal\": \"White-fronted capuchin\",\n \"females\": 72,\n \"males\": 44,\n \"area\": 163\n },\n {\n \"id\": 9,\n \"animal\": \"Raccoon, crab-eating\",\n \"females\": 78,\n \"males\": 61,\n \"area\": 410\n },\n {\n \"id\": 10,\n \"animal\": \"Turtle, long-necked\",\n \"females\": 5,\n \"males\": 77,\n \"area\": 472\n }\n ];\n\n const cols = [\n {\n name: \"id\",\n label: \"#\"\n },\n {\n name: \"animal\",\n label: \"Animal\"\n },\n {\n name: \"females\",\n label: \"Females\"\n },\n {\n name: \"males\",\n label: \"Males\"\n },\n {\n name: \"area\",\n label: \"Area\"\n },\n {\n name: \"density\",\n label: \"Density\",\n computed: {\n args: [\"females\", \"males\", \"area\"],\n method: poblationDensity\n }\n }\n ];\n\n \n\n```\n\n```\n/* Spreadsheet.svelte */\n\n export let data = [];\n export let cols = [];\n\n .numeric {\n width: 70px;\n }\n\n \n {#each cols as col}\n {col.label}\n {/each}\n \n {#each data as item}\n \n {#each cols as col}\n \n \n \n {/each}\n \n {/each}\n\n```\n\n========================================\n\nCode:\n```text\n/* App.svelte */\n<script>\n import Spreadsheet from \"./Spreadsheet.svelte\";\n\n const poblationDensity = (females, males, area) => {\n return (females + males) / area;\n };\n\n let data = [\n {\n \"id\": 1,\n \"animal\": \"White-mantled colobus\",\n \"females\": 13,\n \"males\": 33,\n \"area\": 109\n },\n {\n \"id\": 2,\n \"animal\": \"Woodpecker, red-headed\",\n \"females\": 99,\n \"males\": 88,\n \"area\": 252\n },\n {\n \"id\": 3,\n \"animal\": \"White-necked raven\",\n \"females\": 34,\n \"males\": 36,\n \"area\": 362\n },\n {\n \"id\": 4,\n \"animal\": \"Baleen whale\",\n \"females\": 24,\n \"males\": 67,\n \"area\": 457\n },\n {\n \"id\": 5,\n \"animal\": \"Tiger\",\n \"females\": 89,\n \"males\": 20,\n \"area\": 476\n },\n {\n \"id\": 6,\n \"animal\": \"White spoonbill\",\n \"females\": 56,\n \"males\": 85,\n \"area\": 358\n },\n {\n \"id\": 7,\n \"animal\": \"Giant anteater\",\n \"females\": 83,\n \"males\": 98,\n \"area\": 236\n },\n {\n \"id\": 8,\n \"animal\": \"White-fronted capuchin\",\n \"females\": 72,\n \"males\": 44,\n \"area\": 163\n },\n {\n \"id\": 9,\n \"animal\": \"Raccoon, crab-eating\",\n \"females\": 78,\n \"males\": 61,\n \"area\": 410\n },\n {\n \"id\": 10,\n \"animal\": \"Turtle, long-necked\",\n \"females\": 5,\n \"males\": 77,\n \"area\": 472\n }\n ];\n\n const cols = [\n {\n name: \"id\",\n label: \"#\"\n },\n {\n name: \"animal\",\n label: \"Animal\"\n },\n {\n name: \"females\",\n label: \"Females\"\n },\n {\n name: \"males\",\n label: \"Males\"\n },\n {\n name: \"area\",\n label: \"Area\"\n },\n {\n name: \"density\",\n label: \"Density\",\n computed: {\n args: [\"females\", \"males\", \"area\"],\n method: poblationDensity\n }\n }\n ];\n</script>\n\n<main>\n <Spreadsheet {data} {cols} />\n</main>\n```\n\n```text\n/* Spreadsheet.svelte */\n<script>\n export let data = [];\n export let cols = [];\n</script>\n\n<style>\n .numeric {\n width: 70px;\n }\n</style>\n\n<table>\n <tr>\n {#each cols as col}\n <th>{col.label}</th>\n {/each}\n </tr>\n {#each data as item}\n <tr>\n {#each cols as col}\n <td>\n <input type=\"text\" class=\"{col.name !== 'animal' && 'numeric' }\"\n value={col.computed ? 0 : item[col.name]} \n />\n </td>\n {/each}\n </tr>\n {/each}\n</table>\n```\n\n```text\nfemales, males and area\n```\n\n```text\ndensity\n```\n\n```text\npoblationDensity\n```\n\n```html\nvalue={col.computed ? col.computed.method(item) : item[col.name]}\n```\n\n```js\nconst poblationDensity = ({ females, males, area }) => {\n return (females + males) / area;\n};\n```\n\n```html\n{#if col.computed}\n <input\n type=\"text\"\n class={col.name !== 'animal' && 'numeric'}\n value={col.computed.method(item)} />\n{:else}\n <input\n type=\"text\"\n class={col.name !== 'animal' && 'numeric'}\n bind:value={item[col.name]} />\n{/if}\n```\n\n```text\npoblationDensity\n```\n\n```text\n<input >\n```\n\n```text\n<input />\n```\n\n```text\nbind:value={...}\n```\n\n```text\nbind:value\n```\n\n```text\ndata\n```\n\n========================================\n\nComments:\n- Please provide a stackoverflow.com/help/minimal-reproducible-example\n- There it is an example. svelte.dev/repl/a87904776ebf4fe0813e6b190690ca77?version=3.1‌​6.0\n- Please post this code example into your question for future reference. Other users who looks for the same problem might won't find your link later anymore.\n- You are right. Thanks for your advise!","metadata":{"transformedAt":"2026-08-18T18:33:40.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":379,"estimatedTokens":1541}}791{"id":"stack-53253431","source":"stackoverflow","questionId":53253431,"title":"Focus toggling on click in Svelte Component","tags":["svelte","svelte-component"],"text":"Title: Focus toggling on click in Svelte Component\nTags: svelte, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI made a component for entering financial numbers, to be used in my input forms. It works really great now, except for one odd behavior: When I click on the input field it gets the focus as expected, however when clicking on it when it already has the focus takes away the focus. \n\nThere's only one on:click handler in the component and when I removed it the behavior didn't change. So, I don't know what's causing this oddity. \n\n```\nInput with precision=2 \n \nValue={a}\n\nInput with no precision specified \n\n Value={b}\n\n export default {\n data(){return {\n a:1234.34,\n b:3.14159265\n }},\n\n components: {\n Money : \"./Money.html\"\n }\n }\n\n /* How to sytle the component*/\n :global(#first) {\n font-family:serif;\n lobal(#first) {\n font-family:serif;\n background:#ff9;\n }\n\n```\n\nHere's the REPL that shows the issue.\n\nhttps://svelte.technology/repl?version=2.15.3&gist=27f91d57e7a9267fe7d7d36aad850c7e\n\n========================================\n\nCode:\n```text\n<p>Input with precision=2 <Money id=first bind:value=a precision=2/>\n <br/>Value={a}</p>\n<hr/>\n<p>Input with no precision specified <Money ref:m2 bind:value=b/><br/>\n Value={b}</p>\n\n\n<script>\n\n export default {\n data(){return {\n a:1234.34,\n b:3.14159265\n }},\n\n components: {\n Money : \"./Money.html\"\n }\n }\n</script>\n\n<style>\n /* How to sytle the component*/\n :global(#first) {\n font-family:serif;\n lobal(#first) {\n font-family:serif;\n background:#ff9;\n }\n</style>\n```\n\n```text\ndiv.focused:before {...}\n```\n\n```text\npointer-events: none\n```\n\n========================================\n\nComments:\n- Wow! I would have never figured this one out! Thank you very much for njbotkin and you for the solution. I added the extra CSS rule and it works perfectly. BTW, Svelte is super awesome!! Thank you for creating it! I just found it recently and it makes building apps so much easier and faster! I will use the chat more in the future.","metadata":{"transformedAt":"2026-08-18T18:33:40.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":91,"estimatedTokens":525}}792{"id":"stack-63722573","source":"stackoverflow","questionId":63722573,"title":"How to use PDF.js (pdfjs-dist) with Svelte","tags":["javascript","svelte","svelte-3","svelte-component"],"text":"Title: How to use PDF.js (pdfjs-dist) with Svelte\nTags: javascript, svelte, svelte-3, svelte-component\nSource: Stack Overflow\n\nQuestion:\nI am working on a svelte application that is using TypeScript. I wanted to implement PDF viewer like `pdf.js`. I really like this project, so I found an NPM package for it here. I installed the package and tried to import 'pdfjs-dist', I got an error which says:\n\nCould not find a declaration file for module 'pdfjs-dist'. './node_modules/pdfjs-dist/build/pdf.js' implicitly has an 'any' type.\nTry `npm install @types/pdfjs-dist` if it exists or add a new declaration (.d.ts) file containing `declare module 'pdfjs-dist';`\n\nI tried to install `@types/pdfjs-dist`, and went well but still facing that error. I don't know why. I also got this repo but wasn't helpful for what I was looking for.\n\n**My Imports**\n\n\r\n\r\n\n```\n\n import pdfjs from 'pdfjs-dist';\n import pdfjsWorkerEntry from \"pdfjs-dist/build/pdf.worker.entry\";\n\n```\n\n========================================\n\nCode:\n```js\n<script type = \"ts\" >\n import pdfjs from 'pdfjs-dist';\n import pdfjsWorkerEntry from \"pdfjs-dist/build/pdf.worker.entry\";\n</script>\n```\n\n```text\npdf.js\n```\n\n```text\nnpm install @types/pdfjs-dist\n```\n\n```text\ndeclare module 'pdfjs-dist';\n```\n\n```text\n@types/pdfjs-dist\n```\n\n========================================\n\nComments:\n- Where did you get this error? TypeScript compiler? IDE indication?\n- @johannchopin IDE, but because I am using typescript in my svelte app\n- Did u tried to reload your project in the IDE?\n- What IDE are you using?","metadata":{"transformedAt":"2026-08-18T18:33:40.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":57,"estimatedTokens":390}}793{"id":"stack-65709045","source":"stackoverflow","questionId":65709045,"title":"How can I iterate over an array in a Svelte store?","tags":["javascript","arrays","svelte","svelte-store"],"text":"Title: How can I iterate over an array in a Svelte store?\nTags: javascript, arrays, svelte, svelte-store\nSource: Stack Overflow\n\nQuestion:\nI have an array in `store.ts`\n\n```\nexport let annotations = writable(new Array());\n```\n\nAnd I'd like to iterate over the array, in `component.svelte`:\n\n```\n\n import { annotations } from '../store';\n\n {#each annotations as highlight, index}\n ...\n {/each}\n\n```\n\nThis fails with:\n\nArgument of type 'Writable' is not assignable to parameter of type 'ArrayLike'\n\nWhich makes sense - The `Writable` object isn't a regular Array, it's a `Writable`.\n\n**How can I iterate over an array in a Svelte store?**\n\n========================================\n\nCode:\n```text\nexport let annotations = writable(new Array<Annotation>());\n```\n\n```text\n<script lang=\"ts\">\n import { annotations } from '../store';\n</script>\n\n<section>\n {#each annotations as highlight, index}\n ...\n {/each}\n</section>\n```\n\n```text\nstore.ts\n```\n\n```text\ncomponent.svelte\n```\n\n```text\nWritable\n```\n\n```text\nWritable\n```\n\n```text\n<script lang=\"ts\">\n import { annotations } from '../store';\n</script>\n\n<section>\n {#each $annotations as highlight, index}\n ...\n {/each}\n</section>\n```\n\n```text\ncomponent.svelte\n```\n\n========================================\n\nComments:\n- See svelte.dev/docs#4_Prefix_stores_with_$_to_access_their_value‌​s. You'd just replace `annotations` with `$annotations` in the markup.\n- @101arrowz that works perfectly 😊 Could you add it as an answer and I'll accept it? Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:40.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":87,"estimatedTokens":379}}794{"id":"stack-68944143","source":"stackoverflow","questionId":68944143,"title":"SvelteKit - hotreload for .ts and .js not working","tags":["svelte","sveltekit"],"text":"Title: SvelteKit - hotreload for .ts and .js not working\nTags: svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nAfter installing SvelteKit via this guide and write some code i have problem: hot reload works for .svelte and .html, but not works for .ts and .js files. After editing .ts or .js i need restart dev server for changes. How fix it?","metadata":{"transformedAt":"2026-08-18T18:33:40.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":6,"estimatedTokens":87}}795{"id":"stack-52129277","source":"stackoverflow","questionId":52129277,"title":"How to add css from node_modules to template.html in Svelte","tags":["css","import","node-modules","svelte"],"text":"Title: How to add css from node_modules to template.html in Svelte\nTags: css, import, node-modules, svelte\nSource: Stack Overflow\n\nQuestion:\nI have a sapperjs app that like one you get from calling `npx degit sveltejs/sapper-template my-app`. I'd like to add a font. Normal people might add a line like this to `app/template.html`:\n\n```\n\n```\n\nNetwork reasons make this impractical, so I want to host the font locally. In create-react-app I would simply `import 'typeface-roboto-slab'` at the top of my App.jsx or equivalent component. How can I achieve a similar effect in my sapper/svelte app?\n\nI believe it's best to add it to `app/template.html` because anywhere else and the css would be scoped to an individual component. This seems like something that almost any app would need, but nothing about it in the docs that I can find.\n\n========================================\n\nCode:\n```text\n<link rel=\"stylesheet\" href=\"//fonts.googleapis.com/css?family=Roboto+Slab\">\n```\n\n```text\nnpx degit sveltejs/sapper-template my-app\n```\n\n```text\napp/template.html\n```\n\n```text\nimport 'typeface-roboto-slab'\n```\n\n```text\napp/template.html\n```\n\n```bash\nnpm i typeface-roboto-slab\ncp -r node_modules/typeface-roboto-slab assets\n```\n\n```html\n<link rel=\"stylesheet\" href=\"typeface-roboto-slab/index.css\">\n```\n\n```text\nassets\n```\n\n```text\n<link>\n```\n\n```text\napp/template.html\n```\n\n```text\nurl('./files/roboto-slab-latin-100.woff2')\n```\n\n========================================\n\nComments:\n- Hi Rich, I'm importing css styles \"import 'node_modules/.../file.css'\" with rollup-plugin-css-only. The style looks good but fails to resolve the path to the images. Would it be the same problem or the image files have a solution?\n- Is there some rollup plugin (no sapper here, just svelte) that supports importing css from an npm package, which also supports referenced files (fonts, icons, images)???","metadata":{"transformedAt":"2026-08-18T18:33:40.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":68,"estimatedTokens":470}}796{"id":"stack-71153028","source":"stackoverflow","questionId":71153028,"title":"CORS on Stripe https://js.stripe.com","tags":["stripe-payments","svelte","http-status-code-400"],"text":"Title: CORS on Stripe https://js.stripe.com\nTags: stripe-payments, svelte, http-status-code-400\nSource: Stack Overflow\n\nQuestion:\nI have been trying to integrate stripe elements on my sapper framework.\n\nI am using this library svelte-strip-js, all steps work fine but I have started to see these issues continuously on my console\n\n```\nAccess to XMLHttpRequest at 'https://r.stripe.com/0' from \norigin 'https://js.stripe.com' has been blocked by\nCORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.\n```\n\n```\nPOST https://r.stripe.com/0 net::ERR_FAILED 400\n```\n\n```\nUncaught (in promise) NetworkError: https://r.stripe.com/0\n at XMLHttpRequest.r.a.g.onreadystatechange\n```\n\nMy guess is this has something to do with the content security policy. I followed the stripe docs and have created a CSP that suits my use case after verifying from this evaluator\n\n```\n\n```\n\n========================================\n\nCode:\n```text\nAccess to XMLHttpRequest at 'https://r.stripe.com/0' from \norigin 'https://js.stripe.com' has been blocked by\nCORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.\n```\n\n```text\nPOST https://r.stripe.com/0 net::ERR_FAILED 400\n```\n\n```text\nUncaught (in promise) NetworkError: https://r.stripe.com/0\n at XMLHttpRequest.r.a.g.onreadystatechange\n```\n\n```text\n<meta http-equiv=\"Content-Security-Policy\" \n content=\"\n connect-src * https://api.stripe.com;\n frame-src https://js.stripe.com https://hooks.stripe.com;\n script-src 'self' 'unsafe-inline' 'unsafe-eval' https://js.stripe.com;\n object-src 'none';\n \"\n />\n```\n\n```text\nr.stripe.com\n```","metadata":{"transformedAt":"2026-08-18T18:33:40.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":62,"estimatedTokens":418}}797{"id":"stack-78470083","source":"stackoverflow","questionId":78470083,"title":"Passing a promise to addEventListener() in TypeScript?","tags":["typescript","svelte","sveltekit"],"text":"Title: Passing a promise to addEventListener() in TypeScript?\nTags: typescript, svelte, sveltekit\nSource: Stack Overflow\n\nQuestion:\nOn a sveltekit app, I am trying to create an event listener that executes an async function (a mutation) using Typescript.\n\n```\nonMount(() => {\n document.addEventListener('keyup', handleKeyPress);\n});\n```\n\nThe argument I pass to the addEventListener is an async function defined as...\n\n```\nasync function handleKeyPress(event: KeyboardEvent) {\n if (mainList.length > 0) {\n const press =\n event.key === 'ArrowLeft' ? 'left' : event.key === 'ArrowRight' ? 'right' : null;\n \n if (press) {\n await moveItem(press);\n }\n }\n}\n```\n\nYou see, addEventListener expects a function that returns void, so I am getting this error:\n\n`Promise returned in function argument where a void return was expected. eslint`\n\nAnyway to solve this error?\n\n========================================\n\nCode:\n```text\nonMount(() => {\n document.addEventListener('keyup', handleKeyPress);\n});\n```\n\n```text\nasync function handleKeyPress(event: KeyboardEvent) {\n if (mainList.length > 0) {\n const press =\n event.key === 'ArrowLeft' ? 'left' : event.key === 'ArrowRight' ? 'right' : null;\n \n if (press) {\n await moveItem(press);\n }\n }\n}\n```\n\n```text\nPromise returned in function argument where a void return was expected. eslint\n```\n\n```html\n<svelte:document on:keyup={handleKeyPress} />\n```\n\n========================================\n\nComments:\n- The golden rule of linting rules is if a rule is in your way, you disable it. The rules are there to help. If they cause you to do extra work you disable them (globally or just contextually).\n- Or if you don't want to disable linting rule you can change it to `document.addEventListener('keyup', () => handleKeyPress());` though I think it's better to just disable the rule for the line.","metadata":{"transformedAt":"2026-08-18T18:33:40.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":69,"estimatedTokens":465}}798{"id":"stack-74069649","source":"stackoverflow","questionId":74069649,"title":"How do I set the correct type for a click handler when using Svelte with TypeScript?","tags":["javascript","typescript","svelte","eventhandler"],"text":"Title: How do I set the correct type for a click handler when using Svelte with TypeScript?\nTags: javascript, typescript, svelte, eventhandler\nSource: Stack Overflow\n\nQuestion:\nI am using Svelte with TypeScript. I have a button:\n\n```\n\n Click me\n\n```\n\nI am trying to set the correct type for the click handler.\n\n```\nexport let clickHandler: MouseEventHandler;\n```\n\nI got `MouseEventHandler` from the TS error when I use a different type, eg:\n\nType 'Function' is not assignable to type 'MouseEventHandler'.\n\nHowever this fails with `Cannot find name 'MouseEventHandler'`. I can't work out where to import the type `MouseEventHandler` as it's not exported by Svelte.\n\n**How do I set the correct type for a click handler when using Svelte with TypeScript?**\n\n========================================\n\nTop Answer:\nWhile you can type the property, you might want to just forward the event instead:\n\n```\n\n Click me\n\n```\n\n(Docs - After modifiers)\n\nThat way, whatever uses the component can just also add an `on:click` to the component.\n\n========================================\n\nCode:\n```text\n<button on:click|preventDefault={clickHandler}>\n Click me\n</button>\n```\n\n```text\nexport let clickHandler: MouseEventHandler<HTMLButtonElement>;\n```\n\n```text\nMouseEventHandler<HTMLButtonElement>\n```\n\n```text\nCannot find name 'MouseEventHandler'\n```\n\n```text\nMouseEventHandler\n```\n\n```js\nexport let clickHandler: svelte.JSX.MouseEventHandler<HTMLButtonElement>;\n```\n\n```text\nsvelte.JSX\n```\n\n```text\n.svelte\n```\n\n```text\nJSX\n```\n\n```html\n<button on:click|preventDefault>\n Click me\n</button>\n```\n\n```text\non:click\n```\n\n========================================\n\nComments:\n- The way that the language features work is by transforming the components first. They used to be transformed to TSX, but there has been a rewrite of the transform, so by default that might not be the case anymore. Maybe the namespaces will be changed once the old transform gets removed from the codebase.\n- Thanks @H.B. - if the namespace gets changed I'll update the answer to mention.\n- Not really answering what was questioned.... It could have been a comment instead. A good one, thought.","metadata":{"transformedAt":"2026-08-18T18:33:40.718Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":99,"estimatedTokens":538}}799 