Build and Deploy apps with Svelte and Vite

Build and Deploy apps with Svelte and Vite

Setup Vite with Svelte and learn about building and deploying apps with Svelte and Vite

Svelte with Vite

What is Vite

Vite is known as Next Generation Frontend Tooling System in its documentation. It means that it helps in building and creating a good developer experience for the frontend project. It is an alternative to Svelte default Rollup bundler and it is faster than Rollup when starting the development server.

Vite is also going to be the default bundler for SvelteKit (Framework on top of Svelte) and it proves to be very fast and has lots of cool features for development such as preserving the state during Hot Reload of the page.

Features of Vite

  1. Instant Server Start
  2. Fast Hot Module Reload
  3. Optimized Production Build
  4. Out of box support for CSS, Typescript

Vite is also not specific to a particular frontend framework. It works for multiple frameworks and it has a list of supported templates to bootstrap your next application.

At the time of writing this tutorial, the list of templates supported by Vite

  1. Vanilla Javascript (JS / Typescript support)
  2. Vue (JS / Typescript support)
  3. React (JS / Typescript support)
  4. Preact (JS / Typescript support)
  5. Svelte (JS / Typescript support)
  6. Lit (JS / Typescript support)

Why use Vite over Rollup

Rollup finds all the files in the project and bundles them into a single file. The server is started after this and then the file is served in the server. This can work well when it is a small project and the number of files is limited. As the project grows, the time for bundling the files gets big and each change takes a lot of time to reflect which can cause frustration for the developer.

Image of bundle based Development server (Rollup)

BundleBaseDevServer.jpg

Vite follows a different approach by starting the server first and creates a bundle of the dependencies which doesn’t change often using esbuild. It is extremely fast compared to other bundler and results in faster loading of the development server. Vite also has Hot Module Replacement (HMR) which means that when some file is edited, only the file and its related modules are built again instead of the whole bundle.

Image of Native ESM based Development server (Vite)

NativeEsBasedBundler.jpg

Ok, that’s a lot of theory on what and why to use Vite. Let’s look at some code and getting started with Vite and Svelte. Trust me these steps are very simple compared to the other theory parts.

Create a Vite project

Go to the directory where you want the project to reside and then run the following command

npm init vite@latest
  1. Select the project name
  2. Select the framework from the list. We are going with svelte
  3. Select the variant from the list. We are going with svelte-ts which has typescript support

Vite Setup

Done! You have created a new Vite project.

Follow the steps below to start the dev server after installing the dependencies

cd svelte-vite-starter
npm install
npm run dev

You can follow the official documentation for Getting started with Vite.

Starting Vite development server

After running the server, you should be able to see the counter on the page. Let’s build something a little more fun using some open API. We will build a random cat fact generator.

We will make use of this API to get random facts

https://catfact.ninja/

Create a new svelte file and name is as CatFacts.svelte

Script

<script>
	import { onMount } from "svelte";

	let promise;
	onMount(async () => {
		promise = getRandomCatFacts();
	});

	const getRandomCatFacts = async () => {
		const res = await fetch("https://catfact.ninja/fact");
		const json = await res.json();

		if (json.fact) {
			return json.fact;
		} else {
			throw new Error("Not found any interesting facts");
		}
	};

	const reload = () => {
		promise = getRandomCatFacts();
	};
</script>

We are creating a function that will call the API to get a random cat fact. Since it is an async function, it will return a Promise when calling the function. That promise is getting stored in the variable and then used in the HTML to display the result of the promise.

onMount is a lifecycle method from Svelte which will be called automatically when the component is loaded in the UI for the first time. So we can use this lifecycle method to call the API to get our facts for the first time.

HTML

<main>
	<h1>Cat Facts</h1>
	<div class="cat-fact-container">
		{#await promise}
			<p>...loading...</p>
		{:then fact}
			<p>{fact}</p>
		{:catch error}
			<p style="color: red">{error.message}</p>
		{/await}
	</div>

	<button on:click={() => reload()}>One more fact</button>
</main>

We are using the svelte syntax of await to wait for the promise to finish. At the time of loading the API, UI will show the loading message. After the result is fetched, the fact is displayed on the screen. If there is any error, we are showing that as well in the UI. So either the then block or the catch block is displayed on the screen based on the result of the promise

We also have another button to call the API again and giving us a new and interesting fact

Output.PNG

Style

If you want a similar style to what is done in the example, you can have a look at these simple CSS styles for the component

<style>
	.cat-fact-container {
		border: 0.2rem solid #ccc;
		padding: 5rem;
		margin: 2rem;
		border-radius: 1rem;
		background-color: beige;
	}

	button {
		padding: 1rem 2rem;
		background-color: olive;
		color: white;
		font-weight: bold;
		text-transform: uppercase;
		border: 0px;
		border-radius: 1rem;
		box-shadow: 2px 2px 5px grey;
	}
</style>

Building Vite for production

Building the app for production is also easy as you can just run a command and vite will generate the dist folder.

npm run build

After running this command, you can check to see if the dist folder is created.

After the build is generated, you can verify if the build is working properly using another command in Vite

npm run serve

**Output:**
vite preview

  > Local: http://localhost:5000/
  > Network: use `--host` to expose

This command internally call the vite preview command and it helps serve the files in the dist folder in your local so as to verify the production build.

Deploy the static site

Follow the documentation provided in the Vite docs to deploy the application based on the cloud provider of your choice

https://vitejs.dev/guide/static-deploy.html

Summary

Svelte and Vite are really good tools for building your next side project and will help in making the developer experience a really smooth process. If you have any questions or comments, join our discord server and we can have a discussion

Discord - https://discord.gg/AUjrcK6eep