babel-plugin-jsx-auto-classnames

import xxx from 'classnames'

This plugin is used to automatically add and supplement xxx() to the className property of jsx

NPM version

📦 Install

npm i babel-plugin-jsx-auto-classnames --save-dev

or

pnpm add babel-plugin-jsx-auto-classnames -D

🖥 config

vite-config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import JsxAutoClassnames from 'babel-plugin-jsx-auto-classnames'

export default defineConfig({
  plugins: [react({
    babel: {
      plugins: [JsxAutoClassnames]
    }
  })]
})

.babelrc

{
  "plugins": [
    "jsx-auto-classnames"
  ]
}

🔨 Usage

normal

<div
  className={{
    selected: true
  }}>
</div>

⬇️

import _classNames from 'classnames'
<div
  className={_classNames({
    selected: true
  })}>
</div>

Reuse the alias of the imported package

import xxx from 'classnames'
function App () {
  return (
    <>
      <div
        className={xxx({
          disabled: true
        })}>
      </div>
      <div
        className={{
          selected: true
        }}>
      </div>
    </>
  )
}

⬇️

import xxx from 'classnames'
function App () {
  return (
    <>
      <div
        className={xxx({
          disabled: true
        })}>
      </div>
      <div
        className={xxx({
          selected: true
        })}>
      </div>
    </>
  )
}

TODO

  • Avoid multiple imports of classnames’ dependency packages
  • Find a compatible solution for TS

declare namespace React {
  interface HTMLAttributes<any> extends AriaAttributes, DOMAttributes<any>  {
    className?: Record<string, boolean> | (string | Record<string, boolean>)[]
  }
}
  • Add exclude and include attributes

GitHub

View Github