Giter Club home page Giter Club logo

prettier-plugin-tailwindcss's Introduction

prettier-plugin-tailwindcss

A Prettier v3+ plugin for Tailwind CSS v3.0+ that automatically sorts classes based on our recommended class order.

Installation

To get started, install prettier-plugin-tailwindcss as a dev-dependency:

npm install -D prettier prettier-plugin-tailwindcss

Then add the plugin to your Prettier configuration:

// .prettierrc
{
  "plugins": ["prettier-plugin-tailwindcss"]
}

Upgrading to v0.5.x

As of v0.5.x, this plugin now requires Prettier v3 and is ESM-only. This means it cannot be loaded via require(). For more information see our upgrade guide.

Options

Customizing your Tailwind config path

To ensure that the class sorting takes into consideration any of your project's Tailwind customizations, it needs access to your Tailwind configuration file (tailwind.config.js).

By default the plugin will look for this file in the same directory as your Prettier configuration file. However, if your Tailwind configuration is somewhere else, you can specify this using the tailwindConfig option in your Prettier configuration.

Note that paths are resolved relative to the Prettier configuration file.

// .prettierrc
{
  "tailwindConfig": "./styles/tailwind.config.js"
}

If a local configuration file cannot be found the plugin will fallback to the default Tailwind configuration.

Sorting non-standard attributes

By default this plugin only sorts classes in the class attribute as well as any framework-specific equivalents like class, className, :class, [ngClass], etc.

You can sort additional attributes using the tailwindAttributes option, which takes an array of attribute names:

// .prettierrc
{
  "tailwindAttributes": ["myClassList"]
}

With this configuration, any classes found in the myClassList attribute will be sorted:

function MyButton({ children }) {
  return (
    <button myClassList="rounded bg-blue-500 px-4 py-2 text-base text-white">
      {children}
    </button>
  );
}

Sorting classes in function calls

In addition to sorting classes in attributes, you can also sort classes in strings provided to function calls. This is useful when working with libraries like clsx or cva.

You can sort classes in function calls using the tailwindFunctions option, which takes a list of function names:

// .prettierrc
{
  "tailwindFunctions": ["clsx"]
}

With this configuration, any classes in clsx() function calls will be sorted:

import clsx from 'clsx'

function MyButton({ isHovering, children }) {
  let classes = clsx(
    'rounded bg-blue-500 px-4 py-2 text-base text-white',
    {
      'bg-blue-700 text-gray-100': isHovering,
    },
  )

  return (
    <button className={classes}>
      {children}
    </button>
  )
}

Sorting classes in template literals

This plugin also enables sorting of classes in tagged template literals.

You can sort classes in template literals using the tailwindFunctions option, which takes a list of function names:

// .prettierrc
{
  "tailwindFunctions": ["tw"],
}

With this configuration, any classes in template literals tagged with tw will automatically be sorted:

import { View, Text } from 'react-native'
import tw from 'twrnc'

function MyScreen() {
  return (
    <View style={tw`bg-white p-4 dark:bg-black`}>
      <Text style={tw`text-md text-black dark:text-white`}>Hello World</Text>
    </View>
  )
}

This feature can be used with third-party libraries like twrnc or you can create your own tagged template by defining this "identity" function:

const tw = (strings, ...values) => String.raw({ raw: strings }, ...values)

Once added, tag your strings with the function and the plugin will sort them:

const mySortedClasses = tw`bg-white p-4 dark:bg-black`

Compatibility with other Prettier plugins

This plugin uses Prettier APIs that can only be used by one plugin at a time, making it incompatible with other Prettier plugins implemented the same way. To solve this we've added explicit per-plugin workarounds that enable compatibility with the following Prettier plugins:

  • @ianvs/prettier-plugin-sort-imports
  • @prettier/plugin-pug
  • @shopify/prettier-plugin-liquid
  • @trivago/prettier-plugin-sort-imports
  • prettier-plugin-astro
  • prettier-plugin-css-order
  • prettier-plugin-import-sort
  • prettier-plugin-jsdoc
  • prettier-plugin-organize-attributes
  • prettier-plugin-organize-imports
  • prettier-plugin-style-order
  • prettier-plugin-svelte
  • prettier-plugin-sort-imports

One limitation with this approach is that prettier-plugin-tailwindcss must be loaded last.

// .prettierrc
{
  // ..
  "plugins": [
    "prettier-plugin-svelte",
    "prettier-plugin-organize-imports",
    "prettier-plugin-tailwindcss" // MUST come last
  ]
}

prettier-plugin-tailwindcss's People

Contributors

adamwathan avatar alonski avatar angusmorton avatar bradlc avatar chrsep avatar giacomoferretti avatar j avatar juliusmarminge avatar lirobinxc avatar michaeldeboey avatar nikwen avatar notpeelz avatar ony3000 avatar princesseuh avatar reinink avatar robin-whg avatar robinmalfait avatar saibotk avatar simonswiss avatar thecrypticace avatar tobiasbueschel avatar ufukustali avatar uhyo avatar valtism avatar velut avatar vladimirmikulic avatar yannicel 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

