Anjolaoluwa Adebayo-Oyetoro Maker. Writes sometimes. playful most times. loves beautiful UIs

Using Tailwind CSS in production

Practical steps to reducing your CSS bundle size

6 min read 1893

Using Tailwind CSS in production

Performance on the web is a pretty big deal nowadays as it can make or mar your product. It has moved from being something to be worked on after a product launches to being a very important part to be considered in any development process as web performance is a huge part of user experience(UX).

  • According to this study, The average online user expects your pages to load in 4 seconds or less and 40% are more likely to abandon your site after three seconds
  • This blog post shows how optimizing Pinterest’s website for performance saw a 15% increase in SEO traffic and a 15% increase in conversion rate to signup

What is a bundle size?

To understand what a bundle size means, we have to understand what bundling is.

Bundling is the process of a bundler(like webpack, parcel, or snowpack) to combine different groups of assets such as HTML, CSS, JavaScript, and images to produce a smaller file known as a bundle. Bundling is necessary to reduce the number of HTTP requests the browser has to make to serve content to users.

Bundle size is the size of any generated bundle and it affects how long it takes for our websites and web apps to load.

In this article, we’ll be exploring how to reduce our Tailwind CSS powered app bundle size by tree-shaking Tailwind CSS, we will also learn how to use PurgeCSS with Tailwind in production, we will explore how to do that in JavaScript frameworks such as Vue and React.

What is Tailwind CSS?

It’s a utility-first CSS library used to build custom designs, it offers no pre-configured styles and components to build with, rather it offers you a set of unopinionated building blocks known as utility/helper classes to help you style your components.

According to its official documentation:

Tailwind CSS is a highly customizable, low-level CSS framework that gives you all of the building blocks you need to build bespoke designs without any annoying opinionated styles you have to fight to override.

What is PurgeCSS?

PurgeCSS is a development workflow tool for removing unused CSS in a project, it is the default library for controlling Tailwind CSS bundle sizes. It tree-shakes unused styles and optimizes CSS build sizes.

According to its official documentation:

PurgeCSS analyzes your content and your CSS files. Then it matches the selectors used in your files with the one in your content files. It removes unused selectors from your CSS, resulting in smaller CSS files.

Prerequisites

This tutorial assumes the reader has the following:

We made a custom demo for .
No really. Click here to check it out.

You can install Vue CLI with the following command using Yarn:

yarn global add @vue/cli

Verify the installation was successful by running vue in your terminal. You should see a list of the available commands.

Installation and building Tailwind for production in Vue

Installing the CLI package globally gives us access to the vue command in our terminal, the vue create command helps us create a new project:

vue create run in terminal

First, create a new Vue project with the command:

vue create vue-tailwind

The project name “vue-tailwind” can be replaced with whatever name you deem fit.

Running this command gives you an interactive scaffolding experience, where you can choose the packages your app will need, you can also decide to save the configuration as a preset for your future projects.

Next, change the directory to the project folder:

cd vue-tailwind

Next, spin up the development server in the browser for the newly created app by running one of these commands:

yarn serve
or
npm run serve

Your app should be running on http://localhost:8080 by default after running the command:

welcome to the vue app

Next, let’s install the Tailwind CSS library. To install Tailwind with Yarn package manager, type in the following:

yarn add tailwindcss

Then, create a default config file for your project with the Tailwind CLI utility which was included with the tailwindcss package, this helps to customize your Tailwind installation:

npx tailwindcss init

This command creates a tailwind.config.js file in your project’s base directory, the file houses all of Tailwind’s default configuration.

Next, create a styles folder in the src/assets folder then create a tailwind.css file inside the folder, this is where we will be importing Tailwind’s base, components, and utilities styles configurations.

Use the @tailwind directive to inject Tailwind’s base, components, and utility styles into your CSS, place the following content in your tailwind.css file:

@tailwind base;

@tailwind components;

@tailwind utilities;

Next, create a postcss.config.js in the root directory of your project and include the following:

module.exports = {
    plugins: [
        require('tailwindcss'),
        require('autoprefixer')
    ]
}

Compile and build the styles generated from your tailwind.css file with the Tailwind CLI utility tool, run this command:

npx tailwindcss build src/assets/styles/tailwind.css -o src/assets/styles/index.css

This command should yield something similar to this:
tailwindcss running in command line
We can see the output size for the development build is 2.26MB uncompressed, now that’s huge.

Proceed to import your index.css file into your app, place the following lines of code in your App.vue file like this:

<style src="./assets/styles/index.css">

Open your App.vue and add some random styles from the default styles provided by tailwind to the template.

The build step for our building our styles can be abstracted into an npm script, open your package.json file and include a style script in the scripts object.

Place the following lines of code in the package.json file:

"scripts": {
  "style": "tailwindcss build src/assets/styles/index.css -o src/assets/styles/tailwind.css",
// other scripts
}

Next, let’s build our app for production, we will be using the command:

yarn build

This command starts the vue-cli-service build process which produces a production-ready super optimized bundle in the dist/ directory.

In your CLI you should get the following:

vue cli service build message

We can see the build for the CSS is quite huge for an app that only contains the default styles, imagine a scenario where we added new styles to extend the existing styles.

Reducing the file size with PurgeCSS

Next, let’s include the configurations for PurgeCSS. Open your tailwind.config.js file and replace the purge array between the module.exports with the following:

purge: {
  enabled: true,
  content: [
     './src/**/*.vue',
    './public/**/*.html',
  ]
},

What we’ve done is, we’ve fed an array of paths for PurgeCSS to check, it goes through the files in the specified paths then purges all classes that are not defined in any of the files provided in the array.

