Install Tailwind CSS Svelte
Tailwind CSS is a CSS framework designed to be used with modular predefined classes instead of custom classes for each element. We will go over how to install Tailwind CSS and set it up to build with Svelte.
Install Tailwind
First you need to install Tailwind and it's dependences then run the Tailwind npx
command to setup your project.
1npm install -D tailwindcss postcss autoprefixer
2npx tailwindcss init tailwind.config.cjs -p
Configuration
To properly setup Tailwind you need to make a few changes to your files. In the svelte.config.js
file add the line below, below the import adapter
line.
1import { vitePreprocess } from "@sveltejs/kit/vite";
Set the preprocessor by adding preprocess: vitePreprocess()
to the config object in svelte.config.js
like below:
1/** @type {import('@sveltejs/kit').Config} */
2const config = {
3 kit: {
4 adapter: adapter(),
5 },
6 preprocess: vitePreprocess(),
7};
After running the npx
command, you should have a tailwind.config.cjs
file, add content: ['./src/**/*.{html,js,svelte,ts}'],
to the module.exports
object to enable auto parsing for Tailwind.
1/** @type {import('tailwindcss').Config} */
2module.exports = {
3 content: ["./src/**/*.{html,js,svelte,ts}"],
4 theme: {
5 extend: {},
6 },
7 plugins: [],
8};
Importing Tailwind into Svelte
To import tailwind classes into you app, add the following Tailwind directives into your app.css
file.
1@tailwind base;
2@tailwind components;
3@tailwind utilities;
Then import the app.css
file into your +layout.svelte
.
1<script>
2 import "../app.css";
3</script>
4
5<slot />
Running
Now Tailwind should be up and running, test it by running the following command.
1npm run dev