3. How To Use Tailwind CSS with Eleventy

Nam

Nam Hoang / Sep 24, 2021

3 min read

Prerequisites

This guide assumes you have Webpack installed in your Eleventy project.

1 Install dependencies

yarn add -D tailwindcss autoprefixer mini-css-extract-plugin css-loader postcss-loader

2 Configure 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')],
};

4 Add 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>3. How To Use Tailwind CSS with Eleventy</title>
    <link rel="stylesheet" type="text/css" href="/assets/main.css" />
  </head>
  <body>
    
    <script src="/assets/main.js"></script>
  </body>
</html>

Congratulations! Tailwind CSS is now installed in your project.

5 Customize 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