How to setup Svelte SPA with Vite and Tailwind CSS
Short guide on how to integrate Tailwind CSS into a plain Svelte SPA
I needed to throw together a small Svelte SPA with Vite and Tailwind CSS. There are many existing templates on Github, but it's good to know how to do it yourself.
Thought I might as well write it down in case I forget it. Here are the instructions.
1. Create new Vite project#
I normally use pnpm
, but the commands for npm
should be the same.
$ pnpm create vite
Follow the instructions and choose Svelte
template. TypeScript or plain, doesn't really matter.
2. Add PostCSS and Tailwind CSS#
Next step is to add Tailwind CSS and then initialize it.
$ pnpm add -D tailwindcss autoprefixer postcss-load-config
$ pnpx tailwindcss init tailwind.config.cjs
Make sure to include the correct file glob patterns in the content
property of the Tailwind CSS configuration file.
module.exports = {
content: [
'./index.html',
'./src/**/*.svelte'
],
theme: {
extend: {},
},
plugins: [],
}
Vite has built-in support for PostCSS, but we still need to create PostCSS config and add Tailwind to it.
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
}
}
You also might want to create a main CSS file in case you plan to support re-usable styles in your application.
@tailwind base;
@tailwind components;
@tailwind utilities;
Voila! We now have a minimal working Tailwind setup. Let's put it to use.
3. Use Tailwind in Svelte files#
You don't need any svelte.config.js
file with svelte-prerocess
nonsense, @sveltejs/vite-plugin-svelte got you covered here.
<script>
import "./index.css";
</script>
<h1 class="text-4xl font-extrabold">Yo!</h1>
<p class="meta">This is some meta text</p>
<style lang="postcss">
.meta {
@apply mt-4 text-gray-600;
}
</style>
That's all there is to it. Happy hacking!