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 with Prettier v3 (new)
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
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:
{
"plugins": ["prettier-plugin-blade", "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.
Setting Up the Blade Prettier Plugin with Prettier v2 (old)
If you are using Prettier v2, you should use the following versions instead.
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
And use the following configuration for .prettierrc
:
{
"plugins": [
"./node_modules/prettier-plugin-blade/",
"./node_modules/prettier-plugin-tailwindcss/"
],
"overrides": [
{
"files": ["*.blade.php"],
"options": {
"parser": "blade"
}
}
]
}
If you use the v2 configuration with prettier v3, you will get the following error:
npx prettier --write resources/
[error] Directory import './node_modules/prettier-plugin-blade' is not supported resolving ES modules imported from ./node_modules/prettier/index.mjs
[error] Did you mean to import ./node_modules/prettier-plugin-blade/plugin.js?
error Command failed with exit code 1.
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