How To Use Tailwind CSS with Eleventy

    In this guide, we'll walk through how to install Tailwind CSS in an Eleventy project.

    1Set up Webpack

    This guide assumes you have Webpack installed in your Eleventy project. If you haven't already, follow this guide to prepare your project for Tailwind:

    How To Use Webpack in an Eleventy Project

    2Install dependencies

    Run the following command to install Tailwind and a few other dependencies for Webpack:

    npm install --save-dev tailwindcss autoprefixer mini-css-extract-plugin css-loader postcss-loader

    3Configure the build pipeline

    Open up your webpack.config.js file and add the MiniCssExtractPlugin and the CSS rule:

    const MiniCssExtractPlugin = require('mini-css-extract-plugin');
    module.exports = {
    // ...
    plugins: [new MiniCssExtractPlugin()],
    module: {
    rules: [
    {
    test: /\.css$/,
    exclude: /node_modules/,
    use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader']
    }
    ]
    }
    }

    Then, create a postcss.config.js file:

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

    4Add Tailwind to your CSS

    Create a main.css file in the src/styles directory and add the Tailwind directives:

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

    Then, import your CSS file in your src/scripts/main.js file:

    import '../styles/main.css';

    Finally, add your stylesheet to your layout file:

    <!doctype html>
    <html lang="en">
    <head>
    <title>{{ title }}</title>
    <link rel="stylesheet" type="text/css" href="/assets/main.css" />
    </head>
    <body>
    {{ content | safe }}
    <script src="/assets/main.js"></script>
    </body>
    </html>

    Congratulations! Tailwind CSS is now installed in your project.

    5Customize Tailwind (Optional)

    At this point, you’re all set up to work with Tailwind’s excellent defaults.

    If you need to customize your configuration, run the following command to generate a minimal tailwind.config.js file:

    npx tailwindcss init