callstack / linaria

Zero-runtime CSS in JS library
https://linaria.dev
MIT License
11.51k stars 414 forks source link

how to control when styles are compiled #122

Closed jmjpro closed 6 years ago

jmjpro commented 6 years ago

Do you want to request a feature or report a bug? feature/question

What is the current behavior? When I build my JSX at runtime styles aren't compiled. I get html output of

<div class="{names(AppStyled)}">
    hello
  </div>

from the scenario below.

If the current behavior is a bug, please provide the steps to reproduce and a minimal repository on GitHub that we can yarn install and yarn test. index.js

import * as React from 'react'
import * as ReactDOMServer from 'react-dom/server'
import { collect } from 'linaria/server'

import App from './app'

const html = ReactDOMServer.renderToString(React.createElement(App))
const { critical, other } = collect(html, '')

app.jsx

import { css, names } from 'linaria';
import { Parser as Html2ReactParser } from 'html-to-react'

import appTemplate from './app_template'

const AppStyled = css`
  font-weight: bold;
`;

const html2ReactParser = new Html2ReactParser()
const jsx = html2ReactParser.parse(appTemplate)
/*
const jsx = (
  <div className={names(AppStyled)}>
      hello
  </div>
)
*/

export default () => {
  console.log(jsx)
  return jsx
}

app_template.js

export default`
  <div className={names(AppStyled)}>
    hello
  </div>
`

What is the expected behavior? I'm using html-to-react to compile a string to JSX at runtime. When I build my JSX at runtime I would like styles to compiled to get html output like this:

<div class="AppStyled__186e3ly" data-reactroot="">hello</div>

Is there a way I can achieve this by calling invoking the linaria babel plugin programmatically?

Please provide your exact Babel configuration and mention your Linaria, Node, Yarn/npm version and operating system.

. babelrc

{
  "presets": [
    "env",
    "react",
    "es2015",
    ["linaria/babel", {
      "single": true,
      "filename": "styles.css",
      "outDir": "dist"
    }]
  ]
}

node version 8.5.0 yarn version 1.1.0 linaria version ^0.0.2-alpha.0

zamotany commented 6 years ago

@jmjpro are you sure this app_template.js is correct? To me, it looks like html2ReactParser.parse doesn't resolve the expression names(AppStyled).

Can you try this:

__app_template.js__:

export default (AppStyledClassName) => `
  <div className="${AppStyledClassName}">
    hello
  </div>
`

app.jsx:

import { css, names } from 'linaria';
import { Parser as Html2ReactParser } from 'html-to-react'

import appTemplate from './app_template'

const AppStyled = css`
  font-weight: bold;
`;

const html2ReactParser = new Html2ReactParser()
const jsx = html2ReactParser.parse(appTemplate(names(AppStyled)))

export default () => {
  console.log(jsx)
  return jsx
}
zamotany commented 6 years ago

Closing due to inactivity.