Giter Site home page Giter Site logo

shufo / prettier-plugin-blade Goto Github PK

View Code? Open in Web Editor NEW
305.0 6.0 8.0 1.01 MB

Format your blade template using Prettier

Home Page: https://www.npmjs.com/package/@shufo/prettier-plugin-blade

License: MIT License

JavaScript 7.00% TypeScript 93.00%
blade formatter laravel prettier tailwind

prettier-plugin-blade's Introduction

Prettier PHP

Prettier Blade Plugin

GitHub Workflow Status npm version

Format your blade template using Prettier

Features

  • Automatically indent markup inside directives
  • Automatically add spacing to blade template markers
  • PHP 8 syntax support (null safe operator, named arguments)
  • Compliant to PSR-2 coding standard (PHP code inside directives)
  • Automatically sort Tailwind CSS classes with respect of tailwind.config.js

Installation

$ npm install --save-dev @shufo/prettier-plugin-blade prettier

# yarn
$ yarn add -D @shufo/prettier-plugin-blade prettier

# pnpm
$ pnpm add -D @shufo/prettier-plugin-blade prettier

then, add in your Prettier configuration:

{
  "plugins": ["@shufo/prettier-plugin-blade"],
  "overrides": [
    {
      "files": ["*.blade.php"],
      "options": {
        "parser": "blade",
        "tabWidth": 4
      }
    }
  ]
}

Prettier version Compatibilitiy

Prettier Package
3.x ^1.9.x
2.x 1.8.x

Usage (CLI)

$ ./node_modules/.bin/prettier --write resources/**/*.blade.php
Screen.record.from.2022-01-27.20.53.05@2x_0.5.mp4

Example

Input

@extends('frontend.layouts.app')
@section('title') foo
@endsection
@section('content')
<section id="content">
<div class="container mod-users-pd-h">
    <div class="pf-user-header">
    <div></div>
    <p>@lang('users.index')</p>
    </div>
        <div class="pf-users-branch">
            <ul class="pf-users-branch__list">
                @foreach($users as $user)
        <li>
            <img src="{{ asset('img/frontend/icon/branch-arrow.svg') }}" alt="branch_arrow">
            {{ link_to_route("frontend.users.user.show",$users["name"],$users['_id']) }}
        </li>
        @endforeach
      </ul>
      <div class="pf-users-branch__btn">
      @can('create', App\Models\User::class)
            {!! link_to_route("frontend.users.user.create",__('users.create'),[1,2,3],['class' => 'btn']) !!}
            @endcan
        </div>
  </div>
    </div>
</section>
@endsection
@section('footer')
@stop

Output

@extends('frontend.layouts.app')
@section('title') foo
@endsection
@section('content')
    <section id="content">
        <div class="container mod-users-pd-h">
            <div class="pf-user-header">
                <div></div>
                <p>@lang('users.index')</p>
            </div>
            <div class="pf-users-branch">
                <ul class="pf-users-branch__list">
                    @foreach ($users as $user)
                        <li>
                            <img src="{{ asset('img/frontend/icon/branch-arrow.svg') }}" alt="branch_arrow">
                            {{ link_to_route('frontend.users.user.show', $users['name'], $users['_id']) }}
                        </li>
                    @endforeach
                </ul>
                <div class="pf-users-branch__btn">
                    @can('create', App\Models\User::class)
                        {!! link_to_route('frontend.users.user.create', __('users.create'), [1, 2, 3], ['class' => 'btn']) !!}
                    @endcan
                </div>
            </div>
        </div>
    </section>
@endsection
@section('footer')
@stop

Options

You can use these options for prettier blade plugin in prettier CLI.

key description
--tab-width Number of spaces per indentation level. default: 4
--print-width The line length where Prettier will try wrap. default: 120
--wrap-attributes The way to wrap attributes. [auto|force|force-aligned|force-expand-multiline|aligned-multiple|preserve|preserve-aligned]. default: auto
--wrap-attributes-min-attrs Minimum number of html tag attributes for force wrap attribute options. Wrap the first attribute only if 'force-expand-multiline' is specified in wrap attributes. default: 2.
--end-with-new-line End output with newline. default: true
--sort-tailwindcss-classes Sort Tailwind CSS classes. It will automatically look for and respect tailwind.config.js if it exists. default: false
--tailwindcss-config-path Path to your custom Tailwind configuration file. This option is only available if --sort-tailwindcss-classes is present. default: ''
--sort-html-attributes Sort HTML Attributes in the specified order. [none | alphabetical | code-guide | idiomatic | vuejs] default: none
--no-php-syntax-check Disable PHP syntax checking. default: false
--extra-liners Comma separated list of tags that should have an extra newline before them. default: head,body,/html
--trailing-comma-php If set to false, no trailing commas are printed for php expression. default: true

.prettierrc example

{
  "printWidth": 120,
  "tabWidth": 4,
  "wrapAttributes": "auto",
  "wrapAttributesMinAttrs": 2,
  "sortTailwindcssClasses": true,
  "sortHtmlAttributes": "none",
  "noPhpSyntaxCheck": false,
  "indentInnerHtml": true,
  "extraLiners": "",
  "trailingCommaPHP": true
}

Disabling format in file

To disable formatting in your file, you can use blade/html comments in the following format:

{{-- prettier-ignore-start --}}
    {{ $foo }}
    {{ $bar }}
{{-- prettier-ignore-end --}}

or

<!-- prettier-ignore-start -->
    {{ $foo }}
    {{ $bar }}
<!-- prettier-ignore-end -->

To disable formatting on a specific line, you can use comment in the following format:

{{-- prettier-ignore --}}
    {{ $foo }}

or

<!-- prettier-ignore -->
    {{ $foo }}

Editor Integration

The editors below are confirmed to work with this plugin.

VSCode

You can use Prettier extension for VSCode to format blade in VSCode. You need to install this plugin as a local dependency. see https://github.com/prettier/prettier-vscode#prettier-resolution

If you want to use a formatter without Prettier, please consider to use the vscode-blade-formatter instead.

Vim

You can use coc-prettier plugin on coc.nvim

If you want to use formater without Prettier, please consider to using coc-blade

JetBrains WebStorm, PHPStorm, PyCharm...

You can use the Prettier Plugin for JetBrains IDE.

Add extension setting blade.php to File | Settings | Languages & Frameworks | JavaScript | Prettier | Run for files:

e.g.

{**/*,*}.{js,ts,jsx,tsx,blade.php}

and turn on checkbox On 'Reformat Code' action

Restart your IDE if you get the error: 'Prettier: File *.php has unsupported type'

Limitation

This plugin is based on blade-formatter which does not generate ASTs with lexer, so it might break indentation on complex blade.

Like:

  • The mix of open/closed HTML tag and directives

โŒ Example of unexpected code

@if ($user)
    <div>
    @else
    </div>
@endif

โญ• Example of expected code

@if ($user)
    <div>foo</div>
@else
    <div>bar</div>
@endif

Please keep the blade template as simple as possible for better formatting.

API

You can format the blade file programmatically using Prettier's API

// CommonJS
const prettier = require("prettier");

const input = `
<div>
  @if ($user)
  {{ $foo }}
  @else
  {{ $bar }}
  @endif
</div>
`;

const res = await prettier.format(input, { parser: "blade" });
console.log(res);
// =>
//<div>
//    @if ($user)
//        {{ $foo }}
//    @else
//        {{ $bar }}
//    @endif
//</div>

// ES Module
import * as prettier from "prettier";

const input = `
<div>
  @if ($user)
  {{ $foo }}
  @else
  {{ $bar }}
  @endif
</div>
`;
const res = await prettier.format(input, { parser: "blade" });
console.log(res);

Development

$ yarn install
$ yarn run watch # watch changes

Testing

$ yarn install
$ yarn run test

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Contributors

shufo
Shuhei Hayashibara
howdu
Beej
ianjamieson
Ian Jamieson
mortenscheel
Morten Scheel
nessimabadi
Nessim Abadi
vuolter
Walter Purcaro

LICENSE

MIT

prettier-plugin-blade's People

Contributors

dependabot[bot] avatar github-actions[bot] avatar howdu avatar ianjamieson avatar mortenscheel avatar nessimabadi avatar renovate[bot] avatar shufo avatar vuolter avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

prettier-plugin-blade's Issues

[Bug]: Stopped formatting blade files, but still works on PHP and JS

Description

Using the Nova editor from Panic (Mac) blade files have stopped formatting.

JS, CSS and PHP files still format great.

I have seen this before and it was eventually fixed, but not sure the cause now?

Maybe a new version of prettier causing the issue? Not sure.

Anyone else having issues in VScode or the like?

Expected Behavior

Format code and sort tailwindcss classes in .blade files

Actual Behavior

NOT formatting code and sort tailwindcss classes in .blade files

Additional Context

[email protected]
[email protected]
@shufo/[email protected]

Mac 13.3.1.(a) M1
Nova 10.6

Formatting stops working when inline @php directive present in tag

Hi, thanks a lot for the plugin just wanted to report a possible bug

When having something like:

<article @php(post_class('lg:pt-10'))>
            <header class=" px-0 lg:px-4 container"></header>
</article>

the code get's formated to:

<article
    @php(post_class('lg:pt-10'))>
            <header class=" px-0 lg:px-4 container"></header>
</article>

if the @php inline directive is remove or changed to @php @endphp the formatting works as expected.

This includes all types of formatting, including the tailwind sorting that made me realize my file was being formatted as expected

[Feature Request]: Format JS inside of AlpineJS attributes

Description

Hello!

It would be awesome if this plugin could automatically format javascript inside of AlpineJS attributes. Would it be possible to have the existing JS parser in prettier format the text in any attribute that starts with x-[a-z] (should cover all of Alpine)?

For example, below is a treesitter query I wrote to inject JS into any attribute that starts with x-[a-z].

; AlpineJS attributes
(attribute
  (attribute_name) @_attr
    (#lua-match? @_attr "^x%-%l")
  (quoted_attribute_value
    (attribute_value) @injection.content)
  (#set! injection.language "javascript"))

Thanks!

Suggested Solution

I'd like the javascript in my AplineJS attributes to be automatically formatted with the rest of the blade file.

Alternatives

No response

Additional Context

No response

Unexpected output using < as less than in a conditional

Input

<x-panel class="bg-gray-50">
    <x-content>
        @unless(isset($primaryTicketingLinkData) && $primaryTicketingLinkData['isSoldOut'] && $ticketCount <= 0)
            @include('events.partials.wanted-tickets-button')
        @endunless
    </x-content>
</x-panel>

Actual

<x-panel class="bg-gray-50">
    <x-content>
        @unless(isset($primaryTicketingLinkData) && $primaryTicketingLinkData['isSoldOut'] &&
            $ticketCount <=
                0)
                @include(
                    'events.partials.wanted-tickets-button'
                )
            @endunless
            </x-content
        >
</x-panel>

Expected

<x-panel class="bg-gray-50">
    <x-content>
        @unless(isset($primaryTicketingLinkData) && $primaryTicketingLinkData['isSoldOut'] && $ticketCount <= 0)
            @include('events.partials.wanted-tickets-button')
        @endunless
    </x-content>
</x-panel>

It seems as though it is recognising <= and trying to put the next part on a new line, thinking it is an HTML attribute.

[Bug]: Recommended configuration for using plugin-blade together with plugin-php?

Description

It appears that prettier-plugin-blade is being utilized instead of plugin-php for PHP files. Could you please advise on the recommended approach for using @shufo/prettier-plugin-blade in conjunction with @prettier/plugin-php to ensure proper formatting of both PHP and Blade files?

Expected Behavior

It should only format PHP files using plugin-php and Blade files using plugin-blade.

Actual Behavior

It formats PHP files using plugin-blade.

Additional Context

// prettier.config.js
module.exports = {
  singleQuote: true,
  plugins: [require('@prettier/plugin-php'), require('@shufo/prettier-plugin-blade')],
  overrides: [
    {
      files: ['*.php'],
      options: {
        parser: 'php',
      },
    },
    {
      files: ['*.blade.php'],
      options: {
        tabWidth: 4,
        parser: 'blade',
      },
    },
  ],
};
// package.json
{
  "private": true,
  "type": "module",
  "dependencies": {
    "@prettier/plugin-php": "^0.19.4",
    "@shufo/prettier-plugin-blade": "^1.8.12",
    "prettier": "^2.8.8"
  }
}
// .vscode/settings.json
{
  "[blade][php]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "prettier.documentSelectors": ["**/*.php"]
}

Gigantic css line after reformatting (PHPstorm)

Hello! Thank you for an awesome plugin. Can you help me to understand maybe i'm doing something wrong? When i typing tailwind classes, phpstorm automatically transfer classes to a new line after i reach 120 symbols, but then prettier blade plugin starts to sorting tailwind classes and moves all classes from several lines to a gigantic one. If i disable sortTailwindcssClasses in .prettierrc, then everything works as expected, of course without tailwind sorting :(

Maybe i am doing something wrong?

Before prettier
2022-09-13_22-45-19

After prettier
2022-09-13_22-45-30

SublimeJsPrettier

Hi!

I'm trying to get this to work with SublimeJsPrettier and here's what the console says. It seems to be looking for your package.json's main entry file to kick off the prettier plugin, but the file... indeed doesn't exist? Am I doing something wrong?
Capture dโ€™eฬcran, le 2022-03-19 aฬ€ 19 33 58

[Bug]: Error [ERR_REQUIRE_ESM] with "sortTailwindcssClasses"

Description

Setting "sortTailwindcssClasses" to true results to the following error:

["ERROR" - 12:29:07] Error formatting document.
["ERROR" - 12:29:07] Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/idrisn/dev/todolu/tailwind.config.js from /Users/idrisn/dev/todolu/node_modules/@shufo/tailwindcss-class-sorter/dist/main.js not supported.
Instead change the require of tailwind.config.js in /Users/idrisn/dev/todolu/node_modules/@shufo/tailwindcss-class-sorter/dist/main.js to a dynamic import() which is available in all CommonJS modules.
Error: Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/idrisn/dev/todolu/tailwind.config.js from /Users/idrisn/dev/todolu/node_modules/@shufo/tailwindcss-class-sorter/dist/main.js not supported.
Instead change the require of tailwind.config.js in /Users/idrisn/dev/todolu/node_modules/@shufo/tailwindcss-class-sorter/dist/main.js to a dynamic import() which is available in all CommonJS modules.
    at /Users/idrisn/dev/todolu/node_modules/blade-formatter/dist/bundle.js:59:2579
    at async /Users/idrisn/dev/todolu/node_modules/@shufo/prettier-plugin-blade/src/worker.js:5:18
["INFO" - 12:29:07] Formatting completed in 22ms.

Expected Behavior

<form action="#" class="relative">
    <div class="text-xs flex p-6 ">
        Test
    </div>
</form>

This test file should be sorted correctly.

Actual Behavior

The formatter fails and stops with the error mentioned above.

Additional Context

"prettier": "2.8.8",
"tailwindcss": "3.3.2",
"@shufo/prettier-plugin-blade": "^1.8.13",

# .prettierrc
{
    "plugins": ["@shufo/prettier-plugin-blade"],
    "overrides": [
        {
            "files": ["*.blade.php"],
            "options": {
                "parser": "blade",
                "tabWidth": 4,
                "sortTailwindcssClasses": true,
                "wrapAttributes": "auto"
            }
        }
    ]
}


Bug affecting multiline phpdoc in @php section

Every time a multiline phpdoc comment is processed, extra indentation is added.

It's not unusual to add phpdoc like this to blade files in order to get IDE completion to work

@php
    /**
     * @var \App\Models\User $user
     * @var \App\Models\Post $post
     */
@endphp
<span>{{ $post->title }} by {{ $user->name }}</span>

Expected:
No changes. The syntax and indentation is fine.

Actual:

@php
    /**
         * @var \App\Models\User $user
         * @var \App\Models\Post $post
         */
@endphp
<span>{{ $post->title }} by {{ $user->name }}</span>

Running prettier again yields

@php
    /**
             * @var \App\Models\User $user
             * @var \App\Models\Post $post
             */
@endphp
<span>{{ $post->title }} by {{ $user->name }}</span>

And again:

@php
    /**
                 * @var \App\Models\User $user
                 * @var \App\Models\Post $post
                 */
@endphp
<span>{{ $post->title }} by {{ $user->name }}</span>

Workaround:
To avoid this issue, you can use single-line phpdoc in stead:

@php
    /** @var \App\Models\User $user */
    /** @var \App\Models\Post $post */
@endphp
<span>{{ $post->title }} by {{ $user->name }}</span>

Versions:

Component Arguments Indentation

Input blade file

@component('path.to.component', [
    'title' => 'My title',
    'description' => '',
    'header' => [
        'transparent' => true,
    ],
    'footer' => [
        'hide' => true,
    ],
])
    <div>
        some content
    </div>
@endcomponent

Expected output

@component('path.to.component', [
    'title' => 'My title',
    'description' => '',
    'header' => [
        'transparent' => true,
    ],
    'footer' => [
        'hide' => true,
    ],
])
    <div>
        some content
    </div>
@endcomponent

Actual output

@component('path.to.component', [
    'title' => 'My title',
    'description' => '',
    'header' => [
    'transparent' => true,
    ],
    'footer' => [
    'hide' => true,
    ],
    ])
    <div>
        some content
    </div>
@endcomponent

Note that the indentation on the nested array values is lost.

Let me know if you need any more details or examples.

[Formatting Bug]: does not format when inline directive and if directive mixed

Version

1.8.12

Template before formatting

<div @php($counter = 1) >
     <x-share>
    @if ($counter)
          {{--  --}}
    @endif
  </x-share>
</div>

Template after formatting

<div
  @php($counter = 1) >
     <x-share>
    @if ($counter)
          {{--  --}}
    @endif
  </x-share>
</div>

Expected Behaviour

Expected

  • @php($counter = 1) not to wrap and stay in the same line like <div @php($counter = 1) >.
  • <x-share> to have the same indent as </x-share>.
  • the space between @php($counter = 1) and the closing bracket > to be removed.

Config

This test is done with a fresh Prettier VSCode plugin & no config rules aside from the essential to make this plugin work:

{
  "plugins": ["@shufo/prettier-plugin-blade"],
  "overrides": [
    {
      "files": ["*.blade.php"],
      "options": {
        "parser": "blade"
      }
    }
  ]
}

Workarounds

  1. replacing @php($counter = 1) with @php $counter = 1 @endphp.
  2. remove the @if statement inside the x-share component.

Relevant log output

<div @php($counter = 1) >
        <x-share>
    @if ($counter)
       {{--  --}}
    @endif
    </x-share>
</div>

[Formatting Bug]: Unspecified single quotes

Version

1.8.12

Template before formatting

<html>

<head>
    <meta charset='utf-8'>
    <meta
        name='viewport'
        content='width=device-width, initial-scale=1'
    >
    <meta
        name='csrf-token'
        content='{{ csrf_token() }}'
    >
    <link
        rel='preconnect'
        href='https://fonts.googleapis.com'
    >
    <link
        rel='preconnect'
        href='https://fonts.gstatic.com'
        crossorigin
    >
    <link
        href='https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap'
        rel='stylesheet'
    >
    <link
        rel='shortcut icon'
        href='{{ asset('favicon.ico') }}'
    >
    @section('head')@show
    @vite('resources/css/styles.css')
    @vite('resources/js/scripts.js')
</head>

<body class='flex flex-col bg-white pt-[100px] text-black lg:pt-0'>
    @include('common.header')
    @include('common.navbar')

    @yield('content')

    @include('common.footer')
    @include('common.mobile')
</body>

</html>

Template after formatting

@extends('common.layout')

@section('head')
    <title>{{ $settings->title }}</title>
@endsection

@section('content')
    <x-sliders.swiper />
    <div class="mb-8 h-[150px] w-full bg-gray-100"></div>
    <x-content.container>
        <x-content.title>Products</x-content.title>
        <x-catalog.grid :products="$products" />
        <x-catalog.banners
            :columns="3"
            :banners="$banners->featured"
        />
        <x-catalog.grid :products="$products" />
        <x-catalog.banners
            :columns="2"
            :banners="$banners->release"
        />
        <x-catalog.grid :products="$products" />
        <x-catalog.banners
            :columns="1"
            :banners="$banners->promotion"
        />
    </x-content.container>
@endsection

Expected Behaviour

Hey, noticed that even though I explicitly specified the singleQuote to false, it's still using it.
The quote attribute seems to not work at all inside blade files.

My prettier config:

//.prettierrc.cjs
/** @type {import('prettier').Config} */
module.exports = {
    plugins: [require.resolve("@shufo/prettier-plugin-blade")],
    sortTailwindcssClasses: true,
    tailwindcssConfigPath: "./tailwind.config.js",
    wrapAttributes: "force-expand-multiline",
    semi: true,
    tabWidth: 4,
    singleQuote: false, // should be using double quotes, right?
    arrowParens: "avoid",
    endOfLine: "auto",
    bracketSpacing: true,
    printWidth: 80,
    trailingComma: "none",
    quoteProps: "preserve",
    overrides: [
        {
            files: ["*.blade.php"],
            options: {
                parser: "blade",
                tabWidth: 4
            }
        }
    ]
};

Relevant log output

No response

multiple blade directives on one line

I try to combine this with prettier-plugin-tailwindcss which is not blade aware and sometimes puts some @ directives on one line.
For the following cases, prettier-plugin-blade keeps them on one line, causing layout issues, while it is solved if I separatly split these in two lines before having prettier-plugin-blade process the file . Could prettier-plugin-blade do that split in two lines for us?

@endcan @if
@switch($choice) @case('projects')
@break @case('project')
@break @default
@endcan @if ($condition)

[Bug]: 1.9.* Breaks formatting in Nova ( from Panic )

Description

Not sure if this has to do with the Prettier extension in Nova, but when updating prettier-plugin-blade passed 1.8.13 all formatting breaks. No error messages, but the formatting on blade does nothing.

Anyone else?

Expected Behavior

Format blade files.

Actual Behavior

Does not format blade files .

Additional Context

No response

Getting `Cannot find module '@shufo/prettier-plugin-blade'` when using VS Code

Hi,

when I try to format my blade files with VS Code while having the plugin installed via npm and set in the plugins array in my .prettierrc, I get the error Cannot find module '@shufo/prettier-plugin-blade'.

I'm using:

  • "prettier": "2.6.2"
  • "@shufo/prettier-plugin-blade": "^1.4",
  • VS Code Prettier plugin: v9.5.0
  • Windows 10

I also trie setting the prettier.resolveGlobalModules setting to true, to no avail.

I hope that's plenty into, feel free to ask for more :)

Full error log:

["ERROR" - 10:47:57] Error formatting document.
["ERROR" - 10:47:57] Cannot find module '@shufo/prettier-plugin-blade'
Require stack:
- c:\Users\abc\Documents\Git-Repos\XYZ\forensic-ai-web\node_modules\prettier\index.js
- c:\Users\abc\.vscode\extensions\esbenp.prettier-vscode-9.5.0\dist\extension.js
- c:\Users\abc\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\loader.js
- c:\Users\abc\AppData\Local\Programs\Microsoft VS Code\resources\app\out\bootstrap-amd.js
- c:\Users\abc\AppData\Local\Programs\Microsoft VS Code\resources\app\out\bootstrap-fork.js
Error: Cannot find module '@shufo/prettier-plugin-blade'
Require stack:
- c:\Users\abc\Documents\Git-Repos\XYZ\forensic-ai-web\node_modules\prettier\index.js
- c:\Users\abc\.vscode\extensions\esbenp.prettier-vscode-9.5.0\dist\extension.js
- c:\Users\abc\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\loader.js
- c:\Users\abc\AppData\Local\Programs\Microsoft VS Code\resources\app\out\bootstrap-amd.js
- c:\Users\abc\AppData\Local\Programs\Microsoft VS Code\resources\app\out\bootstrap-fork.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:987:15)
    at h.resolve (c:\Users\abc\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\loader.js:4:761)
    at c:\Users\abc\Documents\Git-Repos\XYZ\forensic-ai-web\node_modules\prettier\index.js:39110:25
    at Array.map (<anonymous>)
    at Object.load (c:\Users\abc\Documents\Git-Repos\XYZ\forensic-ai-web\node_modules\prettier\index.js:39105:65)
    at Object.load [as loadPlugins] (c:\Users\abc\Documents\Git-Repos\XYZ\forensic-ai-web\node_modules\prettier\index.js:15998:27)
    at c:\Users\abc\Documents\Git-Repos\XYZ\forensic-ai-web\node_modules\prettier\index.js:39172:24
    at Object.Success [as format] (c:\Users\abc\Documents\Git-Repos\XYZ\forensic-ai-web\node_modules\prettier\index.js:39188:12)
    at t.default.format (c:\Users\abc\.vscode\extensions\esbenp.prettier-vscode-9.5.0\src\PrettierEditService.ts:463:45)
    at t.PrettierEditProvider.provideEdits (c:\Users\abc\.vscode\extensions\esbenp.prettier-vscode-9.5.0\src\PrettierEditService.ts:322:22)
    at z.provideDocumentFormattingEdits (c:\Users\abc\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\api\node\extensionHostProcess.js:83:105121)

