alexeiaccio / split-classnames

Split long className attributes in jsx files

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool


Splits long className attributes to make them more readable



Subscribe to my Newsletter if you want to get notified about other cool projects and updates.

Example

The following code

function Component() {
    return (
        <Fragment>
            <p className='block w-full py-2 mt-8 text-sm font-semibold text-center text-white bg-gray-900 border border-black rounded-md hover:bg-gray-700 disabled:bg-gray-900 hover:cursor-pointer disabled:opacity-60' />
        </Fragment>
    )
}

becomes

import clsx from 'classnames'
function Component() {
    return (
        <Fragment>
            <p
                className={clsx(
                    'block w-full py-2 mt-8 text-sm font-semibold text-center',
                    'text-white bg-gray-900 border border-black rounded-md',
                    'disabled:bg-gray-900 hover:cursor-pointer',
                    'disabled:opacity-60',
                    'hover:bg-gray-700',
                )}
            />
        </Fragment>
    )
}

Usage as a cli

npm i -g split-classnames
# split classnames on all js files in the src directory
split-classnames --dry --max 30 'src/**'

Usage as an eslint plugin

Install the plugin:

npm i -D eslint-plugin-split-classnames

Add the plugin to your eslint config:

// .eslintrc.json
{
    "plugins": ["split-classnames"],
    "rules": {
        "split-classnames/split-classnames": [
            "error",
            {
                "maxClassNameCharacters": 40,
                "functionName": "classnames"
            }
        ]
    }
}

Then run eslint with --fix to split long classnames

eslint --fix ./src

Features

  • Works bot on typescript and javascript jsx
  • Works on string literals (className='something')
  • Works on template literals (className={something ${anotherClass}})
  • Works on existing classnames calls (className={clsx('very long classNames are slitted in groups')})
  • Sorts the classes for tailwind (variants like sm: and lg: are put last)

About

Split long className attributes in jsx files


Languages

Language:TypeScript 86.1%Language:CSS 9.5%Language:JavaScript 4.3%Language:Shell 0.0%