lv.
a maple leave logo

Setup UnoCSS with SvelteKit


What is UnoCSS?

Unocss is a utility-first CSS framework that is alternative to Tailwind CSS.

How to setup UnoCSS with SvelteKit

In this tutorial, we will be using JavaScript. If you want to use TypeScript, you can follow the same steps but with TypeScript.

Here is a playground for you to try out. Sveltekit + UnoCSS Playground

Install dependencies

npm install -D unocss @unocss/svelte-scoped/vite

Create a unocss.config.js file

Here we will be using the default preset. More about preset here.

import { defineConfig, presetUno } from 'unocss';

export default defineConfig({
	presets: [presetUno()],
});

Config the Vite plugin

In your vite.config.js file, add the svelte-scoped UnoCSS plugin. This allow UnoCSS to be used scoped styles in your SvelteKit app.

import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
import UnoCSS from '@unocss/svelte-scoped/vite';

export default defineConfig({
	plugins: [sveltekit(), UnoCSS()]
});

Make change to app.html

In your app.html file, add %unocss-svelte-scoped.global%to the <head> tag as shown below.

<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<link rel="icon" href="%sveltekit.assets%/favicon.png" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		%unocss-svelte-scoped.global%
		%sveltekit.head%
	</head>
	<body data-sveltekit-preload-data="hover">
		<div style="display: contents">%sveltekit.body%</div>
	</body>
</html>

Inject UnoCSS into your SvelteKit app

In your hooks.server.js file, create one if you don’t have one, under the src folder. In below example, I use sequence so that we could chain multiple hooks together if needed.

import { sequence } from '@sveltejs/kit/hooks';

export const unocssInject = async ({ event, resolve }) => {
	const response = await resolve(event, {
		transformPageChunk: ({ html }) =>
			html.replace('%unocss-svelte-scoped.global%', 'unocss_svelte_scoped_global_styles')
	});
	return response;
};

export const handle = sequence(unocssInject);

There you go! Now you can use UnoCSS in your SvelteKit app!

Example

Supported SyntaxExample
Class attribute<div class="mb-1" />
Class directive<div class:mb-1={condition} />
Class directive shorthand<div class:logo />
Class prop<Button class="mb-1" />

Try it out.

// uno.config.js
export default defineConfig({
	presets: [
		presetUno()
		// ...custom presets
	],
	shortcuts: {
		foo: 'bg-red-500 text-white'
	}
});
// Demo.svelte
<script>
 let foo = false
</script>


<p class:foo>
    Change me
</p>
<button on:click={() => foo = !foo}>Toggle style</button>

More info about preset

For more info about UnoCSS preset, check out the UnoCSS Preset

Thanks for reading!