menu

emotion

Emotion is a css-in-js library focused on performance and developer experience

Channels
# All channels
view-forward
# General
view-forward
# Development
view-forward
# Help
view-forward
# Off Topic
view-forward
Team

Emotion with AMP pages

May 20, 2019 at 9:43am

Emotion with AMP pages

May 20, 2019 at 9:43am
I am researching using emotion with AMP pages. When styling AMP pages you need to have you styles inside a style tag with amp-custom attribute and you can only have one style tag in the DOM (AFAIU). So I need to configure emotion to only generate one style tag and I also need to add the amp-custom attribute to it. Has anyone done this before? Do you think it is possible?

October 21, 2019 at 3:34pm
hey, ive just had to do this :)
the extractCritical function from emotion-server doesnt pull the styles out in emotion 10
something like this validates for me:
// match style tags from html (AMP error if style tags in body)
let styleTagRegex = new RegExp(/<style.*?>(.*?)<\/style>/)
// match source maps in css (AMP error if style tag too large)
let cssCommentRegex = new RegExp(/\/\*(.*?)\*\//, 'g')
function matchStyleTag(html: string) {
return styleTagRegex.exec(html)
}
function extractAmpStyles(html: string): { html: string css: string } {
let match: RegExpMatchArray | null
let css: string = ''
// tslint:disable-next-line: no-conditional-assignment
while ((match = matchStyleTag(html))) {
html = html.replace(match[0], '')
css += match[1]
}
return { html, css: css.replace(cssCommentRegex, '') }
}
function renderAmp(_, res) {
const jsx = <App/>
const { html, css } = renderToString(jsx)
res.write(`
<!doctype html>
<html ⚡>
<head>
<style amp-custom>${css}</style>
</head>
<body>
<div id="#app">${html}</div>
</body>
</html>
`)
}
  • reply
  • like

December 13, 2019 at 2:30pm
the emotion documentation for this seems to have been updated recently: https://emotion.sh/docs/ssr#advanced-approach I’ve just implemented this in a Next.js project and it works pretty well.
like-fill
1
  • reply
  • like