How to setup Tailwind CSS with PostCSS & Browsersync?
Tags: tailwindcss, html, gulp
Published: 2021-03-01 18:38:54

So, you want to start using Tailwind CSS for your next HTML project but don't know how to set it up with PostCSS & Browsersync? Please read this post till the end to start using it easily.

We will see how you can use Gulp js to automate browser reload on file saving, create an optimized version of Tailwind CSS, and optimize production images.

Tailwind CSS output needs to be optimized for production use. The development version for the CSS file is almost 4MB which is not good for production websites. [Read this for more details](https://tailwindcss.com/docs/optimizing-for-production).

So, ideally, you need an editable full version of Tailwind CSS while developing the project. And you need to optimize it for production. We also need to configure the server to watch our files for changes & reload the browser automatically after updates.

We will use gulp js for the automation to enhance our workflow.

### What will we achieve in the end?

* Launch development environment with browser auto-refresh & browser auto-sync
* Customize Tailwind CSS configuration as per your needs
* Build the optimized production version of Tailwind CSS
* Optimize all images for production

> You can find the following code on GitHub as [Tailwind CSS Boilerplate](https://github.com/salttechno/tailwindcss-boilerplate)

Let's start.

## Project Setup

Create a new directory and open it in VS Code.
```bash
mkdir tailwind-starter
cd tailwind-starter
code .
```

Install latest Tailwind CSS & dependencies.
```bash
npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
```
Remember that Tailwind CSS requires Node.js 12.13.0 or higher.

Next, let's generate our `tailwind.config.js` and `postcss.config.js` files:
```bash
npx tailwindcss init -p
```
PostCSS works as our preprocessor here. It will compile our Tailwind CSS file. We will use the `tailwind.config.js` file for configuring our Tailwind.

The first thing we will configure is the purge settings. Add our CSS files & HTML files in an array for purge settings. These are the locations where we will be using Tailwind classes.
```js
// tailwind.config.js
module.exports = {
    purge: ["./src/**/*.css", "./**/*.html"],
    darkMode: false, // or 'media' or 'class'
    theme: {
      extend: {},
    },
    variants: {
      extend: {},
    },
    plugins: [],
}
```
You can use this same file for any customization with our Tailwind CSS. Refer to [this link](https://tailwindcss.com/docs/configuration) to learn more about customization settings.

### Adding CSS & HTML files
Now, let's add a CSS file first where we will inject tailwind directives.

Create an `src` folder in our project's root directory. Add a new file in this directory and name it `styles.css.` Add the following content to the newly created CSS file. To learn more about this, refer to [this link](https://tailwindcss.com/docs/installation#include-tailwind-in-your-css)
```css
/* ./src/styles.css */
@tailwind base;
@tailwind components;

body {
	@apply bg-white text-gray-700;
}

@tailwind utilities;
```

Create a new folder in our project's root directory named `assets`. We will be using this folder for storing all assets required in the project. Within this new folder, create separate folders for `css` & `images`. The compiled version of our CSS file will be stored in this folder by gulp task.

Now, let's add our `index.html` in the root directory and include the compiled CSS file's path.

```html
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<link href="/assets/css/styles.css" rel="stylesheet" />
		<title>
			Tailwind CSS Boilerplate (PostCSS + Browsersync + Gulp 4 + Imagemin)
		</title>
	</head>
	<body>
		<div class="container mx-auto py-12">
			<h1 class="text-4xl font-bold text-gray-900">
				Tailwind CSS Boilerplate (PostCSS + Browsersync + Gulp 4 +
				Imagemin)
			</h1>
			<p class="text-lg mt-4">
				Tailwind CSS boilerplate for HTML projects. Bare-bones HTML
				template with Tailwind CSS, PostCSS, Gulp, Imagemin &amp;
				Browsersync.
			</p>
		</div>
	</body>
</html>

```

If you open this file now in the browser, you won't see Tailwind CSS working. For that, we need to do the following tasks.

### Adding Gulp & Browsersync
Next, we need to install the gulp, Browsersync & gulp-postcss plugin.
```bash
npm install -D gulp browser-sync gulp-postcss gulp-imagemin
```

Gulp will help us automate our workflow. Browsersync will help us in reloading the browser automatically after updating files. gulp-postcss will help us in processing our Tailwind CSS.

Now, let's create the gulpfile. In your project's root folder, create a new file and name it `gulpfile.js`. Open this file in the editor and add the following code:
```js
// gulpfile.js
const { watch, series, src, dest } = require("gulp");
var browserSync = require("browser-sync").create();
var postcss = require("gulp-postcss");
const imagemin = require("gulp-imagemin");

// Task for compiling our CSS files using PostCSS
function cssTask(cb) {
	return src("./src/*.css") // read .css files from ./src/ folder
		.pipe(postcss()) // compile using postcss
		.pipe(dest("./assets/css")) // paste them in ./assets/css folder
		.pipe(browserSync.stream());
	cb();
}

// Task for minifying images
function imageminTask(cb) {
	return src("./assets/images/*")
		.pipe(imagemin())
		.pipe(dest("./assets/images"));
	cb();
}

// Serve from browserSync server
function browsersyncServe(cb) {
	browserSync.init({
		server: {
			baseDir: "./",
		},
	});
	cb();
}

function browsersyncReload(cb) {
	browserSync.reload();
	cb();
}

// Watch Files & Reload browser after tasks
function watchTask() {
	watch("./**/*.html", browsersyncReload);
	watch(["./src/*.css"], series(cssTask, browsersyncReload));
}

// Default Gulp Task
exports.default = series(cssTask, browsersyncServe, watchTask);
exports.css = cssTask;
exports.images = imageminTask;

```

We have defined 3 main tasks in this file for Gulp. The first task is for compiling CSS files using PostCSS. We are reading CSS files located in `./src` folder, compiling them using PostCSS and then pasting compiled CSS files in `./assets/css` folder. 

Another task is created to launch the server from the working directory. As a default Gulp task, we have a series of tasks where we are watching .html & .css files for changes, compiling files & reloading the browser.

### Defining scripts in package.json
Now, to run those gulp tasks, we will define scripts in our package.json file. We will define 3 scripts here. Check the below code for reference. I'm not adding full package.json as you don't need to change anything else in the file. Just find the `scripts` object in the package.json and add the following code:
```json
// package.json
{
    // ...
    "scripts": {
        "dev": "gulp",
        "build": "NODE_ENV=production gulp css",
        "build-images": "gulp images"
    },
    // ...
}

```

This step completes our setup. Our project is now ready with the playground.

## Using our boilerplate
From the root directory of our project, run 
```bash
npm run dev
```
to start the development server. Now you should be able to see the project running at [localhost:3000](http://localhost:3000). This will watch our .html & .css files for changes. It will compile CSS if needed & reload the browser automatically.

### To build for production 
From the root directory of our project, run 
```bash
npm run build
```
to create the optimized version of the Tailwind CSS file. The compiled file will be saved in the `./assets/css/` directory.

To create optimized version of images stored in `./assets/images/` directory, run `npm run build-images`. This will replace original images with an optimized version.

You can find the whole [Tailwind CSS boilerplate](https://github.com/salttechno/tailwindcss-boilerplate) on GitHub as well. You can clone it, run `npm install`, and get started.

If you find this useful, don't forget to star our GitHub repo. Also, I run a small [web development company](https://www.salttechno.com) in Pune, India. Do visit our company website.

##### Thank you for reading. I hope this helps you.