Style to Object Parser
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
-
Error: Cannot parse input: 'top'
cause The input string provided to `parse` is a malformed CSS declaration, specifically an incomplete property without a corresponding value and semicolon.fixProvide a complete and valid CSS style declaration, for example, change `'top'` to `'top: 0;'`, or implement `try...catch` error handling around calls to `parse`. -
TypeError: (0 , style_to_object_1.default) is not a function
cause In a CommonJS environment, `require('style-to-object')` is being used directly to invoke the parser, but the default export is located under the `.default` property.fixUpdate the CommonJS import statement to `const parse = require('style-to-object').default;` to correctly access the default export. -
Property 'parse' does not exist on type 'typeof import("/path/to/node_modules/style-to-object/index")'.cause This TypeScript error occurs when attempting to use a named import for `parse` (e.g., `import { parse } from 'style-to-object';`) when `parse` is actually the default export.fixCorrect the import statement to `import parse from 'style-to-object';` for the default export.
Warnings
- breaking For CommonJS users, the default export now requires accessing the `.default` property (e.g., `require('style-to-object').default`) since version 1.0.0. Direct `require('style-to-object')` will result in a `TypeError`.
- gotcha Providing malformed CSS strings, such as incomplete declarations like `'top'` or unclosed comments like `'/*'`, will cause the `parse` function to throw a synchronous `Error`. It does not gracefully return `null` for these specific malformations.
- gotcha When `parse` is called with a second argument as an iterator function, it will always return `null`, regardless of the input string's validity or the processing done within the callback. The output must be collected directly by the iterator function.
- gotcha Early versions of the 1.x series (specifically <=1.0.4 and <=1.0.10) experienced issues with correctly exporting ESM types, which could lead to TypeScript compilation errors depending on the module resolution settings. These issues were subsequently addressed.
Install
-
npm install style-to-object -
yarn add style-to-object -
pnpm add style-to-object
Imports
- parse
import { parse } from 'style-to-object';import parse from 'style-to-object';
- parse
const parse = require('style-to-object');const parse = require('style-to-object').default; - StyleObject
import { StyleObject } from 'style-to-object';import type { StyleObject } from 'style-to-object';
Quickstart
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');