aws-samples / react-ssr-lambda

Demo of server side rendering for React application on AWS Lambda
MIT No Attribution
107 stars 24 forks source link

How do you add styles to this implementation? #15

Closed christopher-caldwell closed 2 years ago

christopher-caldwell commented 3 years ago

In the webpack config, css-loader is used, but I haven't been able to actually get styles into the browser. Ideally, CSS modules, but I haven't even gotten a CSS file to the browser without importing it into the head as a string.

rishit5 commented 2 years ago

I am facing the same issue, how exactly did you import the styles? Can you elaborate on the workaround you used and also the correct solution, if you have been able to find it?

christopher-caldwell commented 2 years ago

@rishit5 Hey, sorry I missed this. I ended up using styled-components to inject the CSS into the head. It was a very long and painful process to get it right.

Here's a watered down version

import ReactDOMServer from 'react-dom/server'
import { ServerStyleSheet } from 'styled-components'
import MetaTagsServer from 'react-meta-tags/server'
import { MetaTagsContext } from 'react-meta-tags'

import App from './App'
/**
 * <html lang="en">
  <head>
    <meta charset="utf-8" />
    ... other head tags
    META
    STYLED_COMPONENTS
  </head>
  <body >
    <div id="root"></div>
  </body>
</html>
 */
import { HtmlTemplate } from './html'

export const renderApp = () => {
  const Sheets = new ServerStyleSheet()
  const metaTagsInstance = MetaTagsServer()

  const props = {...}

  const app = ReactDOMServer.renderToStaticMarkup(
    Sheets.collectStyles(
      <MetaTagsContext extract={metaTagsInstance.extract}>
        <App {...props} />
      </MetaTagsContext>,
    ),
  )

  const meta = metaTagsInstance.renderToString()
  const styledComponentsTag = Sheets.getStyleTags()

  const html = HtmlTemplate.replace('<div id="root"></div>', `<div id="root">${app}</div>`)
    .replace('STYLED_COMPONENTS', styledComponentsTag)
    .replace('META', meta)
  Sheets.seal()
  return html
}
roman-boiko commented 2 years ago

Webpack 4 could not do it correctly, I am working on a new sample and will address this issue there.