diff --git a/client/.gitignore b/client/.gitignore new file mode 100644 index 0000000..5aea041 --- /dev/null +++ b/client/.gitignore @@ -0,0 +1,6 @@ +.DS_Store +/node_modules/ +/src/node_modules/@sapper/ +yarn-error.log +/cypress/screenshots/ +/__sapper__/ diff --git a/client/README.md b/client/README.md new file mode 100644 index 0000000..fecc155 --- /dev/null +++ b/client/README.md @@ -0,0 +1,109 @@ +# sapper-template + +The default [Sapper](https://github.com/sveltejs/sapper) template, available for Rollup and webpack. + + +## Getting started + + +### Using `degit` + +[`degit`](https://github.com/Rich-Harris/degit) is a scaffolding tool that lets you create a directory from a branch in a repository. Use either the `rollup` or `webpack` branch in `sapper-template`: + +```bash +# for Rollup +npx degit "sveltejs/sapper-template#rollup" my-app +# for webpack +npx degit "sveltejs/sapper-template#webpack" my-app +``` + + +### Using GitHub templates + +Alternatively, you can use GitHub's template feature with the [sapper-template-rollup](https://github.com/sveltejs/sapper-template-rollup) or [sapper-template-webpack](https://github.com/sveltejs/sapper-template-webpack) repositories. + + +### Running the project + +However you get the code, you can install dependencies and run the project in development mode with: + +```bash +cd my-app +npm install # or yarn +npm run dev +``` + +Open up [localhost:3000](http://localhost:3000) and start clicking around. + +Consult [sapper.svelte.dev](https://sapper.svelte.dev) for help getting started. + + +## Structure + +Sapper expects to find two directories in the root of your project — `src` and `static`. + + +### src + +The [src](src) directory contains the entry points for your app — `client.js`, `server.js` and (optionally) a `service-worker.js` — along with a `template.html` file and a `routes` directory. + + +#### src/routes + +This is the heart of your Sapper app. There are two kinds of routes — *pages*, and *server routes*. + +**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. (Sapper will preload and cache the code for these subsequent pages, so that navigation is instantaneous.) + +**Server routes** are modules written in `.js` files, that export functions corresponding to HTTP methods. Each function receives Express `request` and `response` objects as arguments, plus a `next` function. This is useful for creating a JSON API, for example. + +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 the route +* The file `src/routes/index.svelte` (or `src/routes/index.js`) 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 + + +### static + +The [static](static) directory contains any static assets that should be available. These are served using [sirv](https://github.com/lukeed/sirv). + +In your [service-worker.js](src/service-worker.js) file, you can import these as `files` from the generated manifest... + +```js +import { files } from '@sapper/service-worker'; +``` + +...so that you can cache them (though you can choose not to, for example if you don't want to cache very large files). + + +## Bundler config + +Sapper uses Rollup or webpack to provide code-splitting and dynamic imports, as well as compiling your Svelte components. With webpack, it also provides hot module reloading. As long as you don't do anything daft, you can edit the configuration files to add whatever plugins you'd like. + + +## Production mode and deployment + +To start a production version of your app, run `npm run build && npm start`. This will disable live reloading, and activate the appropriate bundler plugins. + +You can deploy your application to any environment that supports Node 8 or above. As an example, to deploy to [Now](https://zeit.co/now), run these commands: + +```bash +npm install -g now +now +``` + + +## Using external components + +When using Svelte components installed from npm, such as [@sveltejs/svelte-virtual-list](https://github.com/sveltejs/svelte-virtual-list), Svelte needs the original component source (rather than any precompiled JavaScript that ships with the component). This allows the component to be rendered server-side, and also keeps your client-side app smaller. + +Because of that, it's essential that the bundler doesn't treat the package as an *external dependency*. You can either modify the `external` option under `server` in [rollup.config.js](rollup.config.js) or the `externals` option in [webpack.config.js](webpack.config.js), or simply install the package to `devDependencies` rather than `dependencies`, which will cause it to get bundled (and therefore compiled) with your app: + +```bash +npm install -D @sveltejs/svelte-virtual-list +``` + + +## Bugs and feedback + +Sapper is in early development, and may have the odd rough edge here and there. Please be vocal over on the [Sapper issue tracker](https://github.com/sveltejs/sapper/issues). diff --git a/client/cypress.json b/client/cypress.json new file mode 100644 index 0000000..f5622fa --- /dev/null +++ b/client/cypress.json @@ -0,0 +1,4 @@ +{ + "baseUrl": "http://localhost:3000", + "video": false +} \ No newline at end of file diff --git a/client/cypress/fixtures/example.json b/client/cypress/fixtures/example.json new file mode 100644 index 0000000..da18d93 --- /dev/null +++ b/client/cypress/fixtures/example.json @@ -0,0 +1,5 @@ +{ + "name": "Using fixtures to represent data", + "email": "hello@cypress.io", + "body": "Fixtures are a great way to mock data for responses to routes" +} \ No newline at end of file diff --git a/client/cypress/integration/spec.js b/client/cypress/integration/spec.js new file mode 100644 index 0000000..9a7140d --- /dev/null +++ b/client/cypress/integration/spec.js @@ -0,0 +1,19 @@ +describe('Sapper template app', () => { + beforeEach(() => { + cy.visit('/') + }); + + it('has the correct
{error.message}
+ +{#if dev && error.stack} +{error.stack}+{/if} diff --git a/client/src/routes/_layout.svelte b/client/src/routes/_layout.svelte new file mode 100644 index 0000000..8432299 --- /dev/null +++ b/client/src/routes/_layout.svelte @@ -0,0 +1,22 @@ + + + + + + +
This is the 'about' page. There's not much here.
\ No newline at end of file diff --git a/client/src/routes/blog/[slug].json.js b/client/src/routes/blog/[slug].json.js new file mode 100644 index 0000000..176890d --- /dev/null +++ b/client/src/routes/blog/[slug].json.js @@ -0,0 +1,28 @@ +import posts from './_posts.js'; + +const lookup = new Map(); +posts.forEach(post => { + lookup.set(post.slug, JSON.stringify(post)); +}); + +export function get(req, res, next) { + // the `slug` parameter is available because + // this file is called [slug].json.js + const { slug } = req.params; + + if (lookup.has(slug)) { + res.writeHead(200, { + 'Content-Type': 'application/json' + }); + + res.end(lookup.get(slug)); + } else { + res.writeHead(404, { + 'Content-Type': 'application/json' + }); + + res.end(JSON.stringify({ + message: `Not found` + })); + } +} diff --git a/client/src/routes/blog/[slug].svelte b/client/src/routes/blog/[slug].svelte new file mode 100644 index 0000000..9e0c419 --- /dev/null +++ b/client/src/routes/blog/[slug].svelte @@ -0,0 +1,64 @@ + + + + + + +First, you have to know what Svelte is. Svelte is a UI framework with a bold new idea: rather than providing a library that you write code with (like React or Vue, for example), it's a compiler that turns your components into highly optimized vanilla JavaScript. If you haven't already read the introductory blog post, you should!
+ +Sapper is a Next.js-style framework (more on that here) built around Svelte. It makes it embarrassingly easy to create extremely high performance web apps. Out of the box, you get:
+ +It's implemented as Express middleware. Everything is set up and waiting for you to get started, but you keep complete control over the server, service worker, webpack config and everything else, so it's as flexible as you need it to be.
+ ` + }, + + { + title: 'How to use Sapper', + slug: 'how-to-use-sapper', + html: ` +Create a new project, using degit:
+ +npx degit "sveltejs/sapper-template#rollup" my-app
+ cd my-app
+ npm install # or yarn!
+ npm run dev
+
+
+ Go to localhost:3000. Open my-app
in your editor. Edit the files in the src/routes
directory or add new ones.
...
+ +Resist overdone joke formats.
+ ` + }, + + { + title: 'Why the name?', + slug: 'why-the-name', + html: ` +In war, the soldiers who build bridges, repair roads, clear minefields and conduct demolitions — all under combat conditions — are known as sappers.
+ +For web developers, the stakes are generally lower than those for combat engineers. But we face our own hostile environment: underpowered devices, poor network connections, and the complexity inherent in front-end engineering. Sapper, which is short for Svelte app maker, is your courageous and dutiful ally.
+ ` + }, + + { + title: 'How is Sapper different from Next.js?', + slug: 'how-is-sapper-different-from-next', + html: ` +Next.js is a React framework from Zeit, and is the inspiration for Sapper. There are a few notable differences, however:
+ +src/routes/blog/[slug].html
routes
directory. These are just .js
files that export functions corresponding to HTTP methods, and receive Express request
and response
objects as arguments. This makes it very easy to, for example, add a JSON API such as the one powering this very page<a>
elements, rather than framework-specific <Link>
components. That means, for example, that this link right here, despite being inside a blob of HTML, works with the router as you'd expect.We're so glad you asked! Come on over to the Svelte and Sapper repos, and join us in the Discord chatroom. Everyone is welcome, especially you!
+ ` + } +]; + +posts.forEach(post => { + post.html = post.html.replace(/^\t{3}/gm, ''); +}); + +export default posts; diff --git a/client/src/routes/blog/index.json.js b/client/src/routes/blog/index.json.js new file mode 100644 index 0000000..bfd9389 --- /dev/null +++ b/client/src/routes/blog/index.json.js @@ -0,0 +1,16 @@ +import posts from './_posts.js'; + +const contents = JSON.stringify(posts.map(post => { + return { + title: post.title, + slug: post.slug + }; +})); + +export function get(req, res) { + res.writeHead(200, { + 'Content-Type': 'application/json' + }); + + res.end(contents); +} \ No newline at end of file diff --git a/client/src/routes/blog/index.svelte b/client/src/routes/blog/index.svelte new file mode 100644 index 0000000..e24f711 --- /dev/null +++ b/client/src/routes/blog/index.svelte @@ -0,0 +1,34 @@ + + + + + + +Try editing this file (src/routes/index.svelte) to test live reloading.
diff --git a/client/src/server.js b/client/src/server.js new file mode 100644 index 0000000..c77f593 --- /dev/null +++ b/client/src/server.js @@ -0,0 +1,17 @@ +import sirv from 'sirv'; +import polka from 'polka'; +import compression from 'compression'; +import * as sapper from '@sapper/server'; + +const { PORT, NODE_ENV } = process.env; +const dev = NODE_ENV === 'development'; + +polka() // You can also use Express + .use( + compression({ threshold: 0 }), + sirv('static', { dev }), + sapper.middleware() + ) + .listen(PORT, err => { + if (err) console.log('error', err); + }); diff --git a/client/src/service-worker.js b/client/src/service-worker.js new file mode 100644 index 0000000..2289a55 --- /dev/null +++ b/client/src/service-worker.js @@ -0,0 +1,82 @@ +import { timestamp, files, shell, routes } from '@sapper/service-worker'; + +const ASSETS = `cache${timestamp}`; + +// `shell` is an array of all the files generated by the bundler, +// `files` is an array of everything in the `static` directory +const to_cache = shell.concat(files); +const cached = new Set(to_cache); + +self.addEventListener('install', event => { + event.waitUntil( + caches + .open(ASSETS) + .then(cache => cache.addAll(to_cache)) + .then(() => { + self.skipWaiting(); + }) + ); +}); + +self.addEventListener('activate', event => { + event.waitUntil( + caches.keys().then(async keys => { + // delete old caches + for (const key of keys) { + if (key !== ASSETS) await caches.delete(key); + } + + self.clients.claim(); + }) + ); +}); + +self.addEventListener('fetch', event => { + if (event.request.method !== 'GET' || event.request.headers.has('range')) return; + + const url = new URL(event.request.url); + + // don't try to handle e.g. data: URIs + if (!url.protocol.startsWith('http')) return; + + // ignore dev server requests + if (url.hostname === self.location.hostname && url.port !== self.location.port) return; + + // always serve static files and bundler-generated assets from cache + if (url.host === self.location.host && cached.has(url.pathname)) { + event.respondWith(caches.match(event.request)); + return; + } + + // for pages, you might want to serve a shell `service-worker-index.html` file, + // which Sapper has generated for you. It's not right for every + // app, but if it's right for yours then uncomment this section + /* + if (url.origin === self.origin && routes.find(route => route.pattern.test(url.pathname))) { + event.respondWith(caches.match('/service-worker-index.html')); + return; + } + */ + + if (event.request.cache === 'only-if-cached') return; + + // for everything else, try the network first, falling back to + // cache if the user is offline. (If the pages never change, you + // might prefer a cache-first approach to a network-first one.) + event.respondWith( + caches + .open(`offline${timestamp}`) + .then(async cache => { + try { + const response = await fetch(event.request); + cache.put(event.request, response.clone()); + return response; + } catch(err) { + const response = await cache.match(event.request); + if (response) return response; + + throw err; + } + }) + ); +}); diff --git a/client/src/template.html b/client/src/template.html new file mode 100644 index 0000000..566cb56 --- /dev/null +++ b/client/src/template.html @@ -0,0 +1,33 @@ + + + + + + + + %sapper.base% + + + + + + + %sapper.styles% + + + %sapper.head% + + + +