Style to Object Parser

1.0.14 · active · verified Sun Apr 19

style-to-object is a focused JavaScript library designed to parse CSS inline style strings into a plain JavaScript object. The current stable version is 1.0.14, and the package maintains a consistent, frequent release cadence primarily for minor dependency updates and occasional bug fixes within the 1.x series. Its core functionality offers a straightforward API for converting CSS style declarations (e.g., `color: #C0FFEE; background: #BADA55;`) into a corresponding JavaScript object where property names are converted from hyphen-case to camelCase or retained as hyphen-case depending on usage. A key differentiator is its optional iterator function, which allows for custom processing of each parsed declaration, rather than just returning a final object. The library ships with TypeScript types, enhancing developer experience for type-safe applications, and builds its parsing logic on the `inline-style-parser` package.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse CSS inline style strings into JavaScript objects, including basic usage, custom processing with the iterator, and error handling for invalid or malformed input. It shows both the object return and the null return when an iterator is used.

import parse from 'style-to-object';
import type { StyleObject } from 'style-to-object';

/**
 * Parses a CSS style string into a JavaScript object.
 * Handles potential parsing errors and demonstrates iterator usage.
 */
function processStyleString(styleString: string): StyleObject | null {
  try {
    // Basic usage: parse a string to an object
    const parsedStyle = parse(styleString);
    console.log(`Parsed style for "${styleString}":`, parsedStyle);
    return parsedStyle;
  } catch (error: any) {
    console.error(`Error parsing style "${styleString}":`, error.message);
    return null;
  }
}

// Example 1: Basic conversion
processStyleString('color: #C0FFEE; background: #BADA55;');
// Expected output: { color: '#C0FFEE', background: '#BADA55' }

// Example 2: Using the iterator for custom processing
const customOutput: [string, string][] = [];
const iteratorResult = parse('font-size: 16px; margin: 10px;', (name, value) => {
  customOutput.push([name, value]);
});
console.log('Custom iterated output:', customOutput);
console.log('Result when using iterator (always null):', iteratorResult);
// Expected output: [['font-size', '16px'], ['margin', '10px']], null

// Example 3: Handling invalid input that returns null
processStyleString('top:');

// Example 4: Handling malformed input that throws an error
processStyleString('top');

view raw JSON →