What is style-to-object?
The style-to-object npm package is used to convert inline CSS style strings into JavaScript objects. This can be particularly useful when working with React or other JavaScript frameworks that expect style information to be provided as objects rather than strings.
What are style-to-object's main functionalities?
Convert CSS string to JavaScript object
This feature allows you to convert a CSS style string into a JavaScript object. The keys of the object are camelCased versions of the CSS property names, and the values are the corresponding CSS values as strings.
const styleToObject = require('style-to-object');
const styleString = 'color: red; font-size: 14px;';
const styleObject = styleToObject(styleString);
console.log(styleObject);
Other packages similar to style-to-object
css-to-object
Similar to style-to-object, css-to-object converts CSS strings into JavaScript objects. The main difference may lie in the API, performance, or additional features provided by the package.
parse-css
This package is designed to parse CSS strings and may offer more comprehensive parsing capabilities, including selectors and media queries, which goes beyond the inline style conversion provided by style-to-object.
style-parser
style-parser is another package that can parse inline style strings into objects. It might offer different parsing options or handle edge cases differently compared to style-to-object.
style-to-object
Parses inline style to object:
var parser = require('style-to-object');
parser('color: #C0FFEE; background: #BADA55;');
JSFiddle
Installation
NPM:
npm install style-to-object --save
Yarn:
yarn add style-to-object
CDN:
<script src="https://unpkg.com/style-to-object@latest/dist/style-to-object.min.js"></script>
<script>
var parser = window.StyleToObject;
</script>
Usage
Import the module:
const parser = require('style-to-object');
import parser from 'style-to-object';
Parse single declaration:
parse(`
color: #f00
`);
Parse multiple declarations:
parse(`
color: #f00;
z-index: 42;
`);
Parse unknown declarations:
parse(`
foo: bar;
`);
Invalid declarations:
parse(1);
parse('top:');
parse(`
top: ;
right: 1em;
`);
parse('top');
Iterator
If the 2nd argument is a function, then the parser will return null
:
parser('color: #f00', function() {});
But the function will iterate through each declaration:
parser('color: #f00', function(name, value, declaration) {
console.log(name);
console.log(value);
console.log(declaration);
});
This makes it easy to customize the output:
const style = `
color: #f00;
background: #ba4;
`;
const output = [];
const iterator = (name, value) => {
output.push([name, value]);
};
parser(style, iterator);
console.log(output);
Testing
$ npm test
$ npm run lint
Release
$ npm run release
$ npm publish
$ git push --follow-tags
Special Thanks
License
MIT