7

GitHub - alexnault/classix: 🏛️ The fastest and tiniest utility for conditionally...

 2 years ago
source link: https://github.com/alexnault/classix
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Banner

classix

The fastest and tiniest utility for conditionally joining classNames.

Installation

npm install classix

Usage

Use any amount of string expressions and classix will join them like so:

import cx from "classix";
// or
import { cx } from "classix";

cx("class1", "class2");
// => "class1 class2"

cx("class1 class2", "class3", "class4 class5");
// => "class1 class2 class3 class4 class5"

cx("class1", true && "class2");
// => "class1 class2"

cx(false && "class1", "class2");
// => "class2"

cx(true ? "class1" : "class2");
// => "class1"

cx("class1", false ? "class2" : "class3");
// => "class1 class3"

cx(...["class1", "class2", "class3"]);
// => class1 class2 class3

cx(
  "flex",
  isPrimary ? "bg-primary-100" : "bg-secondary-100",
  isLarge ? "m-4 p-4" : "m-2 p-2"
);
// => "flex bg-primary-100 m-2 p-2" *assuming isPrimary is true and isLarge is false

classix considers string expressions faster to type and easier to reason about (conditions first, followed by classNames) than the alternative:

// 🚫
clsx({ "class-1": isPrimary });
// ✅
cx(isPrimary && "class-1");

// 🚫
clsx({ "class-1": isPrimary && isLarge, "class-2": !isPrimary || !isLarge });
// ✅
cx(isPrimary && isLarge ? "class-1" : "class-2");

This reasoning enables classix to simplify its API by allowing only string expressions as arguments. Not only does it provide a consistent way of joining classNames, but using classix also leads to better performance and a smaller bundle size for your application.

Comparison

Size comparison chart

Sources: classix, clsx, classnames

Performance comparison chart

Sources: Ran benchmark on an AMD Ryzen 5 5600x.

Highlights

  • Supports all major browsers
  • Supports all versions of Node.js
  • Works with both ES Modules and CommonJS
  • Zero dependencies
  • Fully typed with TypeScript
  • Fully tested
  • Semver compliant

Changelog

For a list of changes and releases, see the changelog.

Contributing

Found a bug, have a question or looking to improve classix? Open an issue, start a discussion or submit a PR!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK