Setting up Tailwind CSS in a Gatsby project.
Start by creating a new Gatsby project if you don’t have one set up already. The most common approach is to use Gatsby CLI:
gatsby new my-project
cd my-project
Tailwind CSS requires Node.js 12.13.0 or higher.
Install gatsby-plugin-postcss
as well as Tailwind and its peer-dependencies using npm
:
npm install -D gatsby-plugin-postcss tailwindcss@latest postcss@latest autoprefixer@latest
Next, generate your tailwind.config.js
and postcss.config.js
files:
npx tailwindcss init -p
This will create a minimal tailwind.config.js
file at the root of your project:
// tailwind.config.js
module.exports = {
purge: [],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
Learn more about configuring Tailwind in the configuration documentation.
It will also create a postcss.config.js
file that includes tailwindcss
and autoprefixer
already configured:
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
If you’re planning to use any other PostCSS plugins, you should read our documentation on using PostCSS as your preprocessor for more details about the best way to order them alongside Tailwind.
In your tailwind.config.js
file, configure the purge
option with the paths to all of your pages and components so Tailwind can tree-shake unused styles in production builds:
// tailwind.config.js
module.exports = {
- purge: [],
+ purge: ['./src/**/*.{js,jsx,ts,tsx}'],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
Read our separate guide on optimizing for production to learn more about tree-shaking unused styles for best performance.
In your gatsby-config.js
file, enable the postcss plugin.
// gatsby-config.js
module.exports = {
/* Your site config here */
- plugins: [],
+ plugins: ['gatsby-plugin-postcss'],
}
Create the ./src/styles/global.css
file
and use the @tailwind
directive to include Tailwind’s base
, components
, and utilities
styles, replacing the original file contents:
/* ./src/styles/global.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
Tailwind will swap these directives out at build-time with all of the styles it generates based on your configured design system.
Read our documentation on adding base styles, extracting components, and adding new utilities for best practices on extending Tailwind with your own custom CSS.
Finally, create a ./gatsby-browser.js
file at the root of your project if it doesn’t already exist, and import your CSS file:
// ./gatsby-browser.js
+ import './src/styles/global.css';
Read the Gatsby documentation on using global styles to learn more about working with global CSS files in Gatsby.
You’re finished! Now when you run gatsby develop
, Tailwind CSS will be ready to use in your Gatsby project.