Prettier Ignore

Is there a way to ignore a line or block of code?

I've tried using php syntax, html syntax and even blade comments with prettier-ignore but nothing seems to work?

@php // prettier-ignore @endphp
<!-- prettier-ignore -->
{{-- prettier-ignore --}}

[Formatting Bug]: Does not respect prettier bracketSameLine

Version

1.10.0

Template before formatting

@section('buttons')
    <x-button.nav
        :href="route('eaglesys::warehouse.create')"
        image="page_add"
        label="Add New Warehouse"
    />
@endsection

Template after formatting

@section('buttons')
    <x-button.nav :href="route('eaglesys::warehouse.create')"
        image="page_add"
        label="Add New Warehouse" />
@endsection

Expected Behaviour

Hello!

I want to use the wrapArrtibutes: 'force' option, however, I don't want it to place the bracket on the same line as the last attribute (note that the default behaviour in prettier is to place the bracket on the next line). I tried adding an bracketSameLine: false override, but it does not seem to be respected

Thanks!

.prettierrc.json

{
    "plugins": [
        "@shufo/prettier-plugin-blade"
    ],
    "overrides": [
        {
            "files": [
                "*.blade.php"
            ],
            "options": {
                "bracketSameLine": false,
                "parser": "blade",
                "printWidth": 80,
                "sortTailwindcssClasses": true,
                "tabWidth": 4,
                "wrapAttributes": "force"
            }
        }
    ]
}

Relevant log output

No response

[Bug]: Plugin stopped formatting blade files after upgrading prettier to 3.0.0

Description

Using version 1.9.2 (was 1.8.13 before) and prettier 3.0.0 (was 2.8.8 before), no Blade files are being checked nor fixed anymore.

It seems more related to the prettier upgrade (unlikely to be a bug on its side, though), as rolling back this plugin to 1.8.13 doesn't make any difference.

Expected Behavior

The Blade files are checked or fixed as they used to be.

Actual Behavior

No Blade files are even being considered. Nothing is reported nor logged either, it's like they don't exist.

Additional Context

package.json

"devDependencies": {
    "@shufo/prettier-plugin-blade": "1.9.2",
    "@tailwindcss/aspect-ratio": "0.4.2",
    "@tailwindcss/forms": "0.5.3",
    "@tailwindcss/typography": "0.5.9",
    "axios": "1.4.0",
    "cross-env": "7.0.3",
    "cypress": "12.16.0",
    "jquery": "3.7.0",
    "laravel-mix": "6.0.49",
    "lodash": "4.17.21",
    "postcss-import": "15.1.0",
    "prettier": "3.0.0",
    "resolve-url-loader": "5.0.0",
    "sass": "1.63.6",
    "sass-loader": "13.3.2",
    "tailwindcss": "3.3.2",
    "vue-template-compiler": "2.7.14"
},
"dependencies": {
    "alpinejs": "^3.12.0",
    "clipboard": "^2.0.11",
    "toastify-js": "^1.12.0"
}

.prettierrc.json

{
  "plugins": [
    "@shufo/prettier-plugin-blade"
  ],
  "overrides": [
    {
      "files": [
        "*.blade.php"
      ],
      "options": {
        "parser": "blade",
        "sortTailwindcssClasses": true,
        "wrapAttributes": "aligned-multiple"
      }
    }
  ]
}

.prettierignore

(None)

[Bug]: Unknown node type: undefined

Version

1.11.0 (prettier 3.0.2)

Template before formatting

<x-filament-forms::field-wrapper
    class="filament-navigation"
    :id="$getId()"
    :label="$getLabel()"
    :label-sr-only="$isLabelHidden()"
    :helper-text="$getHelperText()"
    :hint="$getHint()"
    :hint-icon="$getHintIcon()"
    :required="$isRequired()"
    :state-path="$getStatePath()"
>
    @php
        $isDisabled = $isDisabled();

        $addAction = $getAction('add');
        $addChildAction = $getAction('add-child');
        $editAction = $getAction('edit');
    @endphp

    <div wire:key="tree-items-wrapper">
        <div
            class="space-y-2"
            data-sortable-container
            ax-load
            ax-load-src="{{ \Filament\Support\Facades\FilamentAsset::getAlpineComponentSrc('filament-tree', 'saade/filament-tree') }}"
            ax-load-css="{{ \Filament\Support\Facades\FilamentAsset::getStyleHref('filament-tree-styles', 'saade/filament-tree') }}"
            x-data="tree({
                statePath: @js($getStatePath()),
                disabled: @js($isDisabled)
            })"
        >
            @forelse($getState() as $uuid => $item)
                <x-filament-tree::tree-item
                    :actions="[$addChildAction, $editAction]"
                    :disabled="$isDisabled"
                    :item="$item"
                    :itemStatePath="$getStatePath() . '.' . $uuid"
                    :statePath="$getStatePath()"
                />
            @empty
                <div @class([
                    'w-full bg-white rounded-lg border border-gray-300 px-3 py-2 text-left',
                    'dark:bg-gray-700 dark:border-gray-600',
                ])>
                    {{ __('No items yet') }}
                </div>
            @endforelse
        </div>
    </div>

    <div class="flex justify-end">
        {{ $addAction }}
    </div>
</x-filament-forms::field-wrapper>

Template after formatting

no output

Expected Behaviour

It should be formatting properly.

Relevant log output

