Formatting Laravel Blade files and Tailwind CSS with Prettier
While scrolling through Twitter, I came across a tweet by Zep Fietje regarding a new Blade formatter plugin for Prettier. In collaboration with John Koster, they have made significant improvements to this plugin recently.
As someone who has been searching for a reliable Blade formatter, I was immediately intrigued and decided to give it a try.
To my delight, it worked flawlessly in all three projects I tested it on, prompting me to share this amazing tool with the world.
Setting Up the Blade Prettier Plugin
To get started, you need to install Prettier along with the Prettier Blade and Prettier Tailwind CSS plugins. Run the following command:
yarn add -D prettier prettier-plugin-blade prettier-plugin-tailwindcss
# or
npm install --save-dev prettier prettier-plugin-blade prettier-plugin-tailwindcss
NOTE: Prettier v3 broke the prettier-plugin-blade
plugin, as a temporary workaround,
use prettier 2 instead, replace the above command with this:
yarn add -D prettier@^2.0.2 prettier-plugin-blade prettier-plugin-tailwindcss@^0.4.1
# or
npm install --save-dev -prettier@^2.0.2 prettier-plugin-blade prettier-plugin-tailwindcss@^0.4.1
The related issue is tracked here
Next, update the "scripts" configuration in your package.json file with the following:
{
"scripts": {
"format": "npx prettier --write resources/"
}
}
Now, create a new file called .prettierrc and add the following configuration:
Note This is actually optional, as the plugins will be autodetected, I however like to be explicit about these things, when I in the future ever need to change a configuration option.
{
"plugins": [
"./node_modules/prettier-plugin-blade/",
"./node_modules/prettier-plugin-tailwindcss/"
],
"overrides": [
{
"files": ["*.blade.php"],
"options": {
"parser": "blade"
}
}
]
}
The configuration above sets up the plugins for Prettier Blade and Prettier Tailwind CSS, and specifies that the "blade" parser should be used for *.blade.php
files.
Using the Blade Prettier Plugin with Laravel Pint
If you're using Laravel Pint, a wrapper around PHP-CS-Fixer (a PHP code formatter), in your project, you can integrate it with the Blade Prettier plugin. Create a new file called .blade.format.json
and add the following:
{
"useLaravelPint": true
}
To format your entire project, run the following command:
yarn format
# or
npm run format