Vincent's blog

Formatting PHP and Blade using Prettier and pnpm

Upon my initial experience with pnpm, I was impressed by its speed, ease of use, space-saving capabilities, and workspace features.

However, there was one obstacle that held me back: the occasional incompatibility between Prettier and pnpm when it came to formatting PHP files.

This particular quirk, where Prettier and pnpm didn't always cooperate in formatting PHP files, can be resolved by overriding Prettier's parser settings.

In order to achieve this, we need to manually register the plugins first. With the upcoming Prettier 3 release, this manual registration method will become the default approach for registering plugins, as the plugin search feature has been removed.

Additionally, it is crucial to modify how Prettier parses PHP and Blade files.

export default {
    singleQuote: true,
    plugins: [
        '@prettier/plugin-php',
        'prettier-plugin-blade',
    ],
    overrides: [
        {
            files: ['*.php'],
            options: {
                parser: 'php',
            },
        },
        {
            files: ['*.blade.php'],
            options: {
                parser: 'blade',
            },
        },
    ],
};

To enable PHP formatting with Prettier in Visual Studio Code, you'll need to add these settings.

{
  "[blade][php]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "prettier.documentSelectors": ["**/*.php"]
}

#php