["INFO" - 5:56:21 PM] Formatting file:///Users/saade/GovDigital/govdigital/packages/filament-tree/resources/views/components/tree-item.blade.php
["INFO" - 5:56:21 PM] Using config file at '/Users/saade/GovDigital/govdigital/packages/filament-tree/.prettierrc'
["INFO" - 5:56:21 PM] PrettierInstance:
{
  "modulePath": "/Users/saade/GovDigital/govdigital/packages/filament-tree/node_modules/prettier/index.js",
  "version": "2.8.8",
  "prettierModule": {
    "doc": {
      "builders": {
        "line": {
          "type": "line"
        },
        "softline": {
          "type": "line",
          "soft": true
        },
        "hardline": {
          "type": "concat",
          "parts": [
            {
              "type": "line",
              "hard": true
            },
            {
              "type": "break-parent"
            }
          ]
        },
        "literalline": {
          "type": "concat",
          "parts": [
            {
              "type": "line",
              "hard": true,
              "literal": true
            },
            {
              "type": "break-parent"
            }
          ]
        },
        "lineSuffixBoundary": {
          "type": "line-suffix-boundary"
        },
        "cursor": {
          "type": "cursor"
        },
        "breakParent": {
          "type": "break-parent"
        },
        "trim": {
          "type": "trim"
        },
        "hardlineWithoutBreakParent": {
          "type": "line",
          "hard": true
        },
        "literallineWithoutBreakParent": {
          "type": "line",
          "hard": true,
          "literal": true
        }
      },
      "printer": {},
      "utils": {},
      "debug": {}
    },
    "version": "2.8.8",
    "util": {},
    "__internal": {
      "errors": {},
      "coreOptions": {
        "CATEGORY_CONFIG": "Config",
        "CATEGORY_EDITOR": "Editor",
        "CATEGORY_FORMAT": "Format",
        "CATEGORY_OTHER": "Other",
        "CATEGORY_OUTPUT": "Output",
        "CATEGORY_GLOBAL": "Global",
        "CATEGORY_SPECIAL": "Special",
        "options": {
          "cursorOffset": {
            "since": "1.4.0",
            "category": "Special",
            "type": "int",
            "default": -1,
            "range": {
              "start": -1,
              "end": null,
              "step": 1
            },
            "description": "Print (to stderr) where a cursor at the given position would move to after formatting.\nThis option cannot be used with --range-start and --range-end.",
            "cliCategory": "Editor"
          },
          "endOfLine": {
            "since": "1.15.0",
            "category": "Global",
            "type": "choice",
            "default": [
              {
                "since": "1.15.0",
                "value": "auto"
              },
              {
                "since": "2.0.0",
                "value": "lf"
              }
            ],
            "description": "Which end of line characters to apply.",
            "choices": [
              {
                "value": "lf",
                "description": "Line Feed only (\\n), common on Linux and macOS as well as inside git repos"
              },
              {
                "value": "crlf",
                "description": "Carriage Return + Line Feed characters (\\r\\n), common on Windows"
              },
              {
                "value": "cr",
                "description": "Carriage Return character only (\\r), used very rarely"
              },
              {
                "value": "auto",
                "description": "Maintain existing\n(mixed values within one file are normalised by looking at what's used after the first line)"
              }
            ]
          },
          "filepath": {
            "since": "1.4.0",
            "category": "Special",
            "type": "path",
            "description": "Specify the input filepath. This will be used to do parser inference.",
            "cliName": "stdin-filepath",
            "cliCategory": "Other",
            "cliDescription": "Path to the file to pretend that stdin comes from."
          },
          "insertPragma": {
            "since": "1.8.0",
            "category": "Special",
            "type": "boolean",
            "default": false,
            "description": "Insert @format pragma into file's first docblock comment.",
            "cliCategory": "Other"
          },
          "parser": {
            "since": "0.0.10",
            "category": "Global",
            "type": "choice",
            "default": [
              {
                "since": "0.0.10",
                "value": "babylon"
              },
              {
                "since": "1.13.0"
              }
            ],
            "description": "Which parser to use.",
            "choices": [
              {
                "value": "flow",
                "description": "Flow"
              },
              {
                "value": "babel",
                "since": "1.16.0",
                "description": "JavaScript"
              },
              {
                "value": "babel-flow",
                "since": "1.16.0",
                "description": "Flow"
              },
              {
                "value": "babel-ts",
                "since": "2.0.0",
                "description": "TypeScript"
              },
              {
                "value": "typescript",
                "since": "1.4.0",
                "description": "TypeScript"
              },
              {
                "value": "acorn",
                "since": "2.6.0",
                "description": "JavaScript"
              },
              {
                "value": "espree",
                "since": "2.2.0",
                "description": "JavaScript"
              },
              {
                "value": "meriyah",
                "since": "2.2.0",
                "description": "JavaScript"
              },
              {
                "value": "css",
                "since": "1.7.1",
                "description": "CSS"
              },
              {
                "value": "less",
                "since": "1.7.1",
                "description": "Less"
              },
              {
                "value": "scss",
                "since": "1.7.1",
                "description": "SCSS"
              },
              {
                "value": "json",
                "since": "1.5.0",
                "description": "JSON"
              },
              {
                "value": "json5",
                "since": "1.13.0",
                "description": "JSON5"
              },
              {
                "value": "json-stringify",
                "since": "1.13.0",
                "description": "JSON.stringify"
              },
              {
                "value": "graphql",
                "since": "1.5.0",
                "description": "GraphQL"
              },
              {
                "value": "markdown",
                "since": "1.8.0",
                "description": "Markdown"
              },
              {
                "value": "mdx",
                "since": "1.15.0",
                "description": "MDX"
              },
              {
                "value": "vue",
                "since": "1.10.0",
                "description": "Vue"
              },
              {
                "value": "yaml",
                "since": "1.14.0",
                "description": "YAML"
              },
              {
                "value": "glimmer",
                "since": "2.3.0",
                "description": "Ember / Handlebars"
              },
              {
                "value": "html",
                "since": "1.15.0",
                "description": "HTML"
              },
              {
                "value": "angular",
                "since": "1.15.0",
                "description": "Angular"
              },
              {
                "value": "lwc",
                "since": "1.17.0",
                "description": "Lightning Web Components"
              }
            ]
          },
          "plugins": {
            "since": "1.10.0",
            "type": "path",
            "array": true,
            "default": [
              {
                "value": []
              }
            ],
            "category": "Global",
            "description": "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.",
            "cliName": "plugin",
            "cliCategory": "Config"
          },
          "pluginSearchDirs": {
            "since": "1.13.0",
            "type": "path",
            "array": true,
            "default": [
              {
                "value": []
              }
            ],
            "category": "Global",
            "description": "Custom directory that contains prettier plugins in node_modules subdirectory.\nOverrides default behavior when plugins are searched relatively to the location of Prettier.\nMultiple values are accepted.",
            "cliName": "plugin-search-dir",
            "cliCategory": "Config"
          },
          "printWidth": {
            "since": "0.0.0",
            "category": "Global",
            "type": "int",
            "default": 80,
            "description": "The line length where Prettier will try wrap.",
            "range": {
              "start": 0,
              "end": null,
              "step": 1
            }
          },
          "rangeEnd": {
            "since": "1.4.0",
            "category": "Special",
            "type": "int",
            "default": null,
            "range": {
              "start": 0,
              "end": null,
              "step": 1
            },
            "description": "Format code ending at a given character offset (exclusive).\nThe range will extend forwards to the end of the selected statement.\nThis option cannot be used with --cursor-offset.",
            "cliCategory": "Editor"
          },
          "rangeStart": {
            "since": "1.4.0",
            "category": "Special",
            "type": "int",
            "default": 0,
            "range": {
              "start": 0,
              "end": null,
              "step": 1
            },
            "description": "Format code starting at a given character offset.\nThe range will extend backwards to the start of the first line containing the selected statement.\nThis option cannot be used with --cursor-offset.",
            "cliCategory": "Editor"
          },
          "requirePragma": {
            "since": "1.7.0",
            "category": "Special",
            "type": "boolean",
            "default": false,
            "description": "Require either '@prettier' or '@format' to be present in the file's first docblock comment\nin order for it to be formatted.",
            "cliCategory": "Other"
          },
          "tabWidth": {
            "type": "int",
            "category": "Global",
            "default": 2,
            "description": "Number of spaces per indentation level.",
            "range": {
              "start": 0,
              "end": null,
              "step": 1
            }
          },
          "useTabs": {
            "since": "1.0.0",
            "category": "Global",
            "type": "boolean",
            "default": false,
            "description": "Indent with tabs instead of spaces."
          },
          "embeddedLanguageFormatting": {
            "since": "2.1.0",
            "category": "Global",
            "type": "choice",
            "default": [
              {
                "since": "2.1.0",
                "value": "auto"
              }
            ],
            "description": "Control how Prettier formats quoted code embedded in the file.",
            "choices": [
              {
                "value": "auto",
                "description": "Format embedded code if Prettier can automatically identify it."
              },
              {
                "value": "off",
                "description": "Never automatically format embedded code."
              }
            ]
          }
        }
      },
      "optionsModule": {
        "hiddenDefaults": {
          "astFormat": "estree",
          "printer": {},
          "locStart": null,
          "locEnd": null
        }
      },
      "optionsNormalizer": {},
      "utils": {}
    },
    "__debug": {}
  }
}
["INFO" - 5:56:21 PM] Using ignore file (if present) at /Users/saade/GovDigital/govdigital/packages/filament-tree/.prettierignore
["INFO" - 5:56:21 PM] File Info:
{
  "ignored": false,
  "inferredParser": "blade"
}
["INFO" - 5:56:21 PM] Detected local configuration (i.e. .prettierrc or .editorconfig), VS Code configuration will not be used
["INFO" - 5:56:21 PM] Prettier Options:
{
  "filepath": "/Users/saade/GovDigital/govdigital/packages/filament-tree/resources/views/components/tree-item.blade.php",
  "parser": "blade",
  "useTabs": false,
  "tabWidth": 4,
  "endOfLine": "lf",
  "plugins": [
    "/Users/saade/GovDigital/govdigital/packages/filament-tree/node_modules/@shufo/prettier-plugin-blade/dist/index.cjs"
  ],
  "semi": false,
  "singleQuote": true,
  "trailingComma": "all"
}
["ERROR" - 5:56:21 PM] Error formatting document.
["ERROR" - 5:56:21 PM] Unknown node type: undefined
Error: Unknown node type: undefined
    at Object.u [as print] (/Users/saade/GovDigital/govdigital/packages/filament-tree/node_modules/@shufo/prettier-plugin-blade/src/options.ts:3:3)
    at callPluginPrintFunction (/Users/saade/GovDigital/govdigital/packages/filament-tree/node_modules/prettier/index.js:8601:26)
    at mainPrintInternal (/Users/saade/GovDigital/govdigital/packages/filament-tree/node_modules/prettier/index.js:8550:22)
    at mainPrint (/Users/saade/GovDigital/govdigital/packages/filament-tree/node_modules/prettier/index.js:8537:18)
    at printAstToDoc (/Users/saade/GovDigital/govdigital/packages/filament-tree/node_modules/prettier/index.js:8529:18)
    at coreFormat (/Users/saade/GovDigital/govdigital/packages/filament-tree/node_modules/prettier/index.js:8837:20)
    at formatWithCursor2 (/Users/saade/GovDigital/govdigital/packages/filament-tree/node_modules/prettier/index.js:9021:18)
    at /Users/saade/GovDigital/govdigital/packages/filament-tree/node_modules/prettier/index.js:38183:12
    at Object.format (/Users/saade/GovDigital/govdigital/packages/filament-tree/node_modules/prettier/index.js:38197:12)
    at t.PrettierMainThreadInstance.format (/Users/saade/.vscode/extensions/esbenp.prettier-vscode-10.1.0/dist/extension.js:1:18023)
    at t.default.format (/Users/saade/.vscode/extensions/esbenp.prettier-vscode-10.1.0/dist/extension.js:1:16114)
    at t.PrettierEditProvider.provideEdits (/Users/saade/.vscode/extensions/esbenp.prettier-vscode-10.1.0/dist/extension.js:1:12672)
    at U.provideDocumentFormattingEdits (/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/api/node/extensionHostProcess.js:104:44948)
