DEV Community

webdev03
webdev03

Posted on

Setting up SvelteKit with TailwindCSS

Hello everyone. This is my first post on the dev.to community so I hope you all like it! :D

In this tutorial I will go over the process of setting up SvelteKit with Tailwind CSS.

Setting up your SvelteKit project

So, to set up a basic SvelteKit project, you can run this command.

npm init svelte@next tailwind-sveltekit 
Enter fullscreen mode Exit fullscreen mode

You can replace tailwind-sveltekit with whatever directory name you want, or if you are already in the directory you want to use, you can remove it.

Now you can run

npm install
Enter fullscreen mode Exit fullscreen mode

(or you can use any package manager you like such as pnpm or yarn)
and

npm run dev
Enter fullscreen mode Exit fullscreen mode

Adding Tailwind

To add TailwindCSS, we will also need to use PostCSS.
So, first, run this command in your terminal.

npm install -D tailwindcss postcss autoprefixer
Enter fullscreen mode Exit fullscreen mode

You will now have Tailwind, PostCSS, and Autoprefixer installed.
After that, run

npx tailwindcss init -p
Enter fullscreen mode Exit fullscreen mode

This will create two files, tailwind.config.js and postcss.config.js for you.
Now, you need to rename these files. SvelteKit doesn't accept .js files so change the file names to tailwind.config.cjs and postcss.config.cjs instead.
In your src/ folder of your project, create a folder called lib if you haven't already. Inside, create a tailwind.css file and add this into the file.

@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

In your src/routes/ you can make a __layout.svelte file with this inside of it:

<script>
import "$lib/tailwind.css";
</script>
<div class="pt-2">
  <slot />
</div>
Enter fullscreen mode Exit fullscreen mode

Now you can npm run dev and see it. But you may have noticed something off.
TailwindCSS doesn't know about your Svelte code and so the Just-in-Time engine will only include the base style reset. So in your tailwind.config.cjs file you should change it to

module.exports = {
  content: ['./src/**/*.{js,ts,svelte}'],
  theme: {
    extend: {},
  },
  plugins: [],
}

Enter fullscreen mode Exit fullscreen mode

The content property is what has changed. This lets Tailwind know that your class names are there, so the JIT engine will know what to generate.

Conclusion

I hope you enjoyed this tutorial. If you have any questions, please let me know. :D

Top comments (0)