oklchtohex
v0.8.1
Published
Convert OKLCH colors to HEX as a JavaScript package.
Downloads
2,023
Maintainers
Readme
oklchtohex
oklchtohex converts oklch(...) color values to HEX in emitted CSS.
It provides:
- A Vite plugin (
oklchtohex/vite) - A Next.js webpack wrapper (
oklchtohex/next) - An Astro integration (
oklchtohex/astro) - Direct converter utilities (
oklchtohexoroklchtohex/converter)
Install
npm i -D oklchtohexQuick Start
Vite
import { defineConfig } from "vite";
import { oklchToHexVitePlugin } from "oklchtohex/vite";
export default defineConfig({
plugins: [oklchToHexVitePlugin()]
});Astro
// astro.config.mjs
import { defineConfig } from "astro/config";
import { oklchToHexAstro } from "oklchtohex/astro";
export default defineConfig({
integrations: [oklchToHexAstro()]
});Next.js (CJS)
const { withOklchToHexNext } = require("oklchtohex/next");
module.exports = withOklchToHexNext({
// your next config
});Next.js (ESM)
import { withOklchToHexNext } from "oklchtohex/next";
export default withOklchToHexNext({
// your next config
});JavaScript API
import {
parseOklch,
oklchToHex,
replaceOklchInText,
convertTailwindCssToHex
} from "oklchtohex";
parseOklch("oklch(50% 0 0 / 60%)");
// => { l: 0.5, c: 0, h: 0, alpha: 0.6 }
oklchToHex("oklch(0 0 0)");
// => #000000
replaceOklchInText(".btn{color:oklch(0 0 0 / 50%)}");
// => .btn{color:#00000080}
convertTailwindCssToHex(":root{--x:oklch(1 0 0)}");
// => :root{--x:#ffffff}Use oklchtohex/converter if you only want converter functions.
Options
These options are accepted by converter functions and plugin integrations unless marked otherwise.
| Option | Type | Default | Notes |
| --- | --- | --- | --- |
| gamut | "clip" \| "fit" | "clip" | "clip" clamps channels, "fit" reduces chroma to fit sRGB. |
| includeAlpha | "auto" \| "always" \| "never" \| boolean | "auto" | "auto" adds alpha only when < 1. |
| uppercase | boolean | false | Outputs uppercase HEX. |
| onError | "preserve" \| "throw" | "preserve" | "preserve" keeps original token on parse/convert failure. |
| convertDev | boolean | true | Vite, Next & Astro. Disable conversion in dev mode. |
| convertBuild | boolean | true | Vite, Next & Astro. Disable conversion in build mode. |
| include | RegExp \| (id: string) => boolean | /\.(css\|pcss\|postcss\|scss\|sass\|less\|styl\|stylus)(?:$\|\?)/i | Vite & Astro. File filter. |
| exclude | RegExp \| (id: string) => boolean | undefined | Vite & Astro. Skip filter. |
Tailwind-Specific Handling
replaceOklchInText also supports common Tailwind CSS output patterns:
- Replaces known default palette variables like
--color-red-500with mapped HEX. - Converts
color-mix(in oklab, var(--color-... ) N%, transparent)into HEX with alpha. - Handles slash opacity output such as
border-red-500/30when emitted through CSS variables.
Compatibility
- Node.js
>=18 - Next.js integration is webpack-based and processes emitted
.cssassets - Astro integration uses the Vite plugin under the hood via
astro:config:setup
