Skip to content

Instantly share code, notes, and snippets.

@tkh44
Last active September 22, 2021 17:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkh44/0c4c75c386f2162f23c37b8acbbb7005 to your computer and use it in GitHub Desktop.
Save tkh44/0c4c75c386f2162f23c37b8acbbb7005 to your computer and use it in GitHub Desktop.
Simple SSR template library with scoped styles
const hash = require('@emotion/hash')
const weakMemoize = require('@emotion/weak-memoize')
export function html (strings, ...interpolations) {
return strings.reduce(
(final, str, i) =>
final +
str +
(interpolations[i] === undefined
? ''
: interpolations[i]),
''
)
}
const createScope = weakMemoize(function createScope (fn) {
return `data-scope-${fn.name || '' + hash(fn.toString())}`
})
export function Component(partialFn) {
const scope = createScopeName(partialFn)
return (props) => {
return partialFn(props, scope)
}
}
const { Component, html } = require('./html')
const Name = Component(function Name(props, scope) {
return html`
<style>
.name[${scope}] {
color: blue;
}
</style>
<b class="name" ${scope}>${props.name}</b>
`
}
const responseText = html`
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>${title}</h1>
<p>${content}</p>
${Name({ name })}
<body>
</html>
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment