20 March 2023

How to add tailwind to an existing svelte project

#svelte#tailwindcss#rollup#web

If you are working on an existing Svelte project created with Svelte template and with already existing styles such as Sass or Less, this blog post will show you how to add and configure Tailwind CSS in your project.

1. Installing tailwind and its dependencies

Install Tailwind CSS as a PostCSS plugin.

npm i -D tailwindcss autoprefixer postcss

2. Creating tailwind config file

Configure Tailwind CSS to compile Svelte components with Tailwind CSS styles.

Initialize empty Tailwind CSS config, the command below will generate tailwind.config.js file.

npx tailwindcss init

And then edit content property to specify which files use Tailwind CSS.

// tailwind.config.js

{
    content: [ './src/**/*.{html,svelte}' ]
    ...
}

The whole config file might look like this:

// tailwind.config.js

/** @type {import('tailwindcss').Config} */
module.exports = {
    content: [ './src/**/*.{html,svelte}' ],
    theme: {
        extend: {},
    },
    plugins: [],
}

3. Configuring rollup to use tailwind

Configure PostCSS to use Tailwind CSS as a plugin.

You already should have svelte-preprocess if you are using any other CSS language like Sass or Less. I import svelte-preprocess as preprocess.

// rollup.config.js

import preprocess from 'svelte-preprocess';

Then add necessary plugins to postcss property of preprocess in rollup.config.js

// rollup.config.js

preprocess: preprocess({
    ...
    postcss: {
        plugins: [
            require('tailwindcss'),
            require('autoprefixer')
        ]
    }
})

4. Creating a tailwind provider

As you already might have styles in your App.svelte, create a TailwindProvider.svelte which will import Tailwind CSS and provide it to your application.

// src/TailwindProvider.svelte

<slot />

<style lang="postcss" global>
    @tailwind base;
    @tailwind components
    @tailwind utilities
</style>

After this, wrap content of your App.svelte with TailwindProvider.svelte

// src/App.svelte

<script>
    import TailwindProvider from './TailwindProvider.svelte';
    ...
</script>

<TailwindProvider>
    ...
</TailwindProvider>

Next steps

It is not recommended to mix styled components and Tailwind CSS. Your next steps should be to remove your custom styles and substitute them with the Tailwind CSS classes.

Use official Tailwind CSS reference to successfully migrate to it.

Conclusion

In conclusion, installing Tailwind CSS into an existing Svelte project might seem daughnting, but by following steps provided in this post, you can set it up quickly and easily.

If you enjoyed the content, consider supporting the blog.

Donate