DEV Community

loading...
Cover image for a first look at svelteKit part 1 - setup

a first look at svelteKit part 1 - setup

ajcwebdev profile image anthony-campolo Updated on ・5 min read

Back in July I was considering building a project with Sapper, which thankfully I never actually started. I say thankfully because, as Rich Harris announced at the recent Svelte Summit, Sapper 1.0 will be released... never.

Instead the Svelte core team is shifting its efforts to a project known as SvelteKit, as detailed in What's the deal with SvelteKit?. It's important to emphasize here that the people building Svelte, Sapper, and SvelteKit are all basically the same people. So really nothing drastic is changing here, it's more of a rebrand and namespace migration. Or is it?

There is also going to be a larger focus on serverless technology, with Svelte now being referred to as a "serverless-first" framework. But to me the most significant change by far is the removal of Rollup as a development dependency and its replacement with Snowpack Vite.

SvelteKit is very new, so new it currently exists mostly in the form of the blog post linked at the beginning of this article a monorepo inside the SvelteJS GitHub organization and a website. But you can download it and start using it, albeit with many, many caveats attached to it.

Initialize project

mkdir ajcwebdev-sveltekit
cd ajcwebdev-sveltekit
npm init svelte@next
Enter fullscreen mode Exit fullscreen mode

After initializing the project you'll be given a disclaimer.

Welcome to the SvelteKit setup wizard!

SvelteKit is in public beta now. There are definitely bugs and some feature might not work yet. If you encounter an issue, have a look at https://github.com/sveltejs/kit/issues and open a new one, if it is not already tracked.

You'll then be asked a series of questions to configure your application. Feel free to answer based on your own personal use case.

✔ Use TypeScript in components? … no
✔ What do you want to use for writing Styles in Svelte components? › CSS
✔ Add ESLint for code linting? … no
✔ Add Prettier for code formatting? … no
Enter fullscreen mode Exit fullscreen mode

For the sake of simplicity in this blog series I answered no for TypeScript, ESLint, and Prettier and I will not include any additional CSS libraries.

Install dependencies and start development server

npm i
npm run dev -- --open
Enter fullscreen mode Exit fullscreen mode

Open localhost:3000 to see the project.

01-hello-world-localhost-3000

Something might happen if you click the button that says Clicks: 0, although what that could be no one can possibly know.

If we look at our terminal we'll see the following message:

[vite] page reload .svelte/dev/generated/root.svelte
Enter fullscreen mode Exit fullscreen mode

I used to have a Snowpack joke here, unfortunately that joke is now deprecated.

Project Structure

Now we'll look at the code.

02-folder-structure

app.html

<!DOCTYPE html>

<html lang="en">

  <head>
    <meta charset="utf-8">
    <link
      rel="icon"
      href="/favicon.ico"
    >
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1"
    >

    %svelte.head%
  </head>

  <body>
    %svelte.body%
  </body>

</html>
Enter fullscreen mode Exit fullscreen mode

index.svelte

A .svelte file contains three parts:

  • <script> for JavaScript
  • <style> for CSS
  • Any markup you want to include with HTML.
<script>
  import Counter from '$components/Counter.svelte';
</script>
Enter fullscreen mode Exit fullscreen mode
<main>
  <h1>Hello world!</h1>

  <Counter/>
  <p>
    Visit the <a href="https://svelte.dev">svelte.dev</a> to learn how to build Svelte apps.
  </p>
</main>
Enter fullscreen mode Exit fullscreen mode
<style>
  :root {
    font-family: -apple-system,
    BlinkMacSystemFont,
    'Segoe UI',
    Roboto,
    Oxygen,
    Ubuntu,
    Cantarell,
    'Open Sans',
    'Helvetica Neue',
    sans-serif;
  }

  main {
    text-align: center;
    padding: 1em;
    margin: 0 auto;
  }

  h1 {
    color: #ff3e00;
    text-transform: uppercase;
    font-size: 4rem;
    font-weight: 100;
    line-height: 1.1;
    margin: 4rem auto;
    max-width: 14rem;
  }

  p {
    max-width: 14rem;
    margin: 2rem auto;
    line-height: 1.35;
  }

  @media (min-width: 480px) {
    h1 {
      max-width: none;
    }

    p {
      max-width: none;
    }
  }
</style>
Enter fullscreen mode Exit fullscreen mode

Counter.svelte

Unlike React, Svelte does not have a virtual DOM. Instead, Svelte includes its own system of reactivity to keep the DOM in sync with your application state. This includes responding to events, such as a mouse click. You can listen to any event on an element with the on: directive.

We start by initializing a variable called count to a value of 0. We create an increment function that adds 1 to the count.

<script>
  let count = 0;

  const increment = () => {
    count += 1;
  };
</script>
Enter fullscreen mode Exit fullscreen mode

We pass the increment function to on:click

<button on:click={increment}>
  Clicks: {count}
</button>
Enter fullscreen mode Exit fullscreen mode

To make sure everything is working we'll make a change to our index.svelte file.

<script>
  import Counter from '$components/Counter.svelte';
</script>

