Sub topic 13
Tagged Templates in the Ecosystem: styled-components, lit, graphql-tag
This chapter assumes you already know how a tag receives its strings array and values, that tags can return any value, and that each call site gets one frozen strings array. Here you will see how three popular libraries build on those facts.
The Common Shape
Each of these libraries uses a tag to embed a small language inside JavaScript. That embedded language is a DSL, or domain-specific language. The language might be CSS, HTML, or GraphQL. The library treats the static parts as trusted source code written by the developer. It treats the values as data, or as hooks that get filled in later.
styled-components: Values That Are Functions
In styled-components, styled.button is a member tag. Interpolations are often functions of the component's props. The tag doesn't call them right away. It keeps them and calls them again on each render. This small version shows the idea:
function css(strings, ...values) {
return (props) =>
strings.reduce((out, str, i) => {
const v = values[i - 1];
return out + (typeof v === 'function' ? v(props) : v) + str;
});
}
const button = css`
color: ${(p) => (p.primary ? 'white' : 'black')};
padding: ${8}px;
`;
console.log(button({ primary: true })); // color: white; padding: 8px;
console.log(button({ primary: false })); // color: black; padding: 8px;The tag returns a function, not a string. This is the "tags can return anything" idea applied to styling.
lit: The Strings Array as a Cache Key
lit's html tag has to turn markup into a DOM template, and that is expensive. Every call from the same source location gets the same frozen strings array. Because of this, lit parses the markup once per call site. On later renders it only updates the parts that hold values.
const templateCache = new WeakMap();
function html(strings, ...values) {
let template = templateCache.get(strings);
if (!template) {
template = strings.join('<!--slot-->'); // real lit builds a <template> here
templateCache.set(strings, template);
console.log('parsed');
}
return { template, values };
}
const item = (n) => html`<li>${n}</li>`;
item(1); // logs 'parsed'
item(2); // no log: cache hitA WeakMap fits here because its keys are objects, and an entry can be garbage-collected once its template is no longer reachable.
graphql-tag: Parsing to an AST
The gql tag parses its text into a GraphQL document AST, which is a tree of plain objects. Apollo and other clients consume this tree. Interpolations are usually other gql fragments, and the tag merges them in.
import gql from 'graphql-tag';
const USER = gql`
query User($id: ID!) {
user(id: $id) { name }
}
`;
console.log(USER.kind); // 'Document'Variables such as $id belong to GraphQL itself. You pass them at request time. You don't interpolate them into the template, which is the same separation the SQL tag in an earlier chapter used.
Comparison
| Library | Tag | Returns | Key technique |
|---|---|---|---|
| styled-components | `styled.div`, `css` | React component or style rule | Function values resolved per render |
| lit | `html` | `TemplateResult` | Per-call-site cache keyed by `strings` |
| graphql-tag | `gql` | GraphQL document AST | Parse to a tree, merge fragment values |
Exercise
In the lit-style example, why does calling item(1) and then item(2) log "parsed" only once, and what would happen if you replaced the WeakMap key with strings.join('')?
Show answer
Both calls come from the same call site, so they get the identical frozen strings array, and the WeakMap lookup succeeds on the second call. Keying by the joined string would still hit the cache, but every call would have to build a new string just to do the lookup. The key would also be a string, which a WeakMap rejects, so you would need a Map, and entries would never be garbage-collected.
Exercise
A styled-components interpolation is written as ${props.color} instead of ${(p) => p.color}. What goes wrong?
Show answer
The expression is evaluated once, when the template is defined. At that point props doesn't exist in scope, so you get a ReferenceError (or a fixed value if a variable named props happens to exist). Passing a function lets the library call it later with each render's props.