["INFO" - 5:56:21 PM] Formatting completed in 8ms.

Having trouble installing this plugin inside a ubuntu docker container

Hello I am unsure why this is, but I cannot install this package globally inside my docker container. I am using nvm, node 16.17.0 and npm 8.15.1

root@f1b532f4d6c2:/# npm install -g  @shufo/prettier-plugin-blade
npm ERR! code 127
npm ERR! path /root/.nvm/versions/node/v16.17.0/lib/node_modules/@shufo/prettier-plugin-blade/node_modules/core-js-pure
npm ERR! command failed
npm ERR! command sh /tmp/postinstall-22261380.sh
npm ERR! /tmp/postinstall-22261380.sh: line 1: node: command not found

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2022-10-11T12_45_56_504Z-debug-0.log

Log output:
https://pastebin.com/7UuMu6Kx

vue `v-else-if` wrong formatting

If in blade template there is this tag

<span v-else-if="value.name === 'Name'">

formatting turns it into

<span v-else-if="value.name === 'Name'" v-else-if="value.name === 'Name'">

Usage with vscode ext in WSL

Hi

I have a laravel, with blade ( TALL ) files.

The project is in WSL2 and the editor is perfectly used with remote extension provided automatically.

But If I try to use this plugin with the formatter extension in vscode, the process fails to format trying to find this module.

If i try to run the formatter with default ( local packages) , this is the output:

["INFO" - 11:10:00 AM] Formatting file:///home/nameofuser/code/laravel/nameofproject/resources/views/invoices/documents/edit-with-tab.blade.php
["INFO" - 11:10:00 AM] Using config file at '/home/nameofuser/code/laravel/nameofproject/.prettierrc.json'
["INFO" - 11:10:00 AM] Using ignore file (if present) at /home/nameofuser/code/laravel/nameofproject/.prettierignore
["INFO" - 11:10:00 AM] File Info:
{
  "ignored": false,
  "inferredParser": "php"
}
["INFO" - 11:10:00 AM] Detected local configuration (i.e. .prettierrc or .editorconfig), VS Code configuration will not be used
["INFO" - 11:10:00 AM] Prettier Options:
{
  "filepath": "/home/nameofuser/code/laravel/nameofproject/resources/views/invoices/documents/edit-with-tab.blade.php",
  "parser": "php",
  "useTabs": false,
  "tabWidth": 4,
  "endOfLine": "lf",
  "printWidth": 120,
  "wrapAttributes": "auto",
  "sortTailwindcssClasses": true,
  "plugins": [
    "@shufo/prettier-plugin-blade"
  ]
}
["ERROR" - 11:10:00 AM] Error formatting document.
["ERROR" - 11:10:00 AM] Cannot find module '@shufo/prettier-plugin-blade'
Require stack:
- /home/nameofuser/code/laravel/nameofproject/node_modules/prettier/index.js
- /home/nameofuser/.vscode-server/extensions/esbenp.prettier-vscode-9.5.0/dist/extension.js
- /home/nameofuser/.vscode-server/bin/dfd34e8260c270da74b5c2d86d61aee4b6d56977/out/vs/loader.js
- /home/nameofuser/.vscode-server/bin/dfd34e8260c270da74b5c2d86d61aee4b6d56977/out/bootstrap-amd.js
- /home/nameofuser/.vscode-server/bin/dfd34e8260c270da74b5c2d86d61aee4b6d56977/out/bootstrap-fork.js
Error: Cannot find module '@shufo/prettier-plugin-blade'
Require stack:
- /home/nameofuser/code/laravel/nameofproject/node_modules/prettier/index.js
- /home/nameofuser/.vscode-server/extensions/esbenp.prettier-vscode-9.5.0/dist/extension.js
- /home/nameofuser/.vscode-server/bin/dfd34e8260c270da74b5c2d86d61aee4b6d56977/out/vs/loader.js
- /home/nameofuser/.vscode-server/bin/dfd34e8260c270da74b5c2d86d61aee4b6d56977/out/bootstrap-amd.js
- /home/nameofuser/.vscode-server/bin/dfd34e8260c270da74b5c2d86d61aee4b6d56977/out/bootstrap-fork.js
	at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
	at resolve (node:internal/modules/cjs/helpers:108:19)
	at /home/nameofuser/code/laravel/nameofproject/node_modules/prettier/index.js:39110:25
	at Array.map (<anonymous>)
	at Object.load (/home/nameofuser/code/laravel/nameofproject/node_modules/prettier/index.js:39105:65)
	at Object.load [as loadPlugins] (/home/nameofuser/code/laravel/nameofproject/node_modules/prettier/index.js:15998:27)
	at /home/nameofuser/code/laravel/nameofproject/node_modules/prettier/index.js:39172:24
	at Object.format (/home/nameofuser/code/laravel/nameofproject/node_modules/prettier/index.js:39188:12)
	at t.default.format (/home/nameofuser/.vscode-server/extensions/esbenp.prettier-vscode-9.5.0/dist/extension.js:1:13427)
	at async t.PrettierEditProvider.provideEdits (/home/nameofuser/.vscode-server/extensions/esbenp.prettier-vscode-9.5.0/dist/extension.js:1:10134)
	at async B.provideDocumentFormattingEdits (/home/nameofuser/.vscode-server/bin/dfd34e8260c270da74b5c2d86d61aee4b6d56977/out/vs/workbench/api/node/extensionHostProcess.js:85:102917)
["INFO" - 11:10:00 AM] Formatting completed in 0.03ms.

If i try to use global defined prettier path, the process doesn't work.

