Svelte has been seeing increasing amounts of traction lately but there are sometimes a bit of a dearth of examples of how to use it to build real-life applications. This tutorial illustrates how to build a minimalist application that stores its data in a database and requires login.
You can find the complete code on Github.
We will use Sapper, the Svelte-powered server for easily building isomorphic applications. You can set up a new project with a single command:
npx degit “sveltejs/sapper-template#rollup” sapper-mood
“sapper-mood” is the name of the project you’re creating.
By default, the project is plain JavaScript. To switch to TypeScript, run node scripts/setupTypeScript
followed by yarn
to install dependencies and yarn run dev
to start the development server.
We will store the data in a Postgres database. Rather than hand-coding SQL in the application code, we will use Knex to build SQL queries. Knex is not a fully-fledged ORM (Object–Relational Mapping), that are frequently more effort than they are worth; it’s just an API to build SQL queries and to manage migrations.
Make sure you have Postgres running locally, then create a new database and optionally a new user for your database:
> psql
## create database coaching;
CREATE DATABASE
## create user mooduser with password 'mysecretpassword';
CREATE ROLE
Add Knex and Postgres drivers using yarn add knex pg
followed by npx knex init
which will create Knex’ configuration file knexfile.js
.
Edit the file to enter the credentials of your local Postgres, for example
development: {
client: 'postgresql',
connection: {
database: 'mood',
user: 'mooduser',
password: 'mysecretpassword'
}
}
#sveltejs #javascript #web-development #svelte #programming