Setting up Tailwind CSS in a Laravel project.
Start by creating a new Laravel project if you don't have one set up already. The most common approach is to use the Laravel Installer:
laravel new my-project
cd my-projectNext, install Laravel's front-end dependencies using npm:
npm installInstall Tailwind and its peer-dependencies using npm:
npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9Laravel Mix doesn't support PostCSS 8 yet (but it's coming soon) so you need to install the Tailwind CSS v2.0 PostCSS 7 compatibility build for now as we've shown above.
Next, generate your tailwind.config.js file:
npx tailwindcss initThis 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 Blade templates and JavaScript components so Tailwind can tree-shake unused styles in production builds:
// tailwind.config.js
module.exports = {
- purge: [],
+ purge: [
+ './resources/**/*.blade.php',
+ './resources/**/*.js',
+ './resources/**/*.vue',
+ ],
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 webpack.mix.js, add tailwindcss as a PostCSS plugin:
// webpack.mix.js
mix.js("resources/js/app.js", "public/js")
.postCss("resources/css/app.css", "public/css", [
+ require("tailwindcss"),
]);Open the ./resources/css/app.css file that Laravel generates for you by default
and use the @tailwind directive to include Tailwind's base, components, and utilities styles, replacing the original file contents:
/* ./resources/css/app.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.
Next, import your stylesheet in your main Blade layout (commonly resources/views/layouts/app.php or similar) and add the responsive viewport meta tag if it's not already present:
<!doctype html>
<head>
<!-- ... --->
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<!-- ... --->You're finished! Now when you run npm run watch, npm run dev or npm run prod, Tailwind CSS will be ready to use in your Laravel Mix project.