Styled-components: What is the purpose of using tagged template literals in `styled-components`?

Created on 20 Apr 2017  路  1Comment  路  Source: styled-components/styled-components

The tag functions are implemented as

  const styled = (tag: Target) =>
    (strings: Array<string>, ...interpolations: Array<Interpolation>) =>
      styledComponent(tag, css(strings, ...interpolations))

  // Shorthands for all valid HTML Elements
  domElements.forEach(domElement => {
    styled[domElement] = styled(domElement)
  })

and css is simply

export default (strings: Array<string>, ...interpolations: Array<Interpolation>): RuleSet => (
  flatten(interleave(strings, interpolations))
)

and interleave simply joins the strings and interpolations.

So, why instead of tagged literals

styled.button`...`

not use functions

styled.button(`...`)

It would save some CPU cycles and memory.

Or am I missing something important?

Most helpful comment

Interleaving is actually not a huge performance hog, and it totally disappears when you enable preprocessing (experimental in v2).

We're using tagged template literals for an improved API. We receive all interpolations and can manipulate them in a more sophisticated manner, than just toString-ing everything.

For example this wouldn't be possible without tagged template literals:

const mixin = css`...`

styled.div`
  /* this function would just be toString()'d */
  background: ${p => p.color || 'white'};

  /* this mixin wouldn't be flattened into the rest of the rules */
  ${mixin}
`

Max has an excellent article explaining the details behind tagged template literals btw: http://mxstbr.blog/2016/11/styled-components-magic-explained/

>All comments

Interleaving is actually not a huge performance hog, and it totally disappears when you enable preprocessing (experimental in v2).

We're using tagged template literals for an improved API. We receive all interpolations and can manipulate them in a more sophisticated manner, than just toString-ing everything.

For example this wouldn't be possible without tagged template literals:

const mixin = css`...`

styled.div`
  /* this function would just be toString()'d */
  background: ${p => p.color || 'white'};

  /* this mixin wouldn't be flattened into the rest of the rules */
  ${mixin}
`

Max has an excellent article explaining the details behind tagged template literals btw: http://mxstbr.blog/2016/11/styled-components-magic-explained/

Was this page helpful?
0 / 5 - 0 ratings