Running the Tailwind utility command to build the styles again and bundling for production will see a very significant drop in the CSS chunk size.

Run the following command:

yarn style && yarn build

successfully compiled message

When we run the production build we can see a massive size reduction of our CSS file and with this size reduction comes an improvement in how fast our app loads for users.

Installation and building Tailwind for production in React

First, create a new project with create-react-app, type in the following command into your terminal:

npx create-react-app react-tailwind

create-react-app is the official React build tool for bootstrapping and scaffolding React projects. Built on top of webpack, it is a tool that solves the hassles of configuring and setting up the build processes for projects and lets you focus on writing the code that powers your app.

Next, change your working directory to your project folder:

cd react-tailwind

Next, install Tailwind CSS in your project:

yarn add tailwindcss

Then proceed to initialize Tailwind CSS in your project with the Tailwind CLI utility tool, which was included with the tailwindcss package, this help tool creates a tailwind.config.js file in your project’s base directory, the file houses all of Tailwind’s default configuration. To customize your Tailwind installation:

npx tailwindcss init

Next, create a tailwind.css file inside the /src folder, this is where we will be importing Tailwind’s base, components, and utility styles configurations.

Use the @tailwind directive to inject Tailwind’s base, components, and utility styles into your CSS, place the following content in your tailwind.css file:

@tailwind base;

@tailwind components;

@tailwind utilities;

Next, create a postcss.config.js in the root directory of your project and include the following:

module.exports = {
    plugins: [
        require('tailwindcss'),
        require('autoprefixer')
    ]
}

Next, open your App.js and add some random styles from the default styles provided by Tailwind to the template.

Then proceed to delete the contents of your index.css file then compile and build the styles generated from your tailwind.css file into the index.css file with the Tailwind CLI utility tool, run this command:

npx tailwindcss build src/tailwind.css -o src/index.css

Breaking Changes Message in Command Line Interface

This command should yield a development build of 2.44 MB, which is very huge.

Run the command:

yarn build

run yard build
Bundling our project for production also yields a CSS chunk size of 186.66 KB which is a very big size for an app of this size.

Reducing the file size with PurgeCSS

Next, let’s include the configurations for PurgeCSS, Open your tailwind.config.js file and include the following between the module.exports:

purge: {
    content: [
      'src/**/*.js',
      'src/**/*.jsx',
      'public/**/*.html',
    ]
},

What we’ve done is, we’ve fed an array of paths for PurgeCSS to check, it goes through the files in the specified paths then purges all classes that are not defined in any of the files provided in the array.

Running the Tailwind utility command to build the styles again and bundling for production will see a very significant drop in the CSS chunk size.

Run the following command:

npx tailwindcss build src/tailwind.css -o src/index.css && yarn build

npx tailwindcss command

You should get a development build of ~14KB and a production build size of less than 2KB.

Completed Bundle Optimized Production Build

Caveat: You should only use PurgeCSS in production environments, purging styles during development means you have to recompile Tailwind very often, especially in cases where you need utility classes not used in your previous build. Enabling production only purging can be set up by including the enabled option in your PurgeCSS configuration and setting it to build based on what environment it is, include the following in your purge object:

enabled: process.env.NODE_ENV === 'production'

Although using PurgeCSS solves most of your size control needs, another way to reduce your Tailwind CSS file size is by removing unused styles configuration values from your tailwind.config,.js file such as:

  • Removing unused colors from the default color palette to include only colors used in the project
  • Removing unused media queries breakpoint
  • Disabling unused utilities and variants

These other strategies improve our CSS build significantly but are not as effective as using purgeCSS to tree-shake our unused styles.

Conclusion

In this article, we’ve seen how to use Tailwind CSS in Vue and React, we’ve also seen how to conditional tree-shake our CSS styles based on what environment we’re building for. You can read more in the documentation.

You come here a lot! We hope you enjoy the LogRocket blog. Could you fill out a survey about what you want us to write about?

    Which of these topics are you most interested in?
    ReactVueAngularNew frameworks
    Do you spend a lot of time reproducing errors in your apps?
    YesNo
    Which, if any, do you think would help you reproduce errors more effectively?
    A solution to see exactly what a user did to trigger an errorProactive monitoring which automatically surfaces issuesHaving a support team triage issues more efficiently
    Thanks! Interested to hear how LogRocket can improve your bug fixing processes? Leave your email:

    Full visibility into production React apps

    Debugging React applications can be difficult, especially when users experience issues that are difficult to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.

    LogRocket is like a DVR for web apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.

    The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

    Modernize how you debug your React apps — .

    You come here a lot! We hope you enjoy the LogRocket blog. Could you fill out a survey about what you want us to write about?

      Which of these topics are you most interested in?
      ReactVueAngularNew frameworks
      Do you spend a lot of time reproducing errors in your apps?
      YesNo
      Which, if any, do you think would help you reproduce errors more effectively?
      A solution to see exactly what a user did to trigger an errorProactive monitoring which automatically surfaces issuesHaving a support team triage issues more efficiently
      Thanks! Interested to hear how LogRocket can improve your bug fixing processes? Leave your email:

      Is your frontend hogging your users' CPU?

      As web frontends get increasingly complex, resource-greedy features demand more and more from the browser. If you’re interested in monitoring and tracking client-side CPU usage, memory usage, and more for all of your users in production, try LogRocket.https://logrocket.com/signup/

      LogRocket is like a DVR for web apps, recording everything that happens in your web app or site. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.

      Modernize how you debug web apps — .

      Anjolaoluwa Adebayo-Oyetoro Maker. Writes sometimes. playful most times. loves beautiful UIs

      Leave a Reply