Configuring TailwindCSS for Sapper
Tags: javascript, svelte, tailwindcss, sapper
Published: 2020-01-31 06:46:05

This article is Part III of my first three posts about Svelte. Part I described [how to create Statically generated website with Svelte and Sapper](https://dev.to/vannsl/statically-generated-website-with-svelte-and-sapper-5bi7). Part II discusses [Svelte Single File Components](https://dev.to/vannsl/all-you-need-to-know-to-start-writing-svelte-single-file-components-cbd) in more detail.

In this article we will configure [TailwindCSS](https://tailwindcss.com/) for [Svelte](https://svelte.dev/) + [Sapper](https://sapper.svelte.dev/).

**Versions:**
Svelte: 3.18.0
Sapper: 0.27.9 (! early state)
TailwindCSS: 1.1.4
@fullhuman/postcss-purgecss: 1.3.0
PostCSS: 7.0.26
PostCSS-CLI: 7.1.0
PostCSS-Load-Config: 2.1.0

## TL;DR

I forked the official [sapper-template](https://www.google.com/search?client=firefox-b-d&q=sapper+template) repository. It includes the integration of TailwindCSS, PostCSS and PurgeCSS. You can install the [sapper-tailwindcss-template](https://github.com/Vannsl/sapper-tailwindcss-template) repository. Then you don't have to go through the Step by Step Guide below. To use it, execute the following commands:

```bash
npx degit "vannsl/sapper-tailwindcss-template#rollup" sapper-tailwindcss-template
# or
npx degit "vannsl/sapper-tailwindcss-template#webpack" sapper-tailwindcss-template
cd sapper-tailwindcss-template
npm install
```

To start the local server and watch tailwind, execute these two commands in **separated** windows of your terminal:

```bash
npm run dev:tailwindcss
```

```bash
npm run dev
```

{% github Vannsl/sapper-tailwindcss-template %}

## Existing methods

On Github, there already exists a [TailwindCSS Setup Example for Sapper](https://github.com/tailwindcss/setup-examples/tree/master/examples/sapper). Although the general setup works, I had problems with [PurgeCSS](https://purgecss.com/). The not used CSS of the TailwindCSS Framework was not removed when **exporting** a static version of my Sapper application. Maybe I did something wrong.

I did a bit of research and after a few try and error approaches, I finally got it to work. Here's the Step by Step Guide:

## Step by Step Guide

In the following, we'll install Sapper and TailwindCSS.

### Create a Sapper app

The following commands will install the example project for Sapper using the [Rollup](https://rollupjs.org/guide/en/) Configuration:

```bash
npx degit "sveltejs/sapper-template#rollup" sapper-tailwindcss
# or
npx degit "sveltejs/sapper-template#webpack" sapper-tailwindcss
cd sapper-tailwindcss
npm install
```

Now your Sapper application is installed. Run `npm run dev` to start the local server. Open [http://localhost:3000](http://localhost:3000) to check out the example project.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/k3ym9ozmybuk5fg5owmy.png)

### Download TailwindCSS, PostCSS and PurgeCSS

The following commands will download the packages for [PostCSS](https://postcss.org/) and [TailwindCSS](https://tailwindcss.com/) as [devDependencies](https://docs.npmjs.com/specifying-dependencies-and-devdependencies-in-a-package-json-file) and [PurgeCSS](https://purgecss.com/) as a dependency:

```bash
npm install -D postcss-cli tailwindcss --save
npm install @fullhuman/postcss-purgecss --save
```

### Create the Configurations

The order of the following steps is not important. It will only work when all of the following changes are implemented.

### tailwind.config.js

Afterward, initialize TailwindCSS with:

```bash
npx tailwind init
```

This command creates the file `tailwind.config.js` in the root directory of your project. It contains the following skeleton:

```js
// tailwind.config.js

module.exports = {
  theme: {
    extend: {}
  },
  variants: {},
  plugins: []
}
```

For more information on how to customize TailwindCSS, please read the [official TailwindCSS configuration documentation](https://tailwindcss.com/docs/configuration). You can leave it for now as it is.

### postcss.config.js

Create an empty file with the name `postcss.config.js`. Either by creating this file in your IDE or finder or by executing the following command (if macOS) in the root folder of the sapper application:

```bash
touch postcss.config.js
```

Afterward, append the following content to the file:

```js
// postcss.config.js

const tailwindcss = require("tailwindcss");

const purgecss = require("@fullhuman/postcss-purgecss")({
  content: ["./src/**/*.svelte", "./src/**/*.html"],
  defaultExtractor: content => content.match(/[A-Za-z0-9-_:/]+/g) || []
});

module.exports = {
  plugins: [
    tailwindcss("./tailwind.config.js"),

    ...(process.env.NODE_ENV === "production" ? [purgecss] : [])
  ]
};

```

### rollup.config.js/webpack.config.js

Nothing to do. I added that section here because other approaches include adding PostCSS to the rollup config. There is no need to do this when using the approach of this post.

### static/tailwind.css

Now it's time to add the TailwindCSS Styles to your project. Create a new CSS file in the statics directory.

```bash
cd static
touch tailwind.css
```

To import the TailwindCSS Styles, the rules have to be applied in this file:

```css
/* static/tailwind.css */

@tailwind base;
@tailwind components;
@tailwind utilities;
```

The name of the CSS file is not important. It's best practice to use names like `tailwind.css`, `main.css` or `global.css`. Since the skeleton project of Sapper already provides a `global.css`, this tutorial recommends to use the name `tailwind.css` to prevent conflicts. When using a Utility-Based CSS Framework the styles of the preconfigured `global.css` may not be needed. If you want to, you can also use this file and override the default settings.

> Note: This file can be used either for only adding TailwindCSS to the Sapper project or be extended with further global rules and styles. For example, custom CSS classes or [Font Faces](https://developer.mozilla.org/de/docs/Web/CSS/@font-face) can be registered here.

### package.json

Mostly done. To get the TailwindCSS CSS into the built application for dev and production mode, the following npm scripts in the `package.json` have to be added:

```js
// package.json

// ...
scripts: {
 // ...
 "dev:tailwindcss": "postcss static/tailwind.css -o static/main.css -w",
 "build:tailwindcss": "NODE_ENV=production postcss static/tailwind.css -o static/main.css",
 // ...
}
// ...
```

These commands will create (or override if already existing) the file `main.css` in the `static` folder. The first command `dev:tailwindcss` will create a CSS file including all of the TailwindCSS styles. Any change in your source code will be immediately applied to the website with hot module replacement. When executing PostCSS in the `production` environment with `NODE_ENV=production` the file `main.css` will include only the styles of TailwindCSS you're using in your application thanks to PurgeCSS. If you try out both versions, you should see a significant difference in the file size of `main.css`.

You don't need to name that file `main.css`. You can choose any name that's not taken yet in your project. In the next section, we'll import the built CSS file in our application. But first, we'll add the statement to execute `build:tailwindcss` when building or exporting the Sapper application. Therefore add `npm run build:tailwindcss && ` at the beginning of the `build` and `export` scripts:

```js
// package.json for rollup

// ...
scripts: {
 // ...
 // "dev:tailwindcss": "postcss static/tailwind.css -o static/main.css -w",
 // "build:tailwindcss": "NODE_ENV=production postcss static/tailwind.css -o static/main.css",
 "build": "npm run build:tailwindcss && sapper build --legacy",
 "export": "npm run build:tailwindcss && sapper export --legacy",
 // ...
}
// ...


// package.json for webpack

// ...
scripts: {
 // ...
 // "dev:tailwindcss": "postcss static/tailwind.css -o static/main.css -w",
 // "build:tailwindcss": "NODE_ENV=production postcss static/tailwind.css -o static/main.css",
 "build": "npm run build:tailwindcss && sapper build",
 "export": "npm run build:tailwindcss && sapper export",
 // ...
}
// ...
```

### .gitignore

If you've initialized a git repository, I recommend to add `/static/main.css` to your `.gitignore` file. For example, that's how the `.gitignore` of the Demo Git Repository looks like:

```bash
.DS_Store
/node_modules/
/src/node_modules/@sapper/
yarn-error.log
/cypress/screenshots/
/__sapper__/
/static/main.css
```

### src/template.html

To import the generated `main.css` file, add the following line in the file `src/template.html` just above the other import:

```html
<!-- src/template.html -->

<link rel="stylesheet" href="main.css">
```

### Running the project

To run the application in production more, execute `npm run build`. To generate the static site of the application, run `npm run export`. By adding `npm run build:tailwindcss` to these scripts in the `package.json`, the commands will automatically generate the file `main.css`.

To run the project locally, execute the following commands in **separated** windows of your terminal:

```bash
npm run dev:tailwindcss
```

```bash
npm run dev
```

👏 That's it. You're done. 👏