prettier-plugin-tailwindcss's Issues

NextJS dev and build mismatch

What I did?

  • installed package (latest tailwind installed)
  • restarted server with npm run dev
  • entered couple of files and hit save
  • reformatting worked

What was the problem?

  • when I tried to do npm run build I got a lot of ESLint errors caused by prettier
  • all errors suggested that the order is different than it should be
  • I tried to delete .next dir, reinstall all and try to build again and still the problem remains
  • vs code reported no errors in those files, they were reformatted properly, but build complained

Installed packages:

"eslint": "8.7.0",
"eslint-config-airbnb": "19.0.4",
"eslint-config-next": "12.0.8",
"eslint-config-prettier": "8.3.0",
"eslint-plugin-import": "2.25.4",
"eslint-plugin-jsx-a11y": "6.5.1",
"eslint-plugin-prettier": "4.0.0",
"eslint-plugin-react": "7.28.0",
"eslint-plugin-react-hooks": "4.3.0",
"autoprefixer": "10.4.2",
"postcss": "8.4.5",
"prettier": "^2.5.1",
"prettier-eslint": "13.0.0",
"prettier-plugin-tailwindcss": "^0.1.4",
"tailwindcss": "3.0.16",

Screenshot 2022-01-25 at 21 03 23

Vscode autoformat doesn't work properly

What version of prettier-plugin-tailwindcss are you using?

For example: v0.1.8

What version of Tailwind CSS are you using?

For example: v3.0.23

What version of Node.js are you using?

For example: v14

What package manager are you using?

Yarn

What operating system are you using?

macOS

Describe your issue

Hello! I'm trying to use this plugin with VScode. However, it seems there is a conflict between VSCode settings. I couldn't figure out what happens.

Problem: When saving a file and then it will immediately turn back the previous class names. Any idea on this?

Untitled_ Mar 10, 2022 1_21 PM

Vscode config:

{
  "editor.formatOnPaste": true,
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
    "source.fixAll.format": true
  },
  "eslint.workingDirectories": ["./client"]
}

Eslint config:

{
  "extends": ["next/core-web-vitals", "prettier"],
  "plugins": ["prettier"],
  "rules": {
    "prettier/prettier": "error",
    "react/no-unescaped-entities": 0,
    "@next/next/no-img-element": "off",
    "@next/next/no-html-link-for-pages": "off"
  }
}

Package.json:

"devDependencies": {
    "@tailwindcss/aspect-ratio": "^0.4.0",
    "@tailwindcss/forms": "^0.4.0",
    "@tailwindcss/typography": "^0.5.2",
    "autoprefixer": "^10.4.0",
    "eslint": "^8.10.0",
    "eslint-config-next": "^12.1.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-plugin-prettier": "^4.0.0",
    "eslint-plugin-react": "^7.29.3",
    "eslint-webpack-plugin": "^3.1.1",
    "postcss": "^8.4.4",
    "prettier": "^2.5.1",
    "prettier-plugin-tailwindcss": "^0.1.8",
    "tailwind-scrollbar-hide": "^1.1.7",
    "tailwindcss": "^3.0.23"
  }

Incompatibility with other Prettier plugins

To make this plugin work we had to use private Prettier APIs that can only be used by a single plugin at once. This means this plugin is incompatible with other Prettier plugins that are using the same APIs.

This GitHub issue will serve as a place to keep track of which Prettier plugins are incompatible — and hopefully we'll eventually find some workarounds, or even a proper long term solution. 👍

Known incompatibilities

  • @trivago/prettier-plugin-sort-imports
  • prettier-plugin-organize-imports
  • prettier-plugin-svelte (see below)
  • prettier-plugin-twig-melody

prettier-plugin-svelte

We've bundled the prettier-plugin-svelte directly into prettier-plugin-tailwindcss, so if you'd like to use this plugin with Svelte, just uninstall prettier-plugin-svelte and everything should work as expected.

Workarounds

While I have not tested it yet, @Mattinton provided one possible workaround in this comment.

seems to have no effect on class lists in template literals

as an example:

<div
  className={`
    flex
    flex-col
    justify-between
    flex-1
    p-6
    bg-gradient-to-br
    bg-white
    from-white
    to-gray-200
    dark:bg-gray-800
    dark:from-gray-800
    dark:to-gray-900
    dark:text-gray-50
    ${className}
  `}
>

plugin seems to not operate on these strings, flattening them into a single line seems to not have any effect either

I have also tried randomly shuffling the class list to see if they were already sorted

Not working with `prettier-plugin-organize-imports`

It appears that either prettier-plugin-tailwindcss or prettier-plugin-organize-imports affect the file, based on which one appears last in the config plugin list, but not both.

Prettier Version: 2.5.1
prettier-plugin-tailwindcss version: 0.1.4
prettier-plugin-organize-imports version: 2.3.4

I am currently able to somewhat merge the two plugins manually by using the preprocess function from prettier-plugin-organize-imports, but it would be nice if the two got along without the patch:

// merged-prettier-plugin.js

const tailwind = require('prettier-plugin-tailwindcss')
const organizeImports = require('prettier-plugin-organize-imports')

const combinedFormatter = {
  ...tailwind,
  parsers: {
    ...tailwind.parsers,
    ...Object.keys(organizeImports.parsers).reduce((acc, key) => {
      acc[key] = {
        ...tailwind.parsers[key],
        preprocess(code, options) {
          return organizeImports.parsers[key].preprocess(code, options)
        },
      }
      return acc
    }, {}),
  },
}

module.exports = combinedFormatter
// .prettierrc.js

module.exports = {
  plugins: [require('./merged-prettier-plugin.js')],
  ...
}

Not working on HTML within .php files

Hey guys,

I installed the plugin and it's working like a charm on .html files (VSCode, Prettier extension + prettier php plugin).

However, doesn't seem to apply the same changes if file's extension is .php.

Am I missing something or currently HTML in PHP files is not supported?

Unable to get working VSCode formatOnSave

Apologies if this is a naive question, not had much experience with how prettier & plugins work...

I am trying to get this to work in a Svelte (+TS) setup, and it seems to run fine if I run the pnpm run format script across all files, but the plugin is not running on save with formatOnSave enabled in VSCode.

Is there something I need to set to enable plugins when running within VSCode formatOnSave?
Or is it because the formatOnSave uses the Prettier extension, so doesn't see the project installed plugin and would only work if a Tailwind Prettier extension appeared?

VSCode settings.json
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"

Current set up...
.prettierrc

{
	"useTabs": true,
	"trailingComma": "none",
	"semi": true,
	"printWidth": 100,
	"tailwindConfig": "./tailwind.config.cjs"
}

tailwind.config.cjs in the root of application (same as .prettierrc)

module.exports = {
	content: ["./src/**/*.{html,js,svelte,ts}"],
	theme: {
		extend: {}
	},
	plugins: []
};

.vscode/settings.json

{
	"[svelte]": {
		"editor.formatOnSave": true,
		"editor.defaultFormatter": "svelte.svelte-vscode"
	}
}

Any guidance would be great!

Co-locate extended theme classes?

I couldn't see if this has been requested before in the closed issues, sorry if this is a duplicate.

I know that custom classes are sorted first, so they are easy to see, which is a great idea.

However when the tailwind.config.js has its theme extended, e.g. extra spacing values to extend w-, or extra color values to extend bg-, text-, would it be possible to retain the sort order for those?

e.g. with the existing w-96 the order would be

grid w-96 grid-cols-4 gap-2

if I extend spacing to add a 100: '25rem' the order is

w-100 grid grid-cols-4 gap-2

probably a better example is below, considering some red text with other utility classes:

mb-3 w-full rounded border-2 border-dashed py-5 px-3 text-center text-sm text-red-600

replacing with a custom theme color error you then get

text-error mb-3 w-full rounded border-2 border-dashed py-5 px-3 text-center text-sm

which feels worse because the text- utility classes are no longer co-located.

I know it is a custom class technically, but it seems completely different to the example given in the docs of select2-dropdown; its still in the TailwindCSS ecosystem.

bg-* classes before p-* and m-* classes

In the Prettier plugin blog post it says:

The actual order of the different utilities is loosely based on the box model, and tries to put high impact classes that affect the layout at the beginning and decorative classes at the end...

However the Prettier plugin is moving bg-* before padding p-* and margin m-* classes which is not what I would expect.

I would have thought that bg-* classes would fall into the "decorative" camp and should be placed after m-* and p-* classes.

For example:

// before (expected)
<div className="p-4 bg-red-500 text-white" />

// after (plugin output)
<div className="bg-red-500 p-4 text-white" />

I don't want to be "that guy" bike shedding over class order, but I have always followed the same order/line of thinking as the blog post above—listing bg-* classes after display, padding and margin classes since they are more presentational/decorative.

Just wanted to see if this was the expected order and if not—is there any chance of moving the bg-* classes after padding and margin classes?

Thanks for your consideration.

Class sorting is not working when arbitrary value is used

Hi,

I noticed that plugin is not sorting classes of the element if there is at least one arbitrary value.

This will not be sorted because of w-[200px] class used

<div className="px-5 w-[200px] py-6 justify-center flex flex-col"></div>

This works:

<div className="px-5 py-6 justify-center flex flex-col"></div>

Could we trim the sides?

// before
<body className=" text-white bg-slate-900   "></body>

// after formatting
<body className=" bg-slate-900 text-white   "></body>

// expected behavior
<body className="bg-slate-900 text-white"></body> // <-- trim

classNames order mismatch between VSCode Prettier extension and `prettier` CLI

Seeing similar errors to #19 & #21 in regards to class names order mismatches... In VS Code with the ESLint extension + Prettier extension, class names are formatted as expected and VSCode doesn't show any errors or warnings. However, when running prettier OR eslint (with prettier plugins) from the command line it's complaining that the classnames are in the wrong order... this is in direct contradiction to the rules described in the blog post, which says custom class names should come first.

// Correct className in editor, no warnings shown...
<div className="wrapper grid h-full grid-cols-12 items-center gap-4">

prettier warning output...

→ npx prettier --check src   
Checking formatting...
[warn] src/components/header.tsx
[warn] Code style issues found in the above file(s). Forgot to run Prettier?

... eslint warning output...

→ npx eslint src         
./src/components/header.tsx
  6:23  error  Replace `wrapper·grid·h-full·grid-cols-12·items-center·gap-4` with `grid·h-full·grid-cols-12·items-center·gap-4·wrapper`  prettier/prettier

As you can see, it wants to put wrapper at the end for some reason.

Here's my eslint config:

{
  "plugins": ["prettier"],
  "extends": ["next/core-web-vitals", "plugin:prettier/recommended"],
  "overrides": [
    {
      "files": ["**/*.ts?(x)"],
      "plugins": ["@typescript-eslint"],
      "extends": "plugin:@typescript-eslint/recommended",
    }
  ]
}

And relevant packages...

    "@typescript-eslint/eslint-plugin": "^5.10.2",
    "autoprefixer": "^10.4.2",
    "eslint": "8.8.0",
    "eslint-config-next": "12.0.10",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^4.0.0",
    "postcss": "^8.4.6",
    "prettier": "2.5.1",
    "prettier-plugin-tailwindcss": "^0.1.4",
    "tailwindcss": "^3.0.18",
    "typescript": "4.5.5"

And for what it's worth, here's the very simple plugin for the custom .wrapper class...

    plugin(({ addUtilities, theme }) => {
      const wrapper = theme("wrapper");

      addUtilities({
        ".wrapper": {
          width: "100%",
          maxWidth: wrapper.maxWidth,
          paddingLeft: wrapper.padding,
          paddingRight: wrapper.padding,
          marginLeft: "auto",
          marginRight: "auto",
        },
      });
    })

Incompatible with `@trivago/prettier-plugin-sort-imports`

prettier version: 2.5.1
@trivago/prettier-plugin-sort-imports version: 3.1.1
tailwindcss version: 2.2.17

My .prettierrc.json

{
  "singleQuote": true,
  "jsxSingleQuote": true,
  "importOrder": [
    "<THIRD_PARTY_MODULES>",
    "^@/types$",
    "^@/types/(.*)$",
    "^@/api$",
    "^@/api/(.*)$",
    "^@/config/(.*)$",
    "^@/context/(.*)$",
    "^@/pages/(.*)$",
    "^@/components/(.*)$",
    "^@/hooks/(.*)$",
    "^@/helpers/(.*)$",
    "^@/images/(.*)$",
    "^@/locales/(.*)$",
    "^[./]",
    "^./tailwind.css$",
    "^.*.css$"
  ],
  "importOrderSeparation": true,
  "importOrderCaseInsensitive": false,
  "tailwindConfig": "./tailwind.config.js"
}

Only import sorting works

Handling multiple TW configs (e.g. monorepo)

I've noticed you can specify the config path in case the Tailwind config file isn't placed in the same directory. This also seems to work out-of-the-box in a monorepo where I'm receiving comments about my TWCSS config file (confirmation of the file being found?). Probably this is based on one of my TW configs (the class sorting, too), but I don't know which file it picked. Would it be possible to optionally specify the configs as array to apply them to subfolders? Running Prettier on every subfolder individually may be extensive. An interface could look like this:

// prettier.config.js
module.exports = {
  tailwindConfig: [
    { directory: "./project1", config: "./project1/tailwind.config.js" } // applies the project's own config
    { directory: "./project2", config: "./project3/tailwind.config.js" } // applies a different project's config
  ]
}

This kind of configuration level could become very helpful if Prettier runs globally on a repo with one or many TWCSS configs. Even without this feature, it would be awesome to log by default which of the available TW files has been auto-detected (for debugging purposes). This helps with understanding which config the feedback while running prettier applies to.

Error when running with Jest & toMatchInlineSnapshot: Cannot read properties of undefined (reading 'filepath')

I'm running into this issue while running Jest v27.4.7:

    TypeError: Cannot read properties of undefined (reading 'filepath')

      at Object.parse (node_modules/prettier-plugin-tailwindcss/dist/index.js:145:1735)
      at Object.parse$d [as parse] (node_modules/prettier/index.js:12975:19)
      at coreFormat (node_modules/prettier/index.js:14525:16)
      at formatWithCursor$1 (node_modules/prettier/index.js:14765:14)
      at node_modules/prettier/index.js:60959:12
      at Object.format (node_modules/prettier/index.js:60979:12)

This seems to happen when Jest tries to write out an inline snapshot:

test('a test', () => {
  // In this case, the inline snapshot has not been written yet. When running tests with
  // Jest, it fails with the error above and the inline snapshot is never written.
  expect('abc').toMatchInlineSnapshot()
})

Support formatting template literals inside functions (@netlify/classnames-template-literals)

Describe your issue

Hello! we are using https://github.com/netlify/classnames-template-literals to keep a high number of classes sanitized and legible e.g.

import ctl from "@netlify/classnames-template-literals";

export const searchBarWrapper = ctl(`
  mt-2 
  mx-4
  p-4 
  border-b 
  border-gray-300
`);

Any chance that we could support the plugin to also sort the classes inside these functions?

What version of prettier-plugin-tailwindcss are you using?
Latest

What version of Tailwind CSS are you using?
Latest

What version of Node.js are you using?
v14.0.0

What package manager are you using?
Yarn

What operating system are you using?
macOS

Feature request: remove unnecessary spaces from class list

Hi,

I was using Headwind vscode plugin before (https://marketplace.visualstudio.com/items?itemName=heybourn.headwind) and this plugin was also removing unnecessary characters from class list like spaces and new lines.

It would be really useful if this plugin would do the same:

Expected behaviour:

 <div className="mb-2 flex   flex-col   p-2 text-3xl        font-medium text-slate-700 shadow   " />

This should be changed to:

 <div className="mb-2 flex flex-col p-2 text-3xl font-medium text-slate-700 shadow" />

Make compatible with twin.macro

First off, thanks for putting this plugin out there! I think it's awesome.

It would be fantastic if this had the ability to work with twin.macro. That is how we are using tailwind in our project but this plugin doesn't seem to work with it.

It would be perfect if we can pass in a custom regex to apply the formatting to, just like how twin.macro is configured to work with the official Tailwind VSCode plugin. ben-rogerson/twin.macro#227

Bug: Not working via pnpm

As the title says when installing the dependency using the pnpm add -D prettier-plugin-tailwindcss command and then running pnpm prettier --write, these new rules are not taken into account. I tried deleting the node_modules folder, to reinstall everything and it didn't work either.

After this, I deleted the node_modules folder again to install using yarn, thinking that it is the package manager and when I executed the command it did apply the new order rules in all the corresponding files. I don't know what this is due to or if it has to do with the way pnpm handles packages.

My current prettier version is 2.5.1 and the prettier-plugin-tailwindcss is the latest (0.1.3).

Error: Cannot find module 'prettier-plugin-tailwindcss'

Hi.

I installed the plugin with npm i -D prettier-plugin-tailwindcss. I can find it now in my package.json and in the node_modules folder. I have the following versions:

"prettier": "2.5.1",
"prettier-plugin-tailwindcss": "0.1.8",
"eslint-config-prettier": "8.1.0",

I added the plugin to .prettierrc like this:

{
  "singleQuote": true,
	"plugins": ["prettier-plugin-tailwindcss"]
}

After that I get an error with prettier: Error: Cannot find module 'prettier-plugin-tailwindcss'
Formatting files is then not possible anymore.
When I hover the "dependencies" in the package.json I can see the following error (just when the plugin is installed):

Dependencies are specified with a simple hash of package name to version range. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or git URL.
Module '__ngcc_entry_points__.json' is extraneousnpm

.vue file support ?

The plugin is sorting within .html, .tsx files, but unfortunately not within .vue files.

Not Compatible With Nuxt 3

Can not install it on my Nuxt 3 Project.

My Dependencies:

"devDependencies": {
    "@typescript-eslint/eslint-plugin": "^5.10.0",
    "@typescript-eslint/parser": "^5.10.0",
    "autoprefixer": "^10.4.2",
    "eslint": "^8.7.0",
    "nuxt3": "latest",
    "postcss": "^8.4.5",
    "tailwindcss": "^3.0.15"
  },
  "dependencies": {
    "@nuxtjs/composition-api": "^0.31.0",
    "@pinia/nuxt": "^0.1.8",
    "eslint-plugin-nuxt": "^3.1.0",
    "pinia": "^2.0.9",
    "sass": "^1.49.0"
  }

Error I get

image

Not working as expected with ESLint with formatOnSave

This is a great plugin, congrats!

Prettier is saving a different order from ESLint:

Screen Shot 2022-02-03 at 20 30 29

Screen Shot 2022-02-03 at 20 30 43

My prettier.config.cjs:

/**
 * @type {import('prettier').Options}
 */
const prettierConfig = {
  plugins: [require('prettier-plugin-tailwindcss')],
  semi: false,
  singleQuote: true,
  jsxSingleQuote: false,
  tailwindConfig: './tailwind.config.cjs',
}

module.exports = prettierConfig

And, my .eslintrc.cjs:

const eslintRC = {
  extends: [
    'next/core-web-vitals',
    'plugin:tailwindcss/recommended',
    'plugin:storybook/recommended',
    'prettier',
  ],
  plugins: ['tailwindcss'],
}

module.exports = eslintRC

And, my .vscode/settings.json:

{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "tailwindCSS.includeLanguages": {
    "typescript": "javascript",
    "typescriptreact": "javascript"
  }
}

Incompatible with `prettier-plugin-twig-melody`

Hello,

Regarding this part of the README.

This means this plugin is incompatible with other Prettier plugins that are using the same APIs.
...
If you discover any other incompatibilities, open an issue and hopefully we can figure out a way to make it work.

This plugin does not work with *.twig files, with prettier-plugin-twig-melody

prettier version: 2.5.1
prettier-plugin-twig-melody version: 0.4.6
tailwindcss version: 2.2.19

My .prettierrc.js

module.exports = {
  bracketSpacing: true,
  printWidth: 100,
  semi: true,
  singleQuote: true,
  tabWidth: 2,
  trailingComma: 'es5',
  useTabs: false,
  vueIndentScriptAndStyle: true,
  htmlWhitespaceSensitivity: 'ignore',
  twigPrintWidth: 100,
  twigMultiTags: ['html_element,end_html_element', 'with,endwith'],
  tailwindConfig: './tailwind.config.js'
};

Only the settings from the twig plugin are applied when running prettier, class names stay in the same order.

To long lines

After i install it, all classes are set up together in a single line, and I used to put each on its own line, or at least group them up and divide them in multiple lines so I can scan them, but now they are all in a single line and I have to word wrap the document so I can see all of them, is there a way to divide them when there are lots of them or when the char length overpass the prettier length?

`group` is sorted before custom classes

I have a html element in a Vue installation.

<div class="group task-group-item relative flex bg-red-500 text-neutral-900"></div>

It places group first, even before my custom class which is task-group-item. The custom class should be placed first according to the rules.

Support for tailwindCSS class matching

So happy about this plugin!

I'm not sure what the best way to make a feature request or contribute back to the project but something that could help tailwind users is if the plugin supported class matching. This would allow support for class sorting for applications using tailwind in all sorts of different ways.

For example a project that i'm on is built on react native (mobile+web) and we use a library called tailwind react native classnames to use tailwind in our app.

For this library instead of using class or className it uses tw and tw.style. One issue we noticed early on was tailwind intellisense support did not work out of the box but by adding it to our tailwindCSS.experimental.classRegex and tailwindCSS.classAttributes in vs code settings file it started to work.

Would a feature like this make sense? I'm not as familiar with writing plugins but can take a try at it if it makes sense and am pointed in the right direction.

Thank you!

Css class sorting changes if formatted on save or by a script

Hello,
With a specific config, the css classes order is different when formatted on save and when formatted by a script.

I made a repo with a minimal reproduction to show the bug: https://github.com/francoisromain/bug-svelte-tailwind

To reproduce the bug, in VS Code:

  • Clone this repo
  • Install the dependencies : npm i
  • Install the required VS Code extensions : svelte.svelte-vscode, dbaeumer.vscode-eslint, esbenp.prettier-vscode and bradlc.vscode-tailwindcss.
  • Open the file src/routes/index.svelte and save the file. The order of the css classes changes.
  • Run npm run format. The order of the css classes changes again.

If we remove the boxShadow property in tailwind.config.cjs, the css order stays the same when formatted on save and by a script.

Prettier places "!important" before actual class

After automatic class sorting was applied, the following code:

.facetwp-facet { @apply mb-0 !important; }

... turned into:

.facetwp-facet { @apply !important mb-0; }

which is causing an error.

Incorrectly ordered text-* classes

What version of prettier-plugin-tailwindcss are you using?

0.1.8 with Prettier 2.6.2

What version of Tailwind CSS are you using?

3.0.24

What version of Node.js are you using?

16.10.0

What package manager are you using?

npm 7.24.0

What operating system are you using?

macOS

Reproduction URL

https://github.com/elliotdavies/prettier-plugin-tailwindcss-example

See src/test.html for examples of actual/expected behaviour. Run npm install and npm run format to see the behaviour.

You can use the included shell.nix or bring your own Node / npm.

Describe your issue

  1. text-* classes such as text-md or text-red are appearing before "layout" classes like m-2. I would expect them to appear afterwards, per https://github.com/tailwindlabs/prettier-plugin-tailwindcss
  2. text-* classes that use colours defined in the TW config file are not being kept together with other text-* classes. For example text-md is being separated from text-bespoke-color (where bespoke-color is defined in the config). I would expect all the text-* classes to be grouped

Will not format classes within Blade files.

I'm using VS Code and I have everything installed as required, format on save is on.

When I save, I get an error on the bottom that says Extension 'Prettier - code formatter' is configured as formatter but can not format 'Blade' files.

I have this in my .prettierrc as noted in another issue, but it's not affecting anything:

{
    "overrides": [
        {
            "files": "*.blade.php",
            "options": {
                "parser": "html"
            }
        }
    ]
}

If I run npx prettier --check resources/views it states everything is formatted properly (which it's not)

Interestingly, if I change a blade file to be a plain HTML file,format on save still does not do anything, but running npx prettier will then find the issues.

What am I doing wrong?

Is there no support for the formatter in blade files within a Laravel project?

Ignore Prettier printWidth

It seems to me that the plugin does not respect the maximum characters per line (set by printWidth).

For example, when printWidth is set to 80 characters, this code :

<a href="#" className="mt-8 bg-white border border-transparent rounded-md shadow px-5 py-3 inline-flex items-center text-base font-medium text-indigo-600 hover:bg-indigo-50">
  A stupidly long text just to illustrate my problem with the number of characters per line. I hope you are having a good day and that all is well in your lives!
</a>

Will be format to :

<a
  href="#"
  className="mt-8 inline-flex items-center rounded-md border border-transparent bg-white px-5 py-3 text-base font-medium text-indigo-600 shadow hover:bg-indigo-50"
>
  A stupidly long text just to illustrate my problem with the number of
  characters per line. I hope you are having a good day and that all is
  well in your lives!
</a>

I'm using "prettier": "^2.5.1", "prettier-plugin-tailwindcss": "^0.1.4", "tailwindcss": "^3.0.18" and VS Code.

Thanks for your help, and all your work on this plugin !

VSCode support for .erb files

It would be great to add documentation on how to configure VSCode to work with templating languages like ruby .erb files.

[v0.1.9] Unwanted removal of leading whitespace for concatenated class

What version of prettier-plugin-tailwindcss are you using?

v0.1.9

What version of Tailwind CSS are you using?

v3.0.24

What version of Node.js are you using?

v16.13.0

What package manager are you using?

npm

What operating system are you using?

Windows

Reproduction URL

https://github.com/bennettdams/tailwind-prettier-whitespace-bug

Describe your issue

Version v0.1.9 introduced a change for frameworks like React that will introduce "bugs".

Here is a basic example. When a class consists of multiple concatenated strings, the plugin now removes the leading whitespace:

function Test() {
-      return <div className={"text-white" + " bg-red-100"} />;
+      return <div className={"text-white" + "bg-red-100"} />;
}

I use this format of concatenated strings for visibility when there are a lot of classes, e.g.:

className={
  'inline-flex items-center' +
  ' rounded-md p-2 shadow-sm focus:outline-none focus:ring-2 focus:ring-purple-600 focus:ring-opacity-50' +
  ' bg-dlila text-white transition duration-75 ease-in-out hover:bg-dorange' +
  ' disabled:cursor-not-allowed disabled:bg-gray-200'
}

width and height sorting order

Hello,

Just checking if there's a reason behind why sorting width and height goes like this: h-... w-... instead of the width before height

Bug: Formatting doesn't work with optional chaining in template code

Formatting is not working with angular templates that use the optional chaining operator.

Vue syntax works

<button :class="{ 'test': a?.b }"> Button</button>

Angular [] syntax causes an error

<button [ngClass]="{ 'test': a?.b }">Button</button>
Error Output
Error: Line 2: Unexpected token .
    at t.constructError (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:99104)
    at t.createError (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:99323)
    at c.h.unexpectedTokenError (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:36571)
    at c.h.throwUnexpectedToken (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:36781)
    at c.h.parsePrimaryExpression (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:43621)
    at c.parsePrimaryExpression (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:42:161117)
    at c.h.inheritCoverGrammar (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:41493)
    at c.h.parseLeftHandSideExpressionAllowCall (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:54138)
    at c.h.inheritCoverGrammar (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:41493)
    at c.h.parseUpdateExpression (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:57007)
    at c.h.parseUnaryExpression (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:58391)
    at c.h.inheritCoverGrammar (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:41493)
    at c.h.parseExponentiationExpression (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:58506)
    at c.h.inheritCoverGrammar (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:41493)
    at c.h.parseBinaryExpression (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:59096)
    at c.h.inheritCoverGrammar (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:41493)
    at c.h.parseConditionalExpression (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:60031)
    at c.h.parseAssignmentExpression (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:62247)
    at c.h.isolateCoverGrammar (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:40952)
    at c.h.parseConditionalExpression (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:60178)
    at c.h.parseAssignmentExpression (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:62247)
    at c.h.inheritCoverGrammar (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:41493)
    at c.h.parseObjectProperty (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:47978)
    at c.h.parseObjectInitializer (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:48678)
    at c.h.inheritCoverGrammar (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:41493)
    at c.h.parsePrimaryExpression (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:43305)
    at c.parsePrimaryExpression (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:42:161117)
    at c.h.inheritCoverGrammar (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:41493)
    at c.h.parseLeftHandSideExpressionAllowCall (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:54138)
    at c.h.inheritCoverGrammar (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:41493)
    at c.h.parseUpdateExpression (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:57007)
    at c.h.parseUnaryExpression (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:58391)
    at c.h.inheritCoverGrammar (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:41493)
    at c.h.parseExponentiationExpression (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:58506)
    at c.h.inheritCoverGrammar (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:41493)
    at c.h.parseBinaryExpression (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:59096)
    at c.h.inheritCoverGrammar (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:41493)
    at c.h.parseConditionalExpression (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:60031)
    at c.h.parseAssignmentExpression (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:62247)
    at c.h.isolateCoverGrammar (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:40952)
    at c.h.parseLexicalBinding (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:66418)
    at c.h.parseBindingList (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:66578)
    at c.h.parseLexicalDeclaration (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:67167)
    at c.h.parseStatementListItem (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:65494)
    at c.h.parseScript (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:43:93668)
    at Object.l [as parse] (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:42:154791)
    at Object.nP [as parse] (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:49:9607)
    at Object.TP (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:58:889)
    at n (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:145:2612)
    at n (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:145:2922)
    at n (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:145:2922)
    at n (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:145:2922)
    at Object.parse (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier-plugin-tailwindcss/dist/index.js:145:2363)
    at Object.parse$d [as parse] (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier/index.js:12975:19)
    at coreFormat (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier/index.js:14525:16)
    at formatWithCursor$1 (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier/index.js:14765:14)
    at /Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier/index.js:60959:12
    at Object.Success [as format] (/Users/[REDACTED]/Sites/[REDACTED]/node_modules/prettier/index.js:60979:12)
    at t.default.<anonymous> (/Users/[REDACTED]/.vscode/extensions/esbenp.prettier-vscode-9.1.0/src/PrettierEditService.ts:435:45)
    at Generator.next (<anonymous>)
    at s (/Users/[REDACTED]/.vscode/extensions/esbenp.prettier-vscode-9.1.0/dist/extension.js:1:7872)

Unit test fail

What version of prettier-plugin-tailwindcss are you using?

For example: v0.1.8

What version of Tailwind CSS are you using?
None

What version of Node.js are you using?

v14.17.5

What package manager are you using?

pnpm, npm

What operating system are you using?

macOS

Reproduction URL

This repo

Describe your issue

I tried to run the unit test of this repo, but the test case for svelte is fail. Look like it's because we can't import the svelte/compiler, but I don't know how to address this problem.

image

Mismatch with Github Action using Prettier

I'm using a Github action to format any code that my team pushes up using prettier. It's incredibly useful but I also have a local instance of Prettier installed via my node package.json and in VScode.

There seems to be a mismatch in how the two versions of prettier handle a custom font class.

VSCode returns this:

<div class="font-inter flex w-full flex-row items-center justify-between"></div>

My github action returns this:

<div class="flex w-full flex-row items-center justify-between font-inter "></div>

Is there any reason for this discrepancy?

Actually, I just realized it is more than just the font classes. There are more classes where whatever ordering the styles aren't in sync. I do have this plugin in my dev dependencies so I t should be getting installed.
Adding the commit log for this to show all the changes: fairdataihub/FAIRshare@d4b3dc6

Error formatting document

Hey there! I'm getting this error in the VS code output console when trying to format a rather large .vue file. (SFC with script setup). I tried a bunch of files and this one isn't formatting properly, all others work super smooth. I can't share the exact file but I can provide some more details if necessary.

prettier version: 2.5.1
prettier-plugin-tailwindcss version: 0.1.3
tailwindcss version: 3.0.16

["ERROR" - 8:15:05 AM] Error formatting document.
TypeError: Cannot read property 'includes' of null
    at Lr (/Users/.../node_modules/prettier-plugin-tailwindcss/dist/index.js:145:943)
    at n (/Users/.../node_modules/prettier-plugin-tailwindcss/dist/index.js:145:2520)
    at n (/Users/.../node_modules/prettier-plugin-tailwindcss/dist/index.js:145:2956)
    at n (/Users/.../node_modules/prettier-plugin-tailwindcss/dist/index.js:145:2956)
    at n (/Users/.../node_modules/prettier-plugin-tailwindcss/dist/index.js:145:2956)
    at n (/Users/.../node_modules/prettier-plugin-tailwindcss/dist/index.js:145:2956)
    at Object.parse (/Users/.../node_modules/prettier-plugin-tailwindcss/dist/index.js:145:2363)
    at Object.parse$d [as parse] (/Users/.../node_modules/prettier/index.js:12975:19)
    at coreFormat (/Users/.../node_modules/prettier/index.js:14525:16)
    at formatWithCursor$1 (/Users/.../node_modules/prettier/index.js:14765:14)
    at /Users/.../node_modules/prettier/index.js:60959:12
    at Object.Success [as format] (/Users/.../node_modules/prettier/index.js:60979:12)
    at t.default.<anonymous> (/Users/.../.vscode/extensions/esbenp.prettier-vscode-9.1.0/src/PrettierEditService.ts:435:45)
    at Generator.next (<anonymous>)
    at s (/Users/.../.vscode/extensions/esbenp.prettier-vscode-9.1.0/dist/extension.js:1:7872)

What is the "recommended class order"?

Hi

First of all, thanks for the plugin! Glad to see Tailwind Labs improving the DX more and more.

The README states:

A Prettier plugin for Tailwind CSS v3.0+ that automatically sorts classes based on our recommended class order.

I could not find this in the Tailwind CSS documentation. Could you please link to it? Or is this documented somewhere else?

Transform/translate property with old tailwind (1.9.6)

What version of prettier-plugin-tailwindcss are you using?

v0.1.10

What version of Tailwind CSS are you using?

v1.9.6

What version of Node.js are you using?

v17.9.0

What package manager are you using?

Yarn

What operating system are you using?

macOS

Describe your issue

Our team is using the old version of tailwind 1.9.6.
I ran into a problem that in the old version the translate property declaration should be paired with transform, but the sort plugin doesn't take this into account and overwrites the property. Is there a way to fix this? Thank you!

image

image

image

image

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.