["INFO" - 11:10:00 AM] Formatting file:///home/nameofuser/code/laravel/nameofproject/resources/views/invoices/documents/edit-with-tab.blade.php
["INFO" - 11:10:00 AM] Using config file at '/home/nameofuser/code/laravel/nameofproject/.prettierrc.json'
["INFO" - 11:10:00 AM] Using ignore file (if present) at /home/nameofuser/code/laravel/nameofproject/.prettierignore
["INFO" - 11:10:00 AM] File Info:
{
  "ignored": false,
  "inferredParser": "php"
}
["INFO" - 11:10:00 AM] Detected local configuration (i.e. .prettierrc or .editorconfig), VS Code configuration will not be used
["INFO" - 11:10:00 AM] Prettier Options:
{
  "filepath": "/home/nameofuser/code/laravel/nameofproject/resources/views/invoices/documents/edit-with-tab.blade.php",
  "parser": "php",
  "useTabs": false,
  "tabWidth": 4,
  "endOfLine": "lf",
  "printWidth": 120,
  "wrapAttributes": "auto",
  "sortTailwindcssClasses": true,
  "plugins": [
    "@shufo/prettier-plugin-blade"
  ]
}
["ERROR" - 11:10:00 AM] Error formatting document.
["ERROR" - 11:10:00 AM] Cannot find module '@shufo/prettier-plugin-blade'
Require stack:
- /home/nameofuser/code/laravel/nameofproject/node_modules/prettier/index.js
- /home/nameofuser/.vscode-server/extensions/esbenp.prettier-vscode-9.5.0/dist/extension.js
- /home/nameofuser/.vscode-server/bin/dfd34e8260c270da74b5c2d86d61aee4b6d56977/out/vs/loader.js
- /home/nameofuser/.vscode-server/bin/dfd34e8260c270da74b5c2d86d61aee4b6d56977/out/bootstrap-amd.js
- /home/nameofuser/.vscode-server/bin/dfd34e8260c270da74b5c2d86d61aee4b6d56977/out/bootstrap-fork.js
Error: Cannot find module '@shufo/prettier-plugin-blade'
Require stack:
- /home/nameofuser/code/laravel/nameofproject/node_modules/prettier/index.js
- /home/nameofuser/.vscode-server/extensions/esbenp.prettier-vscode-9.5.0/dist/extension.js
- /home/nameofuser/.vscode-server/bin/dfd34e8260c270da74b5c2d86d61aee4b6d56977/out/vs/loader.js
- /home/nameofuser/.vscode-server/bin/dfd34e8260c270da74b5c2d86d61aee4b6d56977/out/bootstrap-amd.js
- /home/nameofuser/.vscode-server/bin/dfd34e8260c270da74b5c2d86d61aee4b6d56977/out/bootstrap-fork.js
	at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
	at resolve (node:internal/modules/cjs/helpers:108:19)
	at /home/nameofuser/code/laravel/nameofproject/node_modules/prettier/index.js:39110:25
	at Array.map (<anonymous>)
	at Object.load (/home/nameofuser/code/laravel/nameofproject/node_modules/prettier/index.js:39105:65)
	at Object.load [as loadPlugins] (/home/nameofuser/code/laravel/nameofproject/node_modules/prettier/index.js:15998:27)
	at /home/nameofuser/code/laravel/nameofproject/node_modules/prettier/index.js:39172:24
	at Object.format (/home/nameofuser/code/laravel/nameofproject/node_modules/prettier/index.js:39188:12)
	at t.default.format (/home/nameofuser/.vscode-server/extensions/esbenp.prettier-vscode-9.5.0/dist/extension.js:1:13427)
	at async t.PrettierEditProvider.provideEdits (/home/nameofuser/.vscode-server/extensions/esbenp.prettier-vscode-9.5.0/dist/extension.js:1:10134)
	at async B.provideDocumentFormattingEdits (/home/nameofuser/.vscode-server/bin/dfd34e8260c270da74b5c2d86d61aee4b6d56977/out/vs/workbench/api/node/extensionHostProcess.js:85:102917)
["INFO" - 11:10:00 AM] Formatting completed in 0.03ms.

Note: if i try tu use CLI the process work perfectly.

This is my package.json file

"devDependencies": {
        "@shufo/prettier-plugin-blade": "^1.3.5",
        "@tailwindcss/aspect-ratio": "^0.4.0",
        "@tailwindcss/forms": "^0.4.0",
        "@tailwindcss/line-clamp": "^0.3.0",
        "@tailwindcss/typography": "^0.5.0",
        "alpinejs": "^3.5.0",
        "autoprefixer": "^10.4.0",
        "axios": "^0.24.0",
        "laravel-echo": "^1.11.3",
        "laravel-mix": "^6.0.37",
        "lodash": "^4.17.19",
        "postcss": "^8.4.5",
        "postcss-import": "^14.0.2",
        "postcss-nesting": "^9.0.0",
        "prettier": "2.6.2",
        "pusher-js": "^7.0.3",
        "tailwindcss": "^3.0.3"
    },
    "dependencies": {
        "@alpinejs/collapse": "^3.9.0",
        "@alpinejs/focus": "^3.8.1",
        "@ryangjchandler/alpine-clipboard": "^2.1.0",
        "@ryangjchandler/alpine-tooltip": "^1.1.0",
        "canvas-confetti": "^1.4.0",
        "clockwork-browser": "^1.1.0",
        "dayjs": "^1.10.7",
        "fuse.js": "^6.4.6",
        "shiki": "^0.9.12"
    }

Any ideas to solve? this extension work only with CLI command?

Empty lines

The plugin does not collapse multiple blank lines into a single blank line.

It would be great if it supported this like other parsers.

does this work globally?

i've done npm i -g @shufo/prettier-plugin-blade, reloaded vscode, and formatting does not work

i did the same for the prettier php plugin, installed global and formatting works fine

does this work with global npm install?

i also added this to my settings.json which was required to make prettier php plugin work:

  "prettier.resolveGlobalModules": true,

this does not make this plugin work tho

[Feature Request]: Exclude @props directive from formatting

Description

Before

@props([
    'item', 
    'page', 
    'test' => 'long text'
])

After

@props(['item', 'loop', 'page', 'test' => 'long text'])

Suggested Solution

Bypass all Laravel @directives

Alternatives

No response

Additional Context

No response

[Formatting Bug]: Bad HTML formatting

Version

1.10.0

Template before formatting

<!DOCTYPE html>
<html>
    <head>
        <meta
            http-equiv="Content-Type"
            content="text/html; charset=utf-8"
        />
        <title>
            Test Title
        </title>
    </head>
    <body
        onLoad="window.print();"
        style="margin: 0; padding: 0"
    >
        <div
            id="divPage"
            style="text-align: center; margin: 0 auto; width: 700px"
        >
            <?php echo $output; ?>
        </div>
    </body>
</html>

Template after formatting

<!DOCTYPE html>
<html>

<head>
    <meta
        http-equiv="Content-Type"
        content="text/html; charset=utf-8"
    />
    <title>
        Test Title
    </title>
</head>

<body
    onLoad="window.print();"
    style="margin: 0; padding: 0"
>
    <div
        id="divPage"
        style="text-align: center; margin: 0 auto; width: 700px"
    >
        <?php echo $output; ?>
    </div>
</body>

</html>

Expected Behaviour

Hello!

The plugin is messing up the indentation of the html, head and body should be indented and there shouldn't be newlines between the tags.

For reference, here is the same text formatted in a test.html file (using the default html parser, also note the doctype is converted to lower case):

<!doctype html>
<html>
    <head>
        <meta
            http-equiv="Content-Type"
            content="text/html; charset=utf-8"
        />
        <title>Test Title</title>
    </head>
    <body
        onLoad="window.print();"
        style="margin: 0; padding: 0"
    >
        <div
            id="divPage"
            style="text-align: center; margin: 0 auto; width: 700px"
        >
            <?php echo $output; ?>
        </div>
    </body>
</html>

Perhaps it would be possible/easier to reuse the functionality from the default prettier html parser?

Thanks!

Relevant log output

No response

VSCode inferredParser: "php"

Hi, I just installed this plugin, but it doesn't appear to work with VSCode. I had it working a couple of weeks ago, but it suddenly stopped. Prettier is using the wrong parser, I think? It's using the php parser instead of the blade parser?

["INFO" - 3:14:23 PM] Formatting completed in 0.012ms.
["INFO" - 3:14:31 PM] Formatting file:///home/ryan/code/maintenance/resources/views/livewire/procedures/form.blade.php
["INFO" - 3:14:31 PM] Using config file at '/home/ryan/code/maintenance/package.json'
["INFO" - 3:14:31 PM] Using ignore file (if present) at /home/ryan/code/maintenance/.prettierignore
["INFO" - 3:14:31 PM] File Info:
{
  "ignored": false,
  "inferredParser": "php"
}
["INFO" - 3:14:31 PM] Detected local configuration (i.e. .prettierrc or .editorconfig), VS Code configuration will not be used
["INFO" - 3:14:31 PM] Prettier Options:
{
  "filepath": "/home/ryan/code/maintenance/resources/views/livewire/procedures/form.blade.php",
  "parser": "php",
  "useTabs": false,
  "tabWidth": 4,
  "endOfLine": "lf",
  "phpVersion": "7.4",
  "printWidth": 120,
  "singleQuote": true,
  "wrapAttributes": "force-aligned"
}
["INFO" - 3:14:31 PM] Formatting completed in 0.039ms.

Cannot seem to get sortTailwindcssClasses working in VSCode

I cannot seem to get the Tailwindcss auto sorting working in VSCode. On save it does seem to use the prettier-plugin-blade package.

