style-to-object
Parses inline style to object:
var parser = require('style-to-object');
parser('color: #C0FFEE; background: #BADA55;');
Output:
{ color: '#C0FFEE', background: '#BADA55' }
JSFiddle | Repl.it | Examples
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>
window.StyleToObject();
</script>
Usage
Import the module:
const parse = require('style-to-object');
import parse from 'style-to-object';
Parse single declaration:
parse('line-height: 42');
Output:
{ 'line-height': '42' }
Parse multiple declarations:
parse(`
border-color: #ACE;
z-index: 1337;
`);
Output:
{ 'border-color': '#ACE', 'z-index': '1337' }
Parse unknown declarations:
parse('answer: 42;');
Output:
{ 'answer': '42' }
Invalid declarations/arguments:
parse(`
top: ;
right: 1em;
`);
parse();
parse(null);
parse(1);
parse(true);
parse('top:');
parse(':12px');
parse(':');
parse(';');
parse('top');
parse('/*');
Iterator
If the 2nd argument is a function, then the parser will return null
:
parse('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: red;
background: blue;
`;
const output = [];
function iterator(name, value) {
output.push([name, value]);
}
parse(style, iterator);
console.log(output);
Testing
Run tests:
$ npm test
Run tests in watch mode:
$ npm run test:watch
Run tests with coverage:
$ npm run test:coverage
Lint files:
$ npm run lint
Fix lint errors:
$ npm run lint:fix
Release
Only collaborators with credentials can release and publish:
$ npm run release
$ git push --follow-tags && npm publish
Special Thanks
License
MIT