postcss / postcss-js

PostCSS for React Inline Styles, Free Style and other CSS-in-JS
MIT License
657 stars 25 forks source link

nest at-rules, pseudo classes and elements #29

Closed giuseppeg closed 6 years ago

giuseppeg commented 6 years ago

I am converting some CSS to CSS-in-JS and, in the majority of the implementations, at rules, pseudo classes and elements are nested e.g.

.root {
  color: red;
}
@media screen and (min-width: 5em) {
  .root {
     color: green;
  }
}

becomes:

{
  root: {
    color: red,
    '@media screen and (min-width: 5em)': {
      color: 'green',
    },
  },
}

Right now postcss-js produces non nested rules instead and I understand why.

Would you be open to add an option to transform to nested? or do you think that this should be done in user land?

I figured I'd ask you since 1) you are more familar with the postcss-js codebase and probably could implement this quickly 2) if I need to implement this for myself and you think that it'd be nice to have this feature then I could contribute to postcss-js

ai commented 6 years ago

You need to call postcss-nested after postcss.parse() and before postcssJs.objectify().

postcss-js is just a parser. All transformation must be done by PostCSS plugins.

giuseppeg commented 6 years ago

Wait I don't want nesting. I want things to be grouped by selector like in the example above. I don't think that postcss-nested can do that, but obviously I could write a plugin for it, if that's what you mean.

ai commented 6 years ago

Oh, you need a reverse postcss-nested 😅

In this case you need write own PostCSS plugin https://github.com/postcss/postcss/blob/master/docs/writing-a-plugin.md

BTW, this PostCSS plugin (which you can write) will work not only with postcss-js. It will work with any PostCSS sources (including postcss-js) and will be very useful for community.

giuseppeg commented 6 years ago

@ai sorry to bother you. How does this look https://astexplorer.net/#/gist/1630828e8587b051b15d723f117aa216/bb6fed289190dcd360a39ddf433f327e7d3e776c ?

It seems that if use that output postcss-js' objectify can produce the output I want

giuseppeg commented 6 years ago

https://github.com/giuseppeg/postcss-nest-atrules it would be great if you could take a look and review it at some point