Combine Tailwind CSS with Sass Using Webpack



Combining Tailwind CSS with Sass using Webpack can be challenging. The main difficulty is configuring Webpack to handle both, making sure custom styles work well with Tailwind's utilities, and removing unused CSS in production to reduce the file size and improve performance.

Our goal is to combine Tailwind and Sass in a simple way, using Tailwind's utilities for layout, applying custom styles with Sass, and removing unused CSS to optimize the final output

Approaches to Combine Tailwind CSS with Sass using Webpack

We'll cover some simple ways to combine Tailwind CSS with Sass using Webpack. Each method will help you customize your design without making things complicated. Here are the methods we'll go through:

Combining Tailwind CSS and Sass in One File

In this approach, we combine Tailwind CSS with Sass to create a flexible styling system. Tailwind handles layout and responsiveness, while Sass is used for custom styles like colors, fonts, and components. This way, both tools work together to build an efficient project. Here are the steps we have taken to build a clean and efficient project:

First, we install Webpack, Sass, Tailwind, and the required loaders:

npm install --save-dev webpack webpack-cli webpack-dev-server style-loader css-loader sass-loader sass postcss-loader tailwindcss autoprefixer html-webpack-plugin

Next, we initialize Tailwind by generating the tailwind.config.js file:

npx tailwindcss init

Then, we create a postcss.config.js file to configure PostCSS and Autoprefixer:

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

We create a main Sass file, src/styles/main.scss, and import Tailwind's base, components, and utilities. We also add custom styles:

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

$primary-color: #3498db;

.btn {
    background-color: $primary-color;
    color: white;
    padding: 0.5rem 1rem;
    border-radius: 4px;
}

Here, we define a $primary-color in Sass and create a .btn class to style the button. Tailwind still controls layout and responsiveness.

Next, we configure Webpack by creating a webpack.config.js file to make sure our Sass is compiled, PostCSS is applied, and everything is bundled properly.

const path = require('path');  // Add this line at the top of your file
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'development', // Or 'production' if you're building for production
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),  // Use path to resolve the output directory
    },
    module: {
        rules: [
          {
            test: /\.scss$/,
            use: [
                'style-loader',  // Injects styles into the DOM
                'css-loader',    // Resolves CSS imports
                'postcss-loader',// Applies PostCSS transformations
                'sass-loader',   // Compiles Sass to CSS
            ],
          },
        ],
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html',
        }),
    ],
    devServer: {
        static: {
            directory: path.join(__dirname, 'dist'),  // Serve files from the 'dist' directory
        },
        hot: true, // Enable Hot Module Replacement (HMR)
    },
};

We then create an HTML file, src/index.html, with a button that will be styled with both Tailwind and Sass:

<html lang="en">
<head>
    <title>Tailwind + Sass</title>
</head>

<body>
    <button class="btn">Click Me</button>
</body>

</html>

In the src/index.js file, we import the Sass file to include our styles:

import './styles/main.scss';

Make sure your tailwind.config.js has the correct paths to your HTML, JS, and SCSS files so Tailwind can find all the utility classes.

module.exports = {
    content: [
        './src/**/*.{html,js,scss}', // Ensure Tailwind scans these files
    ],
    theme: {
        extend: {},
    },
    plugins: [],
};

Finally, we run the Webpack development server:

npx webpack serve

Once the server is running, we open the browser and check the result. We should see a button with the text "Click Me" styled with both Tailwind and Sass.

Output

button output

Using Tailwind CSS and Sass in Separate Files

In this approach, we separate Tailwind CSS and custom Sass styles into different files. Tailwind handles the layout and responsiveness, while Sass handles custom styles like colors, fonts, and components. This method keeps the setup clean, easy to maintain, and free of conflicts. Steps we have taken to achieve this include:

We started by installing Webpack, Sass, Tailwind, and the necessary loaders.

npm install --save-dev webpack webpack-cli webpack-dev-server style-loader css-loader sass-loader sass postcss-loader tailwindcss autoprefixer html-webpack-plugin

Next, we initialized Tailwind CSS by generating the tailwind.config.js file with:

npx tailwindcss init

We then created the postcss.config.js file to configure PostCSS and Autoprefixer, following the same setup as in the first approach.

For the Tailwind setup, we created a separate src/styles/tailwind.scss file where we imported Tailwind's core utilities like this:

@use 'tailwindcss/base';
@use 'tailwindcss/components';
@use 'tailwindcss/utilities';

Then, we created the src/styles/custom.scss file for our custom styles. In this file, we defined a green, rounded button with a hover effect:

$primary-bg: #4CAF50;
$primary-hover: #45a049;
$btn-border: #3e8e41;
$btn-text: white;

