Sveltekit Vite with Tailwind 2
Tags: svelte, javascript, boilerplate
Published: 2020-12-14 16:06:06

svelte@next with postcss and tailwind

#### UPDATE : 
5.update to SvelteKit Vite, all work. This post outdate and will not maintain anymore, check the repo
4.add demo
3.make `run build` export static `build/` directory
2.fix `run build` error
1.fix huge error

## S T O P
```
Pump the brakes! A little disclaimer...

svelte@next is not ready for use yet. It definitely can't
run your apps, and it might not run at all.

We haven't yet started accepting community contributions,
and we don't need people to start raising issues yet.

Given these warnings, please feel free to experiment, but
you're on your own for now. We'll have something to show
soon.
```

Sapper v1 will never be released, instead Svelte is being developed further. For more information, please check out the jessenkinner post at dev.to : [Sapper is dead, what is next in Svelte?](https://dev.to/jesseskinner/sapper-is-dead-what-s-next-in-svelte-4pbc)

However, that didn't stop me from trying it wholeheartedly.

By the way, I just got to know pnpm and was very happy to know and use it. So I'm going to use `pnpm` instead of `npm` or `yarn`, although they both have the same use.

## Create Svelte project
for now, you can run this command in your terminal, assuming you have `pnpm` installed : 
```
pnpm init svelte@next svelte-next
cd svelte-next
pnpm i
```

Where `svelte-next` is the name of your project directory. You can choose if you want to use typescript or not.

Before going any further, we can ensure that the current version is *"ok"* to develop by running the command below and accessing `localhost:3000` in the browser.
```
pnpm run dev
```

If you got error like this
```
Error: NOT_FOUND
    at Object.loadUrl (C:\Users\hp\www\sveltest\node_modules\.pnpm\snowpack@3.0.0-rc.2\node_modules\snowpack\src\commands\dev.ts:607:13)
    at C:\Users\hp\www\sveltest\node_modules\.pnpm\@sveltejs\kit@1.0.0-next.15\node_modules\@sveltejs\kit\src\api\dev\index.js:167:14
```

it seems like there problem in the snowpack configuration, so edit `plugins` line to like this
```js
    plugins: [
        [
            "@snowpack/plugin-svelte",
            {
                compilerOptions: {
                    hydratable: true
                }
            }
        ],
        '@snowpack/plugin-typescript'
    ],
```
stop and rerun the dev server

## Setting up the preprocess
**If** you are not using typescript, then you need to add the preprocess manualy by run this command
```
pnpm i -D svelte-preprocess
```

Then apply the preprocess to svelte add PostCSS to it
```js
// svelte.config.js
const sveltePreprocess = require('svelte-preprocess');
module.exports = {
    // Consult https://github.com/sveltejs/svelte-preprocess
    // for more information about preprocessors
    preprocess: [
        sveltePreprocess({
            defaults: {
                script: 'typescript',
                style: 'postcss',
            },
            postcss: true
        }),
    ],
	kit: {
		// By default, `npm run build` will create a standard Node app.
		// You can create optimized builds for different platforms by
		// specifying a different adapter
		adapter: '@sveltejs/adapter-node',

		// hydrate the <div id="svelte"> element in src/app.html
		target: '#svelte'
	}
};
```

The `default` object property that defines the default languages of your components. so the configuration above makes TypeScript the default language, removing the need of adding `lang="ts"` to script tags and `lang="postcss"` to style tags.

## Add PostCSS and Tailwind
```
pnpm add -D @snowpack/plugin-postcss postcss postcss-cli postcss-load-config postcss-preset-env
pnpm add -D tailwindcss autoprefixer cssnano
```
Because svelte@next still in development, maybe you wont to bring it to production, you may just skip `autoprefixer` or `cssnano` if you don't need them.

I just use `postcss-preset-env` for nesting, you can use other plugin like `postcss-nesting` or else.

## Setting up PostCSS
Edit the Snowpack Configuration file
```js
// snowpack.config.js
// Consult https://www.snowpack.dev to learn about these options
module.exports = {
	extends: '@sveltejs/snowpack-config',
	plugins: [
        [
            '@snowpack/plugin-build-script',
            {
                cmd: "postcss",
                input: [".css", ".pcss"],
                output: [".css"],
            }
        ],
        [
            "@snowpack/plugin-svelte",
            {
                compilerOptions: {
                    hydratable: true
                }
            }
        ],
	    '@snowpack/plugin-typescript'
    ],
	mount: {
		'src/components': '/_components'
	},
	alias: {
		$components: './src/components'
	}
};

```

Create PostCSS configuration file in the project's root folder. Shomething like this.
```js
// postcss.config.js
const mode = process.env.NODE_ENV;
const dev = mode === "development";

module.exports = {
    plugins: [
        require('postcss-preset-env')({stage: 1}),
        require("tailwindcss"),
        require("autoprefixer"),

        !dev && require("cssnano")({
            preset: "default",
        }),
    ],
};
```

## Setting up Tailwind
Run this command 
```
npx tailwind init
```

Edit Tailwind configuration
```js
// taiwind.config.js
const { tailwindExtractor } = require("tailwindcss/lib/lib/purgeUnusedStyles");

module.exports = {
	purge: {
		content: [
			"./src/**/*.html",
			"./src/**/*.svelte"
		],
		options: {
			defaultExtractor: (content) => [
				...tailwindExtractor(content),
				...[...content.matchAll(/(?:class:)*([\w\d-/:%.]+)/gm)].map(([_match, group, ..._rest]) => group),
			],
			keyframes: true,
		},
	},
    darkMode: 'class',
	theme: {
		extend: {},
	},
	variants: {
		extend: {},
	},
	plugins: [],
};
```

the tailwindExtractor is for future purpose, so you can use `class:` directive

## Tailwind ready to use

Create `src\routes\global.pcss`
```css
@tailwind base;
@tailwind components;
@tailwind utilities;

```

then use it on `src\routes\$layout.svelte`
```html
<script>
	import './global.pcss';
</script>

<slot/>
```

on the `src\routes\index.svelte`
```html
<script>
	import Counter from '$components/Counter.svelte';
</script>

<main>
	<h1 class="uppercase text-5xl font-extrabold my-16">Hello world!</h1>

	<Counter/>
	<p>Visit the <a href="https://svelte.dev">svelte.dev</a> to learn how to build Svelte apps.</p>
</main>

<style>
  main {
    @apply px-8 py-16 mx-auto max-w-5xl text-center;
  }

  * + * {
    @apply mb-0 mt-4;
  }

  p {
    @apply text-xl;
  }
</style>
```

## The boileplate

![Sveltekit with Tailwind](https://dev-to-uploads.s3.amazonaws.com/i/yyqy860f5z4n4vk8euzz.png)

If you want to try ready to use boiler plate I made with dark mode toggle theme, you can check my reposistory [here](https://github.com/dansvel/sveltekit-typescript-postcss-tailwind2) 

#### UPDATE : 
 - to generate static site you can deploy in netlify, just run build command, i already update the repo
 - [**Live Demo**](https://sveltekit-tailwind2.netlify.app/)

*Still learning to write post in English. Please be advised.*

*comment if you find another error*

thanks