💾 Github - https://github.com/gopinav/SvelteKit-Tutorials
-
- create project
npm create svelte@latest hello-world
cd
into./hello-world/
- run
npm install
- start development server:
npm run dev -- --open
- edit
./src/routes/+page.svelte
- create project
-
- create dir in
/src/routes/
to create routesrc/routes/about/
creates route to http://localhost:5173/about- add
+page.svelte
for the routes content
- create dir in
-
- create nested dirs (with
+page.svelte
) to create nested routessrc/blog/
=> http://localhost:5173/blogsrc/blog/first/
=> http://localhost:5173/blog/first
- create nested dirs (with
-
- dynamic route folders are in square brackets
[productId]
- import
page
module from$app/stores
to get the page data.
- dynamic route folders are in square brackets
-
- put dynamic route in dynamic route folder ¯\_(ツ)_/¯
-
[...slug]
slugArr = $page.params.slug.split("/");
-
[[lang]]
const { lang = "en" } = $page.params
makesen
default
-
- plain ol'
<a>
tags (* ^ ω ^)
- plain ol'
-
11 - Navigating Programmatically
- use
goto
from$app/navigation
- use
-
- add
src/params/integer.js
- https://kit.svelte.dev/docs/advanced-routing#matchin
Each module in the params directory corresponds to a matcher, with the exception of
_.test.js
and_.spec.js
files which may be used to unit test your matchers.
- https://kit.svelte.dev/docs/advanced-routing#matchin
- change
[productId]
to[productId=integer]
- add
-
- https://kit.svelte.dev/docs/routing#layout
-
To create a layout that applies to every page, make a file called
src/routes/+layout.svelte
. +page.svelte
files are rendered in the<slot/>
of the layout page.- Layouts can be nested.
- By default, each layout inherits the layout above it.
-
- https://kit.svelte.dev/docs/advanced-routing#advanced-layouts-group
- We can group routes with a directory whose name is wrapped in parentheses — these do not affect the URL path name of the routes inside them.
-
- https://kit.svelte.dev/docs/advanced-routingadvanced-layouts-breaking-out-of-layouts
- We can reset to a layouts by appending @ followed by the segment name.
(auth)/passwords/forgot/+page#@(auth).svelte
uses layout from (auth) group
-
- https://kit.svelte.dev/docs/routing#other-files
-
Any other files inside a route directory are ignored by SvelteKit. This means you can colocate components and utility modules with the routes that need them.
If components and modules are needed by multiple routes, it's a good idea to put them in
$lib
.
-
- export
GET
function in+server.js
- export
-
- SvelteKit provides a convenience json function.
import { json } from "@sveltejs/kit"; export function GET() { return json(myObject); }
-
export async function POST(requestEvent) { // do logic here return json(myObject, { status: 201 }); }
-
- API Routes are wrapped in
[ ]
- API Routes are wrapped in
-
- create fake API endpoint with json-server
npm install json-server
- create
/db.json
file
I used https://www.mockaroo.com/ - edit package.json
"serve-json": "json-server --watch db.json --port 4000"
- start server:
npm run serve-json
- product list:
http://localhost:4000/products
- product:
http://localhost:4000/products/1
- product list:
- create fake API endpoint with json-server
-
- use load function defined in
+page.js
- use load function defined in
-
- Load function with native
window.fetch
makes an HTTP call. - SvelteKit's
fetch
function directly calls thegetHandler
without making an additional request. - you can make relative requests;
fetch("/api/postcodes")
, protocol,domain ,port are all optional
- Load function with native
-
- A function defined
load
in+page.js
. - For a page refresh this function runs both on the server and in the browser.
- For client-side routing it only runs in the browser.
- A function defined
-
- defined in a
page.server.js
- runs only on the server.
- useful when loading page data that involves sensitive information which should never make it to the browser.
- defined in a
-
28 - Universal vs Server Load Function
- Page data can be loaded using a universal load function, a server load function or both.
- A server load function is useful when you have to work with sensitive information such as credentials or API keys.
- A universal load function is useful when you have to return values that are not necessarily serializable, such as a component constructor.
- If your page data requires both you can use them to get there.
- The data returned from a server load function is available through the data pre-structured argument in the universal load function
- Any page data loaded can be accessed using the data prop in the Svelte component file.
-
- Load Function Inputs
params
url
route
fetch
- create a
[productID
] dynamic route - define a
serverLoadFunction
for that page - get the route parameter using
params
- make an API call to
json-server
- return page
title
andproduct
details - display it in the UI
- Load Function Inputs
-
-
Errors
-
in
+page.server.js
-
import { error } from "@sveltejs/kit";
-
throw error(404, { message: "🙁 Oh no! Looks like product isn't available!", hint: "Please try another product.", });
-
-
in
+error.svelte
-
<script> import { page } from "$app/stores"; </script> <h1>{$page.error.message}</h1> <po>{$page.error.hint}</p>
-
-
Redirects
- in
+page.server.js
import { redirect } from "@sveltejs/kit";
throw redirect(307, "/products");
- in
-
-
- define
+layout.js
or+layout.server.js
- return an object that will be available as the
data
prop - in +layout.svelte file bind the data to the HTML and apply any necessary CSS
- define
-
- add
/routes/+layout.svelte
file - add
load
function inroutes/+layout.js
- in
/routes/products/+layout.js
deconstructparent
in theload
function
- add
-
-
in
products/+page.js
const notification = "End of season sale";
-
in
products/productID/+page.server.js
const notification = "End of season sale! 50% off"
-
in
/layout.svelte
import { page } from "$app/stores";
bind$page.data.notification
to<p>
-
Setting the title
-
in
/layout.svelte
-
<svelte:head> <title> {$page.data.title} || "Codevolution" </svelte:head>
-
-
-
-
-
instead of
-
const foo = await foo.json(); const bar = await bar.json(); return { foo, bar };
-
-
do
-
return { foo: foo.json(); bar: bar.json(); };
-
-
SvelteKit will resolve the promises in parallel.
-
-
- add
depends
in+page.js
- add
invalidate
/invalidateAll
in+page.svelte
- add
-
- add
<body data-sveltekit-preload-data="hover">
insrc/app.html
- add
data-sveltekit-preload-data="off"
on individual links to fine tune pre-loading - values:
hover
: preloading will start if the mouse comes to a rest over a link. On mobile, preloading begins on touchstarttap
: preloading will start as soon as a touchstart or mousedown event is registered
- add
-
sveltekit-preload-code
- values:
eager
: links will be preloaded straight awayviewport
: links will be preloaded once they enter the viewporthover
- as above, except that only code is preloadedtap
- as above, except that only code is preloaded
-
-
in
routes/+page.svelte
import { goto, preloadData } from "$app/navigation";
<button on:mouseover={async () => { await preloadData("/products"); }} > Go to Products </button>
-
same can be done for
preloadCode
-
-
- SSR - server side rendering
- CSR - client-side rendering
- pre-render - render in advance of sending to the browser (build time)
-
-
in
+page.js
or+page.server.js
-
export const ssr = true / false; export const csr = true / false;
-