Use Sveltekit and Tailwind CSS
Asked Answered
U

2

9

Sveltekit is finally in public beta. Does anyone know how to use it with Tailwind CSS? There aren't any official docs for this integration.

Unemployable answered 25/3, 2021 at 14:34 Comment(0)
O
21

Since you're using SvelteKit, you can also look at using the Svelte Adder for Tailwind.

From their README:

You must start with a fresh copy of the official SvelteKit template, which is currently created by running this command:

npm init svelte@next

Once that is set up, run this command in your project directory to set up Tailwind CSS:

npx svelte-add tailwindcss # --jit

That command will perform the Tailwind setup for you, so you don't have to create all the configs yourself.

Orthocephalic answered 25/3, 2021 at 14:58 Comment(2)
almost too easy! Seriously though, very nice! was excited to see a similar adder for Bulma.ioTandie
Just a note there's currently a bug with it: github.com/svelte-add/tailwindcss/issues/…Viewfinder
U
9

Luckily, setting up Tailwind CSS in Sveltekit is easy.

1. Install Sveltekit

If you don't have a Sveltekit project already, now's the time to create one.

npm init svelte@next
npm install

2. Install Tailwind CSS

Assuming you already have Svelte

npm install -D tailwindcss@latest postcss@latest autoprefixer@latest

If you want to use just in type compilation for Tailwind, install that, too.

npm install -D @tailwindcss/jit

3. Run Tailwind setup

npx tailwindcss init -p

Next, change the created tailwind.config.js to a commonjs module by renaming it to tailwind.config.cjs. You just need to change the extension to cjs.

Then, inside the config, setup which pages/components to purge from.

// tailwind.config.cjs
module.exports = {
    purge: ['src/app.html', 'src/**/*.svelte'],
...
}

4. Create styles.css

Create a styles.css file in the src folder.

// ./src/style.css
@tailwind base;
@tailwind components;
@tailwind utilities;

Now, create a layout component to import the styles from.

// ./src/routes/$layout.svelte
<script>
    import '../style.css';
</script>

5. Connect Sveltekit with Tailwind

This is the final step.

In your svelte.config.cjs file, add postcss as a preprocessor.

// svelte.config.cjs
module.exports = {
    // add this
    preprocess: sveltePreprocess({
        postcss: true,
        defaults: {
            style: 'postcss',
        },
    }),
}

And create a postcss.config.cjs file in the root of the project.

// postcss.config.cjs
module.exports = {
    plugins: {
        'tailwindcss': {},
        autoprefixer: {},
    },
};

If you're using @tailwindcss/jit, replace tailwindcss above with @tailwindcss/jit.

That's it! You're now ready to use Sveltekit and Tailwind CSS.

P.S. Credit goes to Matt Lehrer for writing a great blog post on the subject.

Unemployable answered 25/3, 2021 at 14:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.