Skip to content

Documentation Update #403

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Feb 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 20 additions & 24 deletions documentation/docs/01-structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,60 +15,56 @@ If you take a look inside a new SvelteKit project, you'll see some files that Sv
│ └ app.html
├ static
│ ├ # your files here
snowpack.config.js
└ svelte.config.js
snowpack.config.cjs
└ svelte.config.cjs
```

### package.json

Your package.json contains your app's dependencies and defines a number of scripts:

* `npm run dev` — start the app in development mode, and watch source files for changes
* `npm run build` — build the app in production mode
* `npm start` — start the app in production mode after you've built it

- `npm run dev` — start the app in development mode, and watch source files for changes
- `npm run build` — build the app in production mode
- `npm start` — start the app in production mode after you've built it

### src

This contains the *home page* for your app — `src/index.svelte` and (optionally) `src/service-worker.js` — along with a `src/app.html` file.

This contains the _home page_ for your app — `src/index.svelte` and (optionally) `src/service-worker.js` — along with a `src/app.html` file.

#### src/routes/index.svelte

This is the home page for your application and is just like any other Svelte component.


#### src/service-worker.js

_Currently not implemented._

Service workers act as proxy servers that give you fine-grained control over how to respond to network requests. For example, when the browser requests `/goats.jpg`, the service worker can respond with a file it previously cached, or it can pass the request on to the server, or it could even respond with something completely different, such as a picture of llamas.

Among other things, this makes it possible to build applications that work offline.

Because every app needs a slightly different service worker (sometimes it's appropriate to always serve from the cache, sometimes that should only be a last resort in case of no connectivity), Sapper doesn't attempt to control the service worker. Instead, you write the logic in `service-worker.js`. You can import any of the following from `@sapper/service-worker`:

* `files` — an array of files found in the `static` directory
* `shell` — the client-side JavaScript generated by the bundler (Rollup or webpack)
* `routes` — an array of `{ pattern: RegExp }` objects you can use to determine whether a Sapper-controlled page is being requested
* `timestamp` — the time the service worker was generated (useful for generating unique cache names)

- `files` — an array of files found in the `static` directory
- `shell` — the client-side JavaScript generated by the bundler (Rollup or webpack)
- `routes` — an array of `{ pattern: RegExp }` objects you can use to determine whether a Sapper-controlled page is being requested
- `timestamp` — the time the service worker was generated (useful for generating unique cache names)

#### src/app.html

This file is a template for responses from the server. Sapper will inject content that replaces the following tags:

* `%svelte.base%` — a `<base>` element (see [base URLs](docs#Base_URLs))
* `%svelte.styles%` — critical CSS for the page being requested
* `%svelte.head%` — HTML representing page-specific `<head>` contents, like `<title>`
* `%svelte.html%` — HTML representing the body of the page being rendered
* `%svelte.scripts%` — script tags for the client-side app
* `%svelte.cspnonce%` — CSP nonce taken from `res.locals.nonce` (see [Content Security Policy (CSP)](docs#Content_Security_Policy_CSP))

- `%svelte.base%` — a `<base>` element (see [base URLs](docs#Base_URLs))
- `%svelte.styles%` — critical CSS for the page being requested
- `%svelte.head%` — HTML representing page-specific `<head>` contents, like `<title>`
- `%svelte.html%` — HTML representing the body of the page being rendered
- `%svelte.scripts%` — script tags for the client-side app
- `%svelte.cspnonce%` — CSP nonce taken from `res.locals.nonce` (see [Content Security Policy (CSP)](docs#Content_Security_Policy_CSP))

### src/routes

This is the meat of your app — the pages and server routes. See the section on [routing](docs#Routing) for the juicy details.


### static

This is a place to put any files that your app uses — fonts, images and so on. For example `static/favicon.png` will be served as `/favicon.png`.
Expand All @@ -77,10 +73,10 @@ Sapper doesn't serve these files — you'd typically use [sirv](https://github.c

> Note that the default behaviour of the service worker is to cache all assets from the static directory, so if you have more than 50mb of files here, you will start to exceed the cache limit for service-workers in some browsers, which can cause the service worker to stop loading. In this instance, it is advisable to customise what files are cached by editing the service-worker yourself.

### snowpack.config.js
### snowpack.config.cjs

This is the [Snowpack configuration file](https://www.snowpack.dev/reference/configuration) for your project.

### svelte.config.js
### svelte.config.cjs

This file contains SvelteKit options as well as options for `svelte-preprocess`.
50 changes: 24 additions & 26 deletions documentation/docs/02-routing.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ title: Routing

As we've seen, there are two types of route in SvelteKit — pages and API endpoints.


### Pages

Pages are Svelte components written in `.svelte` files. When a user first visits the application, they will be served a server-rendered version of the route in question, plus some JavaScript that 'hydrates' the page and initialises a client-side router. From that point forward, navigating to other pages is handled entirely on the client for a fast, app-like feel.
Expand Down Expand Up @@ -37,20 +36,18 @@ Dynamic parameters are encoded using `[brackets]`. For example, here's how you c
```html
<!-- src/routes/blog/[slug].svelte -->
<script context="module">
import * as api from '$common/api.js';

