Setting up Tailwind CSS in a Nuxt.js project.
Start by creating a new Nuxt.js project if you don't have one set up already. The most common approach is to use Create Nuxt App:
npx create-nuxt-app my-project
Do not choose "Tailwind CSS" when prompted to select your "UI Framework". This will cause conflicts that prevent you from being able to install Tailwind CSS v2.0 due to the @nuxtjs/tailwindcss
module depending on an old version of Tailwind.
Next, change directories to your new project:
cd my-project
Tailwind CSS requires Node.js 12.13.0 or higher.
If you already have the @nuxtjs/tailwindcss
and tailwindcss
modules installed for any reason, it's important that you uninstall it before installing Tailwind itself:
npm uninstall @nuxtjs/tailwindcss tailwindcss
Next, install @nuxtjs/tailwindcss
as well as Tailwind and its peer-dependencies using npm
:
npm install -D @nuxtjs/tailwindcss tailwindcss@npm:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
Nuxt.js doesn't support PostCSS 8 yet so you need to install the Tailwind CSS v2.0 PostCSS 7 compatibility build for now as we've shown above.
Add the @nuxtjs/tailwindcss
module to the buildModules
section of your nuxt.config.js
file:
// nuxt.config.js
export default {
buildModules: ['@nuxtjs/tailwindcss']
}
Next, generate your tailwind.config.js
file:
npx tailwindcss init
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.
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: [
+ './components/**/*.{vue,js}',
+ './layouts/**/*.vue',
+ './pages/**/*.vue',
+ './plugins/**/*.{js,ts}',
+ './nuxt.config.{js,ts}',
+ ],
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.
Open the ./assets/css/tailwind.css
file that Nuxt.js generates for you by default
and use the @tailwind
directive to include Tailwind's base
, components
, and utilities
styles, replacing the original file contents:
/* ./assets/css/tailwind.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.
You're finished! Now when you run npm run dev
, Tailwind CSS will be ready to use in your Nuxt.js project.