1
Watch
0
Star
0
Fork
0
Issue

css to javascript-object converter

moatorres
moatorres
pushedAt 9 months ago

moatorres/cssobject

CSS to JavaScript-Object

Convert CSS rules to JavaScript style objects

This repo is a fork from the archived css-to-object with minor updates and improvements.

Installation

This repo also available as a package and can be installed with NPM and Yarn.

NPM
npm install @moatorres/cssobject
Yarn
yarn add @moatorres/cssobject

Usage

import toObj from '@moatorres/cssobject'

const options = {
  kebabCase: true,
  camelCase: false,
  numbers: true,
}

const style = toObj(
  `
  .button {
    color: tomato;
    padding: 16px;
    @media (min-width: 40em) {
      paddingLeft: 32px;
      paddingRight: 32px;
    }
    &:hover {
      color: black;
    }
    & h1 {
      font-size: 48px;
    }
  }
`,
  options
)

console.log(style)

Prints

const style = {
  '.button': { color: 'tomato', padding: 16 },
  '@media (min-width: 40em)': {
    '.button': { 'padding-left': 32, 'padding-right': 32 },
  },
  '.button:hover': { color: 'black' },
  '.button h1': { 'font-size': 48 },
}

Options

  • numbers converts px values to numbers
  • camelCase converts CSS properties to camelCased keys
  • kebabCase converts CSS properties to 'kebab-cased' keys

Tests

------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------|---------|----------|---------|---------|-------------------
All files   |   95.35 |    77.78 |     100 |   97.22 |
 helpers.js |     100 |      100 |     100 |     100 |
 index.js   |   94.12 |    71.43 |     100 |   96.55 | 31
------------|---------|----------|---------|---------|-------------------

🔖 License

ucloud ads