// the (optional) load function takes a
// `{ page, session }` object and turns it into
// the data we need to render the page
export async function load({ page, session }) {
export async function load({ fetch, page, session }) {
// the `slug` parameter is available because this file
// is called [slug].svelte
const { slug } = page.params;

// `api.get` is a wrapper around `fetch` that allows
// you to make credentialled requests on both
// server and client
const res = await api.get(`blog/${slug}.json`);
// `fetch` is a wrapper around the browser`fetch`
// that allows you to make credentialled requests
// on both server and client
const res = await fetch(`blog/${slug}.json`);
const article = await res.json();

return { { props: article } };
Expand All @@ -67,9 +64,7 @@ Dynamic parameters are encoded using `[brackets]`. For example, here's how you c

<h1>{article.title}</h1>

<div class='content'>
{@html article.html}
</div>
<div class="content">{@html article.html}</div>
```

If you want to capture more params, you can create nested folders using the same naming convention: `[slug]/[language]`.
Expand All @@ -82,58 +77,61 @@ If you don't want to create several folders to capture more than one parameter l
export async function load({ page }) {
let [slug, year, month, day] = page.params.slug;

return { props: { slug, year, month, day }};
return { props: { slug, year, month, day } };
}
</script>
```


> See the section on [loading](docs#Loading) for more info about `load` and `this.fetch`

> See the section on [loading](docs#Loading) for more info about `load` and `fetch`

### Server routes

Server routes are modules written in `.js` files that export functions corresponding to HTTP methods. Each function receives HTTP `request` and `response` objects as arguments, plus a `next` function. This is useful for creating a JSON API. For example, here's how you could create an endpoint that served the blog page above:
Server routes are modules written in `.js` or `.ts` files that export functions corresponding to HTTP methods. Each function receives HTTP `request` and `context` objects as arguments. This is useful for creating a JSON API. For example, here's how you could create an endpoint that served the blog page above:

```js
// routes/blog/[slug].json.js
import db from './_database.js'; // the underscore tells SvelteKit this isn't a route

export async function get(req, res, next) {
export async function get(req, context) {
// the `slug` parameter is available because this file
// is called [slug].json.js
const { slug } = req.params;

const article = await db.get(slug);

if (article !== null) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(article));
return {
body: {
article
}
};
} else {
next();
return {
status: 404,
body: {
error: 'Not found'
}
};
}
}
```

> `delete` is a reserved word in JavaScript. To handle DELETE requests, export a function called `del` instead.


### File naming rules

There are three simple rules for naming the files that define your routes:

* A file called `src/routes/about.svelte` corresponds to the `/about` route. A file called `src/routes/blog/[slug].svelte` corresponds to the `/blog/:slug` route, in which case `params.slug` is available to `load`
* The file `src/routes/index.svelte` corresponds to the root of your app. `src/routes/about/index.svelte` is treated the same as `src/routes/about.svelte`.
* Files and directories with a leading underscore do *not* create routes. This allows you to colocate helper modules and components with the routes that depend on them — for example you could have a file called `src/routes/_helpers/datetime.js` and it would *not* create a `/_helpers/datetime` route

- A file called `src/routes/about.svelte` corresponds to the `/about` route. A file called `src/routes/blog/[slug].svelte` corresponds to the `/blog/:slug` route, in which case `params.slug` is available to `load`
- The file `src/routes/index.svelte` corresponds to the root of your app. `src/routes/about/index.svelte` is treated the same as `src/routes/about.svelte`.
- Files and directories with a leading underscore do _not_ create routes. This allows you to colocate helper modules and components with the routes that depend on them — for example you could have a file called `src/routes/_helpers/datetime.js` and it would _not_ create a `/_helpers/datetime` route

### Error page

In addition to regular pages, there is a 'special' page that SvelteKit expects to find — `src/routes/$error.svelte`. This will be shown when an error occurs while rendering a page.

The `error` object is made available to the template along with the HTTP `status` code. `error` is also available in the [`page` store](docs#Stores).


### Regexes in routes

You can use a subset of regular expressions to qualify route parameters, by placing them in parentheses after the parameter name.
Expand Down
46 changes: 12 additions & 34 deletions documentation/docs/03-client-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,64 +4,42 @@ title: Client API

The `$app/navigation` and `$app/stores` modules contain functions for controlling SvelteKit programmatically and responding to events.


### start({ target })

* `target` — an element to render pages to

This configures the router and starts the application — listens for clicks on `<a>` elements, interacts with the `history` API, and renders and updates your Svelte components.

Returns a `Promise` that resolves when the initial page has been hydrated.

```js
import * as sapper from '@sapper/app';

sapper.start({
target: document.querySelector('#sapper')
}).then(() => {
console.log('client-side app has started');
});
```


### goto(href, options?)

* `href` — the page to go to
* `options` — not required
* `replaceState` (`boolean`, default `false`) — determines whether to use `history.pushState` (the default) or `history.replaceState`.
* `noscroll` (`boolean`, default `false`) — prevent scroll to top after navigation.
- `href` — the page to go to
- `options` — not required
- `replaceState` (`boolean`, default `false`) — determines whether to use `history.pushState` (the default) or `history.replaceState`.
- `noscroll` (`boolean`, default `false`) — prevent scroll to top after navigation.

Programmatically navigates to the given `href`. If the destination is a Sapper route, Sapper will handle the navigation, otherwise the page will be reloaded with the new `href`. In other words, the behaviour is as though the user clicked on a link with this `href`.
Programmatically navigates to the given `href`. If the destination is a SvelteKit route, SvelteKit will handle the navigation, otherwise the page will be reloaded with the new `href`. In other words, the behaviour is as though the user clicked on a link with this `href`.

Returns a `Promise` that resolves when the navigation is complete. This can be used to perform actions once the navigation has completed, such as updating a database, store, etc.

```js
import { goto } from '@sapper/app';
import { goto } from '$app/navigation';

const navigateAndSave = async () => {
await goto('/');
saveItem();
}
};

const saveItem = () => {
// do something with the database
}
};
```


### prefetch(href)

* `href` — the page to prefetch
- `href` — the page to prefetch

Programmatically prefetches the given page, which means a) ensuring that the code for the page is loaded, and b) calling the page's `preload` method with the appropriate options. This is the same behaviour that Sapper triggers when the user taps or mouses over an `<a>` element with [rel=prefetch](docs#rel_prefetch).
Programmatically prefetches the given page, which means a) ensuring that the code for the page is loaded, and b) calling the page's `preload` method with the appropriate options. This is the same behaviour that SvelteKit triggers when the user taps or mouses over an `<a>` element with [rel=prefetch](docs#rel_prefetch).

Returns a `Promise` that resolves when the prefetch is complete.


### prefetchRoutes(routes?)

* `routes` — an optional array of strings representing routes to prefetch
- `routes` — an optional array of strings representing routes to prefetch

Programmatically prefetches the code for routes that haven't yet been fetched. Typically, you might call this after `sapper.start()` is complete, to speed up subsequent navigation (this is the 'L' of the [PRPL pattern](https://developers.google.com/web/fundamentals/performance/prpl-pattern/)). Omitting arguments will cause all routes to be fetched, or you can specify routes by any matching pathname such as `/about` (to match `src/routes/about.svelte`) or `/blog/*` (to match `src/routes/blog/[slug].svelte`). Unlike `prefetch`, this won't call `preload` for individual pages.
Programmatically prefetches the code for routes that haven't yet been fetched. Typically, you might call this to speed up subsequent navigation (this is the 'L' of the [PRPL pattern](https://developers.google.com/web/fundamentals/performance/prpl-pattern/)). Omitting arguments will cause all routes to be fetched, or you can specify routes by any matching pathname such as `/about` (to match `src/routes/about.svelte`) or `/blog/*` (to match `src/routes/blog/[slug].svelte`). Unlike `prefetch`, this won't call `preload` for individual pages.

Returns a `Promise` that resolves when the routes have been prefetched.
Loading