I'm testing this by juggling some Tailwind classes in my blade template into a random order. What am I doing wrong?

{
	"semi": true,
	"singleQuote": true,
	"trailingComma": "es5",
	"printWidth": 150,
	"useTabs": true,
	"tabWidth": 1,
	"plugins": ["@shufo/prettier-plugin-blade"],
	"overrides": [
		{
			"files": ["*.blade.php"],
			"options": {
				"parser": "blade",
				"printWidth": 999,
				"sortTailwindcssClasses": true,
				"wrapAttributes": "auto",
				"sortHtmlAttributes": "none",
				"noPhpSyntaxCheck": false
			}
		}
	]
}

Saving a .blade.php file

["INFO" - 3:47:23 PM] Prettier Options:
{
  "filepath": "/mypath/resources/views/vp-account-settings.blade.php",
  "parser": "blade",
  "useTabs": true,
  "tabWidth": 1,
  "endOfLine": "lf",
  "semi": true,
  "singleQuote": true,
  "trailingComma": "es5",
  "printWidth": 999,
  "plugins": [
    "/mypath/node_modules/@shufo/prettier-plugin-blade/dist/index.js"
  ],
  "sortTailwindcssClasses": true,
  "wrapAttributes": "auto",
  "sortHtmlAttributes": "none",
  "noPhpSyntaxCheck": false
}
["INFO" - 3:47:23 PM] Formatting completed in 139ms.```

prettier-plugin-blade not honouring singleAttributePerLine setting

prettierrc.json (note the singleAttributePerLine)

{
    "jsxSingleQuote": true,
    "singleQuote": true,
    "printWidth": 100,
    "singleAttributePerLine": true,
    "sortTailwindcssClasses": true,
    "plugins": ["@shufo/prettier-plugin-blade"]
}

package.json (note the latest version of prettier is used 2.6.0)

{
  "devDependencies": {
    "@shufo/prettier-plugin-blade": "^1.1.10",
    "prettier": "^2.6.0",
  }
}

When running:

npx prettier -w resources/views/components/example.blade.php

resources/views/components/example.blade.php

<div id="test" class="test absolute m-2 block h-4 w-4">
    @if (true)
        test
    @endif
</div>

Expected output

<div
    id="test"
    class="test absolute m-2 block h-4 w-4"
>
    @if (true)
        test
    @endif
</div>

Actual output

<div id="test" class="test absolute m-2 block h-4 w-4">
    @if (true)
        test
    @endif
</div>

Community

This is awesome. Didn't know that this exists. Maybe we should try to educate the community that it exists.

[Feature Request]: classes in @class directive sorting support

Version

1.8.10

Template before formatting

<a href="{{ $item['url']() }}" @class([
    'relative flex items-center h-10 transition duration-200 rounded-lg border-transparent border-2 focus:ring-1 focus:outline-none focus:ring-gray-800 hover:bg-gray-100/5 hover:border-gray-100/10',
    'text-white bg-gray-100/5 border-gray-100/10' => $isActive,
    'text-gray-400 hover:text-white' => !$isActive,
])>

Template after formatting

<a href="{{ $item['url']() }}" @class([
    'relative flex items-center h-10 transition duration-200 rounded-lg border-transparent border-2 focus:ring-1 focus:outline-none focus:ring-gray-800 hover:bg-gray-100/5 hover:border-gray-100/10',
    'text-white bg-gray-100/5 border-gray-100/10' => $isActive,
    'text-gray-400 hover:text-white' => !$isActive,
])>

Expected Behaviour

The individual class lines aren't sorted.

Relevant log output

No response

HTML attributes keep indenting when value is an object

Input

@component('some.file')
    <div>
        <input
            type="text"
            an-object="{
                'Some error': slot.props.hasError,
            }"
        />
    </div>
@endcomponent

Expected

@component('some.file')
    <div>
        <input
            type="text"
            an-object="{
                'Some error': slot.props.hasError,
            }"
        />
    </div>
@endcomponent

Actual

@component('some.file')
    <div>
        <input
            type="text"
            an-object="{
                        'Some error': slot.props.hasError,
                    }"
        />
    </div>
@endcomponent

If you run prettier again on the actual outcome, then the indentation increases further

@component('some.file')
    <div>
        <input
            type="text"
            an-object="{
                            'Some error': slot.props.hasError,
                        }"
        />
    </div>
@endcomponent

Surrounding the code in @component directives is important here to reproduce the error

Parse only blade files. Ignore other .php files

Hi there,

I thought this plugin would only parse .*blade.php files but it also does with all *.php files.

It is possible to only parse blade files? For the basic PHP I've already have laravel-pint.

Tailwind CSS sorting with custom values does not seem to work

Thanks so much for this plugin. I've noticed that the Tailwind CSS class sorting does not seem to work when there's a custom value in the class list. In fact the formatter seems to "give up" on the class attribute entirely

E.g.:

<div class="md:tw-mx-[1rem]   tw-mx-1"></div>

Expected result:

<div class="tw-mx-1 md:tw-mx-[1rem]"></div>

Actual result:

<div class="md:tw-mx-[1rem]   tw-mx-1"></div>

Invalid quote type used in @php block

This is kind of an edge case, but I'll mention it anyway.

Input

@php
$icon = "<i class='fa fa-check'></i>";
@endphp

Output

@php
$icon = '<i class='fa fa-check'></i>';
@endphp

Apparently this only happens with html strings in double quotes inside @php blocks. Which I'll admit is a weird thing to have in a blade file, but I didn't know that at the time.

Usage in combination with Tailwind CSS Prettier Plugin

Is it possible to run it with the Tailwind CSS Prettier Plugin? I installed it alongside this package and it is not working.

I would expect it to properly sort the classes when both plugins are installed.

<div class="white px-4 sm:px-8 py-2 sm:py-3 bg-sky-700 hover:bg-sky-800">
</div>

Component/Livewire attribute error

Hi, if i try to use cli on blade that has component or livewire tag, the plugin add me space in variable chain.

Before:

<x-component-name type="error" :content="$message->content"/>

After:

<x-component-name type="error" :content="$message - > content"/>

It's a bug or an option?

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/auto-assign.yml
  • technote-space/assign-author v1
  • pozil/auto-assign-issue v1.13.0
.github/workflows/contributors.yml
  • akhilmhdh/contributors-readme-action v2.3.6
.github/workflows/create-release.yml
  • GoogleCloudPlatform/release-please-action v4
  • actions/checkout v4
  • actions/setup-node v4
  • actions/cache v4
.github/workflows/labels.yml
  • actions/checkout v4
  • micnncim/action-label-syncer v1
.github/workflows/node.yml
  • actions/checkout v4
  • actions/setup-node v4
  • actions/cache v4
  • codecov/codecov-action v4
.github/workflows/platform-test.yml
  • actions/checkout v4
  • actions/setup-node v4
  • actions/cache v4
.github/workflows/rebase.yml
  • cirrus-actions/rebase 1.8
.github/workflows/stale.yml
  • actions/stale v9
npm
package.json
  • blade-formatter 1.41.1
  • prettier 3.2.5
  • @biomejs/biome 1.5.3
  • @types/concat-stream ^2.0.0
  • @types/prettier ^2.4.4
  • codecov ^3.8.3
  • concat-stream ^2.0.0
  • cross-env ^7.0.3
  • esbuild ^0.19.0
  • esbuild-node-externals ^1.4.1
  • ts-node ^10.5.0
  • typescript ^5.0.0
  • vitest ^1.3.1
  • node >= 14.0.0

  • Check this box to trigger a request for Renovate to run again on this repository

wrapAttributes option not working on Fedora Linux.

Hi,
It seems like the wrapAttributes option is no longer working on Fedora Linux 35 after blade-formatter was bumped to 1.26.5 on Node 16.14.2.

"devDependencies": {
    "@prettier/plugin-php": "0.18.8",
    "@shufo/prettier-plugin-blade": "1.4.13",
    "prettier": "2.7.1"
},
{
    "bracketSameLine": true,
    "phpVersion": "8.1",
    "plugins": ["./node_modules/@shufo/prettier-plugin-blade"],
    "printWidth": 120,
    "tabWidth": 4,
    "wrapAttributes": "preserve",
    "overrides": [
        {
            "files": "*.blade.php",
            "options": {
                "parser": "blade"
            }
        }
    ]
}

Input

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>

</html>

Output

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>

</html>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.