martinandert / babel-plugin-css-in-js

A plugin for Babel v6 which transforms inline styles defined in JavaScript modules into class names so they become available to, e.g. the `className` prop of React elements. While transforming, the plugin processes all JavaScript style definitions found and bundles them up into a CSS file, ready to be requested from your web server.
MIT License
299 stars 11 forks source link

feature request: support template literal #22

Open Pyrolistical opened 7 years ago

Pyrolistical commented 7 years ago

I love inline-css, but I don't like the mental gymnastics I need to do to convert css into a js object.

Could we add template literal support to allow us to write more vanilla css?

for example we could convert this:

const styles =  cssInJs({
  myButton: {
    border: 'solid 1px #ccc',
    backgroundColor: 'lightgray',

    ':hover': {
      borderColor: '#ddd',

      ':active': {
        borderColor: '#eee'
      }
    },

    '[disabled]': {
      opacity: .5,
    }
  },

  '@media only screen and (max-width: 480px)': {
    myButton: {
      borderWidth: 0
    }
  }
})

to

const styles =  cssInJs(`
  .myButton {
    border: solid 1px #ccc
    background-color: lightgray

    &:hover {
      border-color: #ddd

      &:active {
        border-color: #eee
      }
    }

    &[disabled] {
      opacity: .5
    }

    @media only screen and (max-width: 480px) {
      border-width: 0
    }
  }
`)

the output would be the same

const styles = {
  myButton: 'example_js_styles_button'
}
adamseckel commented 7 years ago

👍

Pyrolistical commented 7 years ago

babel does some silly things with tagged template literals, going to simplify and try to just add support for string literal instead

Pyrolistical commented 7 years ago

added proof of concept with passing unit test: https://github.com/Pyrolistical/babel-plugin-css-in-js/tree/string-literal-poc

  it('works with template literal as argument', () => {
    const css = testTransformed({
      from: 'var styles = cssInJS(`.foo { margin-top: -10px }`);',
      to:   'var styles = { foo: "test-styles-foo" };'
    });

    testStyleRule(css, 'test-styles-foo', 'margin-top: -10');
  });
martinandert commented 7 years ago

Hi @Pyrolistical, nice work! Could you please provide a proper PR that I can merge? Also please add a few lines to the README explaining the new feature. Thanks!