Skip to content

Babel transform #59

Closed
Closed

Description

@mxstbr

We need a way (probably babel transform?) to extract and precompile the static styles of our components!

Extracting static styles is actually not what we want, we want to pre-parse the CSS in a build step but leave it in the JS: See this comment

Has anybody done this before? I know I haven't…

Activity

  1. tizmagik commented on Oct 13, 2016

    @tizmagik
    Contributor

    Take a look at CSJS, similar template strings construct and has a pipeline to statically extract styles

  2. mxstbr commented on Oct 13, 2016

    @mxstbr
    MemberAuthor
  3. oliviertassinari commented on Oct 13, 2016

    @oliviertassinari
    Contributor

    I'm curious about the motivation behind. Shouldn't we aim for the opposite?

    What I mean is, injecting as small bits of CSS as possible in the document in order to:

    • reduce network usage when inlining CSS for SSR
    • reduce bootstrap JS execution
    • reduce cache invalidation with code splitting
    • reduce bootstrap browser CSSDOM processing

    Does it scale up?

  4. geelen commented on Oct 13, 2016

    @geelen
    Member

    @oliviertassinari the reason is that once certain styles are defined they can never change. Some component X will always have some chunk of styles applied. So we can basically parse over the files and extract that into a static mapping, which is effectively all a CSS file is anyway :)

    If you're doing SSR, you might prefer not to do this, but if you have a fairly common set of components across the entire site it could be better to extract all those into a static, separately-cached CSS file. But not everyone is doing SSR.

    As for bootstrap JS & CSSDOM parsing, serving raw CSS is always going to be faster than serving JS, executing it and dynamically injecting styles. Browsers have been optimising their CSS parsing since... CSS became a thing. So I'd like to make use of as much of that as is possible.

  5. ndelangen commented on Oct 13, 2016

    @ndelangen

    With the content of the stylesheet classes changing between renders (because they are based on props) how is this going to work?

    Whatever CSS is extracted, is only for the initial state? Looking at how it works it seems each different render wich results in a different style output will also result in a new classname..
    I don't see an easy way of pre-generating all possible classes.

    take this style:

    styled.button`
      background: ${(props) => props.theme.main || 'palevioletred'};
      border: ${(props) => (props.width || 2) + 'px'} solid ${(props) => props.theme.main || 'palevioletred'};
    `;
    

    Potentially props.width could be any Integer, resulting in infinite classes to generate?

    As @tizmagik pointed out, CSJS seems rather similar and also support interpolation inside the template strings, so might deal with the same issue?

    I'm trying to understand how this might work, would love to contribute in some way.

  6. DrewML commented on Oct 13, 2016

    @DrewML

    This is probably possible to do with the static portions of styles, but, as mentioned by @ndelangen, I'm not sure there is a way to handle anything that uses ${} inside the template.

    I'm wondering if Babel may not be the best tool for the job either way? Few problems I can see with that:

    1. Babel transforms run per-file. So, to share style information (so you can get 1 final stylesheet across all JS files), you'd need to write to a tmp file along the way. This would probably become a major problem when you introduce incremental compilation (Babel's watch mode, for example).
    2. Where would the file be written? Since you're not running inside a module bundler, you'd likely have to have your transform accept config in .babelrc, and then just dump to some file the user then includes in their bundler.

    My suspicion is that something like this might be much better suited for Webpack + Browserify plugins. I believe you'd be able to solve both 1 and 2 above.

  7. geelen commented on Oct 13, 2016

    @geelen
    Member

    I think extracting just the static portion of styles is enough to start with. @DrewML you might be right we might need something more build-tool-specific like a Webpack/Browserify plugin to actually do something with the output css, but as a first step I'd like to transform a single file and extract the css, and so babel seems like the obvious choice, right?

  8. DrewML commented on Oct 13, 2016

    @DrewML

    as a first step I'd like to transform a single file and extract the css, and so babel seems like the obvious choice, right?

    Yep, definitely. I went to go mock up an example for y'all before I left my comment, but then I realized I had been using JSCodeShift instead of Babel 😛 - whoops!. Having said that, definitely possible to update the template literal to only have the dynamic bits.

    Knowing nothing about this project (besides that it looks awesome), what would be your suggested approach, while extracting the static styles, to get a dynamic classname onto that component. Need something once those styles are ripped out to associate them with the component.

  9. SeeThruHead commented on Oct 14, 2016

    @SeeThruHead

    I've been thinking about content addressable css rules which could be useful here. Each rule that is identified as being static could be output to a stylesheet with a classname that directly maps to the rule contents itself, then you apply that classname to the component. This is nice because you could write the same style rules all over the place and they would only ever end up in the extracted css once. Implementation wise you could build up a { classname: ruleContent } hash and just set every rule, then parse the object into actual css using one of the many tools for that on npm.

  10. geelen commented on Oct 14, 2016

    @geelen
    Member

    Yep these are the lines that currently do that logic:

    const hash = hashStr(flatCSS)
    if (!inserted[hash]) {
    const selector = nameGenerator(hash)
    inserted[hash] = selector
    const root = parse(`.${selector} { ${flatCSS} }`)
    postcssNested(root)
    autoprefix(root)

    Then we'd just need an API to get that on to the class at runtime, but that should be easy enough.

  11. geelen commented on Oct 14, 2016

    @geelen
    Member

    @SeeThruHead yeah I've wanted to do that!! But I decided we had to strictly preserve the ordering of definitions. If you have two conflicting rules on an element then using content-addressable css means the one defined later would apply. So you'd need to resolve all the conflicts per component, then only inject the CSS classnames that "win". So I gave up 😄

    This was actually issue #1 on this repo, and we've gone through a few iterations to make sure that the CSS you get is in the same order as the Styled Components you write. But if we could resolve things ahead of time it would make the output pretty amazing. And the extracted CSS would be super minimal.

    If you're up for trying, let me know! I can throw you all the edge-cases that stumped me 😜

  12. DrewML commented on Oct 14, 2016

    @DrewML

    Here is a not-so-pretty example of a Babel plugin that gets the static pieces (it's not removing them from the source for this example). Comes fully-loaded with a million edge-cases, but it gives you a starting point. Open console to see output.

    http://astexplorer.net/#/Zlh1EM2eE7/1

  13. geelen commented on Oct 14, 2016

    @geelen
    Member

    😍 this is an excellent start!

    I think it's safe to assume that if a line has a ${} on it it can be treated as dynamic, yeah.

  14. 52 remaining items

  15. kitten commented on Mar 12, 2017

    @kitten
    Member

    @jacobp100 sorry, it's getting hard for me to sift through the github notifications. I consider the preprocessor as done for a first version. Of course there needs to be more testing involved, but I haven't completed the part of this work on styled-components itself. I really need to get onto that ;)

    @thysultan this is only for preprocessing it, like Jacob said. However, it should make splitting static and dynamic styles really easy, in the future.

  16. reopened this on Mar 12, 2017
  17. jacobp100 commented on Mar 13, 2017

    @jacobp100
    Contributor

    No worries! Let me know if I can help in any way!

  18. kitten commented on Mar 13, 2017

    @kitten
    Member

    @jacobi pinged you on gitter. Since I haven't done anything on implementing the preprocessed css in a while, we could definitely divvy it up, if you want

  19. kitten commented on Mar 14, 2017

    @kitten
    Member

    I've started from scratch on the 'v2-preprocessed' branch. It looks like I'm actually going to be done with it soon. Maybe today even? Who knows ;)

  20. kitten commented on Mar 25, 2017

    @kitten
    Member

    Released experimental CSS preprocessing with babel-plugin-styled-componenrs v1.1.0 and styled-components v2.0.0-9

  21. garmjs commented on Mar 26, 2017

    @garmjs

    @philpl how can we try it now

  22. kitten commented on Mar 26, 2017

    @kitten
    Member

    @garmjs Get the latest styled-components v2 prerelease and use the babel plugin with the preprocess option turned on ;) https://github.com/styled-components/babel-plugin-styled-components

  23. wmertens commented on Mar 27, 2017

    @wmertens
    Contributor

    @philpl I have styled-components 2.0.0-10 and the plugin 1.1.1, turning on preprocess complains that it can't find the no-parser export…

  24. wmertens commented on Mar 27, 2017

    @wmertens
    Contributor

    Oops, PEBCAK. Disregard, I had 2.0.0-4, was reading the output of yarn wrongly.

  25. WilliamDugdale commented on Jun 8, 2017

    @WilliamDugdale

    Hi all,
    I'm grappling with SSR and subsequent client-side connecting, and was wondering if someone here could help me - I suspect I'm missing some very important and obvious point.
    State-wise, all is well, but using style-components seems to mean that SSR HTML is immediately being updated solely because the client side 'processor' is generating a different sc-tag from the server side on component render. Am I trying to use the wrong tool for the job, or am I missing an important point?
    Thanks in advance - I'm keen to get this up and running; component-scoped style seems like a very sensible idea to me!
    Will

  26. kitten commented on Jun 14, 2017

    @kitten
    Member

    @WilliamDugdale please create a new issue and we'll help you. This issue is unrelated :)

  27. locked and limited conversation to collaborators on Jun 14, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions