Skip to content

Commit 35c42d0

Browse files
Add examples to serialize apis
1 parent e41fce2 commit 35c42d0

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

README.md

+41
Original file line numberDiff line numberDiff line change
@@ -137,9 +137,50 @@ enableReactOptimization(); // just makes it a but faster
137137
## Serialize API
138138

139139
Use it to separate generation of styles lookup from your runtime.
140+
140141
It is useful in cases, where you can't directly use Discovery APIs on your client CSS bundles during app's runtime, e.g. various serverless runtimes.
141142
Also it may be useful for you, if you want to save on the size of your container for the server app, since it allows you to only load styles lookup into it, without CSS bundles.
142143

144+
1. `serializeStylesLookup(def: StyleDef): SerializedStyleDef` - creates a serializable object from original styles lookup. Result can be then stringified with `JSON.stringify`
145+
2. `loadSerializedLookup(def: SerializedStyleDef): StyleDef` - transforms serialized style definition back to normal `StyleDef`, which can be used with any Scanner API
146+
147+
### Example
148+
149+
#### During your build
150+
151+
1. Add separate script to generate style lookup and store it as you like.
152+
```js
153+
// project/scripts/generate_styles_lookup.mjs
154+
import { serializeStylesLookup, discoverProjectStyles } from 'used-styles'
155+
import { writeFileSync } from 'fs'
156+
157+
const stylesLookup = discoverProjectStyles('./path/to/dist/client');
158+
159+
await stylesLookup;
160+
161+
writeFileSync('./path/to/dist/server/styles-lookup.json', JSON.stringify(serializeStyles(lookup)))
162+
```
163+
2. Run this code after your build
164+
```sh
165+
yarn build
166+
node ./scripts/generate_styles_lookup.mjs
167+
```
168+
169+
Notice, that you can store serialized lookup in any way, that suits you and your case, example above is not the only valid option.
170+
171+
#### During your runtime
172+
173+
1. Access previously created and stored styles lookup, convert it to `StyleDef` with `loadSerializedLookup` and use it normally
174+
```js
175+
import { loadSerializedLookup } from 'used-styles'
176+
177+
const stylesLookup = loadSerializedLookup(require('./dist/server/styles-lookup.json');
178+
179+
// ...
180+
181+
getCriticalStyles(markup, stylesLookup)
182+
```
183+
143184
# Example
144185
145186
## Demo

0 commit comments

Comments
 (0)