.btn {
    background-color: $primary-bg;
    color: $btn-text;
    padding: 12px 24px;
    border-radius: 30px;
    border: 2px solid $btn-border;
    text-transform: uppercase;
    font-weight: bold;
    font-size: 16px;
    transition: all 0.3s ease;

    &:hover {
        background-color: $primary-hover;
        border-color: $primary-hover;
  }

  &:focus {
    outline: none;
    box-shadow: 0 0 10px rgba(0, 123, 255, 0.5);
  }
}

After that, we created the src/styles/main.scss file where we imported both the tailwind.scss and custom.scss files:

@import './tailwind';
@import './custom';

The Webpack configuration remained the same as in the first approach, so we used that for our setup.

We then made sure Tailwind scans the right files by setting the correct paths in the tailwind.config.js. This is the same setup as in the first approach.

Now, we create the src/index.htm file with a simple button styled by both Tailwind and Sass:

<html lang="en">
<head>
    <title>Tailwind + Sass Button</title>
</head>

<body class="bg-gray-100 p-4">
    <button class="btn">Click Me</button>
</body>

</html>

In the src/index.js file, we imported the main.scss file to apply both Tailwind and our custom styles:

import './styles/main.scss';

Finally, we ran the Webpack development server using:

npm run dev

Output

output Image

Using Tailwind CSS with Sass and PurgeCSS

In this approach, we combine Tailwind CSS with PurgeCSS to remove unused CSS classes, making the final build smaller and faster. This improves performance in production. Here's how we do it:

First, we start by installing the necessary packages for Webpack, Sass, Tailwind, Autoprefixer, and PostCSS (which is already integrated with PurgeCSS by default):

npm install --save-dev webpack webpack-cli webpack-dev-server style-loader css-loader sass-loader sass postcss-loader tailwindcss autoprefixer html-webpack-plugin

Next, we initialize Tailwind CSS. In the tailwind.config.js file, we set the paths to our HTML, JavaScript, and SCSS files so Tailwind can find and apply the utility classes. This step is the same as in the first approach.

Now, in the postcss.config.js file, we configure PurgeCSS to remove any unused styles from the production build.

const purgecss = require('@fullhuman/postcss-purgecss');

module.exports = {
    plugins: [
        require('tailwindcss'),
        require('autoprefixer'),
        purgecss({
            content: ['./src/**/*.{html,js,scss}'],  // Scan HTML, JS, and SCSS files
        }),
    ],
};

Then, in src/index.html, we create a button and style it with Tailwind for layout and responsiveness, and Sass for custom colors and design.

<html lang="en">
<head>
    <title>Tailwind + Sass Button</title>
</head>

<body class="bg-gray-100 p-4">
    <button class="bg-purple-500 text-white py-3 px-6 rounded-lg hover:bg-violet-700">
        Click Me
    </button>
</body>

</html>

Once everything is set up, run the production build with:

npm run build

PurgeCSS will now remove any unused Tailwind utility classes, optimizing the final CSS.

Output

output of third approach

Combining Tailwind with Sass for Component-based Styling

In this approach, we use Tailwind CSS with Sass for layout, responsiveness, and reusable component styles. Here are the steps to combine Tailwind and Sass in a Webpack project.

First, we install the necessary packages, including Webpack, Sass, Tailwind CSS, and PostCSS, with the following command:

npm install --save-dev webpack webpack-cli webpack-dev-server style-loader css-loader sass-loader sass postcss-loader tailwindcss autoprefixer html-webpack-plugin

Next, we initialize Tailwind CSS and configure the tailwind.config.js file to include paths for all HTML, JavaScript, and SCSS files.

module.exports = {
    content: [
        './src/**/*.{html,js,scss}',  // Make sure Tailwind scans all relevant files
    ],
    theme: {
        extend: {},
    },
    plugins: [],
};

Now, we'll create component-specific Sass files. For example, create _buttons.scss in src/styles/components and add the following code:

// _buttons.scss
@use 'tailwindcss/utilities';

$primary-color: #176c6f; // Custom primary color

.btn {
    background-color: $primary-color;
    padding: 0.5rem 1rem;
    border-radius: 4px;
    @apply text-white; // Tailwind's utility class to apply text color
}

Next, we create main.scss in src/styles to import component SCSS files, including the buttons component like this:

// main.scss
@use './components/buttons'; // Import button styles

Now, we configure Webpack to handle Sass, PostCSS (for Tailwind), and other necessary loaders, just like in the first approach.

Then, we create index.html in the src directory as the entry point and add a button with the btn class to apply styles:

<!-- src/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Tailwind + Sass</title>
</head>

<body>
    <button class="btn">Click Me</button>
</body>

</html>

After that, in src/index.js, we import main.scss to apply the styles:

// src/index.js
import './styles/main.scss'; // Import the main SCSS file

Finally, we run the development server with:

npm run dev

Output

Output of Component-based
Updated on: 2024-12-27T09:05:52+05:30

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements