Skip to content

heap-code/eslint-plugin-sort-attribute-content

Repository files navigation

eslint-plugin-sort-attribute-content

CI npm version Code coverage

An ESLint plugin to sort attribute content in HTML

If you are using Tailwind and only want to lint the classnames, then the eslint-plugin-tailwindcss is probably a better choice.

Installation

First, eslint must be installed:

npm i --save-dev eslint

Then, eslint-plugin-sort-attribute-content can be installed:

npm i --save-dev eslint-plugin-sort-attribute-content

Usage

A parser must be set to use this plugin:

{
  "parser": "@html-eslint/parser"
}

Go to the parsers section to display the list of available parsers.

The plugin can then be activated by adding sort-attribute-content to the plugins property:

{
  "plugins": ["sort-attribute-content"]
}

The rule can be defined as follows:

{
  "rules": {
    "sort-attribute-content/sort-attribute-content": ["error", { "attributes": "class" }]
  }
}

All this configuration can be done on a override section: https://eslint.org/docs/latest/use/configure/configuration-files#how-do-overrides-work

Parsers

The plugin can be used with multiple parsers.

HTML

A regular HTML parser can be used for any HTML files.
The parser @html-eslint/parser should be installed first:

npm i -D @html-eslint/parser

Then set in the configuration file:

{
  "parser": "@html-eslint/parser"
}

Angular

This plugin can be used with the Angular framework.
The parser @angular-eslint/template-parser should be installed first:

npm i -D @angular-eslint/template-parser

Then set in the configuration file:

{
  "parser": "@angular-eslint/template-parser"
}

Note:
It only works for text attributes.

<div class="a b c" [title]="'d e f'"></div>
            ^^^^^

React

This plugin can be used with the React library.
ESLint must first be configured to read React.

How to configure?

Once enabled, it will work on jsx and tsx files.

Do not forget to set the typescript parser for tsx files.

Install:

npm i -D @typescript-eslint/parser

Then set in the configuration file:

{
  "parser": "@typescript-eslint/parser"
}

It might be useful to enable the rule only on these files:

{
  "overrides": [
    {
      "files": ["*.jsx", "*.tsx"],
      "rules": {
        "sort-attribute-content/sort-attribute-content": ["error", { "attributes": "className" }]
      }
    }
  ]
}

Note:
It only works for literal text attributes.

return <div className="a b c" title={title} />
                       ^^^^^

Rules

🔧 Automatically fixable by the --fix CLI option.

Name 🔧
sort-attribute-content 🔧

Releases

See information about breaking changes and release notes here.