<main>
  <h1>ajcwebdev</h1>

  <Counter/>
  <p>
    <a href="https://github.com/ajcwebdev">GitHub</a>
  </p>
  <p>
    <a href="https://twitter.com/ajcwebdev">Twitter</a>
  </p>
  <p>
    <a href="https://dev.to/ajcwebdev">Dev.to</a>
  </p>
</main>
Enter fullscreen mode Exit fullscreen mode

03-home-page-ajcwebdev

Config

SvelteKit is a rare framework containing configuration that's actually interesting. You may have heard in the past that SvelteKit was using Snowpack. While SvelteKit was heavily developed in tandem with Snowpack, it migrated to Vite in February 2021 about a month before its beta launch. You can read Rich Harris's reasoning for the switch here.

svelte.config.cjs

npm run build will create a standard Node app. target will hydrate the

element in src/app.html.
const node = require('@sveltejs/adapter-node');
const pkg = require('./package.json');

/** @type {import('@sveltejs/kit').Config} */
module.exports = {
  kit: {
    adapter: node(),

    target: '#svelte',

    vite: {
      ssr: {
        noExternal: Object.keys(pkg.dependencies || {})
      }
    }
  }
};

package.json

{
  "name": "ajcwebdev-sveltekit",
  "version": "0.0.1",
  "scripts": {
    "dev": "svelte-kit dev",
    "build": "svelte-kit build",
    "start": "svelte-kit start"
  },
  "devDependencies": {
    "@sveltejs/adapter-node": "next",
    "@sveltejs/kit": "next",
    "svelte": "^3.29.0",
    "vite": "^2.1.0"
  },
  "type": "module"
}

adapters

Svelte apps are built with adapters for optimizing your project to deploy with different environments such as:

There are also adapters for running your app on a Node server or deployed on a static hosting provider.

  • adapter-node — for creating self-contained Node apps
  • adapter-static — for prerendering your entire site as a collection of static files

By default, npm run build will generate a Node app that you can run with node build. To use a different adapter, install it and update your svelte.config.cjs accordingly.

Discussion (15)

pic
Editor guide
Collapse
mweissen profile image
mweissen

Yes, this is a great concept. I have tried sveltekit and Snowpack is a dream. But the project is turning into a never-ending-story. When should there be a beta version? In December 2020? In January 2021? February 2021? I'm afraid by now that it will never be finished. Just like Sapper.

Collapse
ajcwebdev profile image
anthony-campolo Author

I think it's reasonable to expect a broad picture of where a project is going and when it will be stable, but I think it's unreasonable to expect open sources projects of this nature to have specific "release dates" in the way we think of releasing traditional software.

And to your point about Sapper, I know many people with Sapper apps who are perfectly happy with them, so the idea that Sapper was "never finished" doesn't make any sense because there are projects built with Sapper that exist in the world.

The question of when the team feels like svelte-kit is polished enough to be called "1.0" or "General Availability" or whatever is going to be up to them. Only they will know when the project is in a stable state.

To me this comes with the territory of using software I'm not paying for, I'm not in a position to dictate the timeline. Asking them to put a date on it is counterproductive. Others are welcome to disagree but that's my philosophy.

Collapse
jwess profile image
Joel

I followed this article but chose "yes" for TypeScript. I saw the error Error: Failed to load /_app/assets/generated/root.js: NOT_FOUND when I tried to launch, but I was able to fix this issue by making this change to snowpack.config.js:

github.com/snowpackjs/snowpack/dis...

Collapse
ajcwebdev profile image
anthony-campolo Author

Thanks a lot, Joel! I'll make a note in the article.

Collapse
asader profile image
asader

"But to me the most significant change by far is the removal of Rollup and its replacement with Snowpack."
Only in development.

Collapse
ajcwebdev profile image
anthony-campolo Author • Edited

Very true since you're always just shipping vanilla JS with Svelte. But these tools have become so ingrained in our development workflow this still seems significant to me.

Collapse
borsemayur2 profile image
Mayur Borse

I used adapter-vercel for deploying on vercel.

Collapse
ajcwebdev profile image
anthony-campolo Author

Very cool! Do you have a repo or link to the site you could share?

Collapse
borsemayur2 profile image
Mayur Borse

github.com/borsemayur2/sveltekit-d...

It supports deployment to Netlify, Vercel or Node (default).
Set ADAPTER env variable as per deployment service.
ADAPTER=vercel // Vercel
ADAPTER=netlify // Netlify

Thread Thread
ajcwebdev profile image
anthony-campolo Author

Awesome, thanks for sharing!

Collapse
borsemayur2 profile image
Collapse
clozach profile image
Chris Lozac'h

Remember, you have to whisper when you say Snowpack.

😂

Collapse
erickmarcia profile image
Erick Marcia

It gives me an error when trying to build..

Collapse
ajcwebdev profile image
anthony-campolo Author • Edited

This project is currently in flux and it's been over a month since I updated this blog post, so it's entirely possible somebody broke something since then. Feel free to post your error in your comment and maybe we can help figure it out.

Collapse
erickmarcia profile image