🧑🏽🍳 What is vanilla-extract?In this post we look at how to get started using vanilla-extract with SvelteKit. Before we get going though, we should spend a moment looking at what vanilla-extract is and why you might want to use in a project or at least try it out.
vanilla-extract is a modern Cascading Style Sheets (CSS) preprocessor, which generates plain CSS stylesheets. It is TypeScript friendly and leans on TypeScript to add some extra useful features. You can create your style in TypeScript files which sit alongside your Svelte code and import the styles, adding them as classes to your components. The way you use them is similar to CSS modules usage pattern.
We'll get a proper introduction shortly, but here's a sneak peak as a teaser. Here we define some style in our
then consume it it a Svelte file:
The CSS is generated at compile time, meaning there is no overhead at runtime (when the user opens up the page). Having TypeScript support allows you create styling policies and ensure they are enforced by your team (or even by you when you return to the code in six months' time).
We will look at an example of theming our site. In doing so, we will create a theme contract (this is quite straightforward) and just means if we decide to add a Christmas theme in a month we can be fairly comfortable it won't break the site as long as we define the colours etc, required by the theme.
😕 How is vanilla-extract different to vanilla CSS, Sass, Tailwind etc.?
I first heard about vanilla-extract on the JS Party podcast. They had a show on the process Shopify used for replacing Sass . I won't tell you what they opted for, in case you want to listen to the show! Anyway Shopify generated a grid of the pros and cons for each solution , comparing Sass, CSS, Tailwind and other frameworks. If you are looking at switching CSS tooling, definitely consider adapting that grid to your own use case to help inform your decision process. On top there is a top notch GitHub discussion on replacing Sass too . Although titled “Replacing Sass”, the process was open and keeping Sass was a possible solution. Hopefully those resources answer any questions you have on the relative merits of the different solutions.
🌟 Why use vanilla-extract for styling?
I like vanilla-extract for a few things, probably the most important ones to me are:
- it is modern with wide support — although we focus on SvelteKit here, vanilla-extract works with ESBuild, Vite and Snowpack as well as Next.js and other React site generators ,
- you create efficient CSS files with zero runtime overhead,
- contracts offer a built-in way of enforcing styles, and preventing issues like colour drift over time. This is where, for example, you might hardcode a colour in CSS while debugging or checking contrast ratio and forget to swap it out for a variable.
🧱 What we're Building
We'll knock up a minimal Single Page App advertising a couple of courses for a fictitious event. We will:
- see how to configure vanilla-extract for SvelteKit,
- create a couple of themes,
- add a contract for new themes so they need to have all our colour variables defined.
As well as seeing the vanilla-extract features in action we will see how to store the chosen theme in the browser local storage and a little bit of animations in SvelteKit. If there's anything there you can get excited about then let's get started.
⚙️ Using vanilla-extract with SvelteKit: Getting Started
Create a new SvelteKit skeleton TypeScript project:
From the options, choose Skeleton project, Use TypeScript:? Yes, Add ESLint...? Yes and Add Prettier...? Yes. Next we install the vanilla-extract plugins and some other packages we will use later, then start up the dev server:
🔨 Using vanilla-extract with SvelteKit: SvelteKit Setup for vanilla-extract
Next we will add vanilla-extract configuration to
svelte.config.js. Thanks to Ben Jervis from the vanilla-extract maintainer team for helping to get this config working. vanilla-extract is not yet (at time of writing) a 100% ESM compatible package. Without the
vite/ssr config (below) you can currently run a site in dev mode though to build, you will need the extra parameters. Update
svelte.config.js to get started:
20 we are added the
imagetools plugin as well as
vanillaExtractPlugin(). The former is not strictly needed for running vanilla-extract though we will use it on this site to help with processing images.
vite/ssr parameters (lines
26) needed for building the site seem to break the dev site so we have a switch to change the config based on whether we have run
pnpm run dev or
pnpm run build. If you are quite new to SvelteKit, I should explain,
pnpm run dev lets you develop the site, with fast, hot reloading so when you change something it is updated straight away in your browser. Each time you integrate a new feature, it is a good idea to run
pnpm run build to generate a production-ready site and then
pnpm run preview to view that production-ready version of your site. Hopefully that makes the first part of the paragraph clearer!
For type consistency add the Lazyload type to the browser document (this is the
src/global.t.ds in your project):
As a last bit of setup, download a couple of images (blake.jpg and river.jpg ) which we will use on the site. Place these in a new
src/lib/assets folder. Finally, create a JSON file containing event details as
src/lib/data below. Next, we will add our global vanilla-extract styles and variables.
Learn more about importing JSON in SvelteKit in the video on SvelteKit JSON data import.
💄 Vanilla Extract Styles
Let's create a styles folder and add some vanilla-extract to our project. Create a new directory at
src/lib.styles. In there create
styles.css.ts and paste in the following content:
In the first file you see how you can declare variables in vanilla-extract. Using variables is handy when working with a design system and lets you easily change styles across the project quickly. Later we will use these variables when styling our Svelte components. The second file contains our global styles. In there we define the variables (give them values) and also set some other global CSS like font families, much like you would in CSS or Sass.
Using vanilla-extract with SvelteKit: Theming
We're only going to scratch the surface on what vanilla-extract can do with theming here. We will create a theme template which will act as our theme contract. We then use that template to create a summer and winter colour theme. Create a
src/lib/styles/themes folder and in there create
theme.css.ts and paste the content below. This will be our template.
We are only varying colours by theme, but in a fully-fleshed out project, you might add fonts, accessible styling and a whole host of other elements. We will see in a moment when we create a actual themes, we will get a TypeScript error if we forget to define one of the theme colours. This can be great when working in teams or on long-term projects making it harder to break the site by adding new themes.
Let's create the summer and winter themes in the same folder:
Try commenting out one of lines where you define a colour in the
winterTheme.css.ts file. You should get a warning in your code editor that a colour is missing. This is one of the advantages TypeScript brings to the party. Next we will create some components and use these themes.
🏠 Home Page Styles
With vanilla-extract, we can define styles in a TypeScript file which sits alongside the page or component they will be used in. Then we import them into the Svelte file. Let's create
src/routes/index.css.ts which will contain the styles needed for the home page:
We see in line
1 that we import the template theme we just created. Then throughout the file, we reference this. In our svelte component, we will add the class for the current theme. vanilla-extract will generate the all the CSS we need for handling themes.
You will notice we are importing and using variables defined in our
styles folder. In line
41 you can see an example of using our existing CSS variables to calculate the
minHeight for a text element.
We will use the browser local storage to keep track of which theme the user prefers. Svelte stores will provide an interface between our components and local storage. Make a store by creating
src/lib/shared/stores/theme.ts and adding the following content:
5 we set the default value for the store, which is used when the page first loads. It checks if there is a value already stored in the local storage for theme and defaults to summer. The code in line
10 runs when our components update the store and sets the theme to the value passed in.
🧩 Using vanilla-extract with SvelteKit: Components
Before we add the markup for the home page, we will add some components which get used in the home page. Naturally, these components will also use vanilla-extract so we will continue learning on the way. Create a components folder at
src/lib/components and add
Card.css.ts file with the following content:
Now we can create
Card.svelte which will import these styles:
This lets us see a few things. In line
7 we can access the store with
$theme (we imported the file in line
2). All we do here is check what the theme is. We use the store as a central source of truth, accessible in components. This means we don't have to pass the theme as a prop between components. We imported styles from the
Card style file in line
5. As an example, in line
11, you add the
container class variable to the
section element. vanilla-extract does the magic to convert this to a class with a unique name and also generate the CSS.
The last interesting line here is line
8 where we add the right class variable depending on the current theme. We imported the themes in lines
Speaker Picture Component
Let's pick up the pace now and paste in a couple of files for pictures we use. We add the responsive image boiler plate in full here, though for a larger project, it is probably worth using an image component to help.
If anything here needs more explanation let me know and I can update the post.
Home Page ❤️ Svelte
We're back home! Replace the content in
In terms of vanilla-extract we're not introducing new concepts here, which we haven't seen in other components. You might notice we have added some animation. Let me know if you would like a separate post focussing on animation with SvelteKit. Svelte does make it easy to add a little polish with not too much effort. We will just gloss over some details here so this post doesn't get too long.
63 we use the
key keyword to let SvelteKit know which variable change will trigger the animation. Here, this is
currentIndex which changes between zero and one. The dynamic parts are within the
Card, but we can set animation parameters in a parent element. We do that in line
65 on the main element. There are a lot of different easing functions you can use. Josh Nussbaum has put together a nice little playground to experiment with . You can also learn more about Svelte Transitions in the official tutorial .
The final piece of the puzzle before testing is the layout. In our layout component, we will add a switch for changing theme and also the related code for updating the store. First add the styles to a new file:
Then let's paste in the Svelte (
src/routes/__layout.svelte) and take a quick look.
The most interesting part here is line
27. When the user clicks the button, we change the theme in the store by calling
theme.set(). This changes the theme for all components. On top it triggers the code in our store file which sets the theme in local storage.
💯 SvelteKit Infinite Scroll: Testing
That was a lot to get through! Thanks for following through to the end. Go get a drink then and some fresh air so you can fully appreciate testing!
Everything should be working now so you can go to localhost:3000 to take the site for spin.
Inspect one of the site's elements and see what class you find. You should see something like this:
vanilla-extract has generated a unique class name, giving us scoped styling without the need for BEM or a similar system. Next, in your browser developer tools, open up Local Storage. You should see something like:
Try toggling theme to make sure this changes. Finally run
pnpm run build then in your code editor find
build/_app/assets/winterTheme.css. ... .css. This is an example of the CSS files created by vanilla-extract.
If that's all worked give yourself a star!
🙌🏽 Using vanilla-extract with SvelteKit: What we Learned
In this post we learned:
some vanilla-extract basics,
configuration for using vanilla-extract with SvelteKit,
a cheeky peek at how to set up animation in SvelteKit.
I do hope there is at least one thing in this article which you can use in your work or a side project. There is a lot more you can learn on vanilla-extract. Continue exploring by heading over to the official vanilla-extract documentation . You can see the full working example at sveltekit-vanilla-extract.rodneylab.com/ .
As always get in touch with feedback if I have missed a trick somewhere! You can see the full code for this using vanilla-extract with SvelteKit tutorial on the Rodney Lab Git Hub repo .
🙏🏽 Using vanilla-extract with SvelteKit: Feedback
Have you found the post useful? Do you have your own methods for solving this problem? Let me know your solution. Would you like to see posts on another topic instead? Get in touch with ideas for new posts. Also if you like my writing style, get in touch if I can write some posts for your company site on a consultancy basis. Read on to find ways to get in touch, further below. If you want to support posts similar to this one and can spare a few dollars, euros or pounds, please consider supporting me through Buy me a Coffee.
Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on Twitter and also askRodney on Telegram . Also, see further ways to get in touch with Rodney Lab. I post regularly on SvelteKit as well as other topics. Also subscribe to the newsletter to keep up-to-date with our latest projects.