Last active
September 22, 2021 17:29
-
-
Save tkh44/0c4c75c386f2162f23c37b8acbbb7005 to your computer and use it in GitHub Desktop.
Simple SSR template library with scoped styles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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