|
1 | | -import { defineNitroPlugin, defineEventHandler, useStorage, getRouterParam, setHeader, readBody } from '#imports' |
| 1 | +import { defineNitroPlugin, defineEventHandler, useStorage, getRouterParam, setHeader } from '#imports' |
| 2 | +import optimiseCss from '#style-extractor/nuxt-style-extractor-transform.js' |
2 | 3 |
|
3 | 4 | export default defineNitroPlugin((nitroApp) => { |
| 5 | + const nameReg = /data-style-extractor-name="(.*?)"/ |
| 6 | + const styleReg = /<style[^>]*>([\s\S]*?)<\/style>/ |
4 | 7 | const cacheStorage = useStorage<string>('cache:_css') |
5 | 8 | const assetsStorage = useStorage<string>('assets:_css') |
6 | 9 |
|
7 | | - nitroApp.router.add('/_css/:name', defineEventHandler(async (event) => { |
| 10 | + nitroApp.router.get('/_css/:name', defineEventHandler(async (event) => { |
8 | 11 | const name = getRouterParam(event, 'name') |
9 | 12 | let css = await cacheStorage.getItem(name!) |
10 | 13 | setHeader(event, 'Content-Type', 'text/css') |
11 | 14 | if (!css) { |
12 | 15 | css = await assetsStorage.getItem(name!) |
13 | 16 | } |
| 17 | + |
14 | 18 | return css |
15 | 19 | })) |
16 | 20 |
|
17 | | - nitroApp.router.post('/_css', defineEventHandler(async (event) => { |
18 | | - const body = await readBody<{ name: string, css: string }>(event) |
19 | | - const { name, css } = body |
| 21 | + nitroApp.hooks.hook('render:response', async (res) => { |
| 22 | + const html: string = res.body |
| 23 | + const [_, name] = html.match(nameReg) || [] |
| 24 | + if (!name) { |
| 25 | + return |
| 26 | + } |
| 27 | + const storage = import.meta.prerender ? assetsStorage : cacheStorage |
| 28 | + const item = await storage.getItem(name) |
20 | 29 |
|
21 | | - await Promise.all([ |
22 | | - cacheStorage.setItem(name, css), |
23 | | - assetsStorage.setItem(name, css), |
24 | | - ]) |
25 | | - })) |
| 30 | + if (item === null) { |
| 31 | + const [style, css] = html.match(styleReg) || [''] |
| 32 | + |
| 33 | + const newCss = await optimiseCss({ |
| 34 | + html, |
| 35 | + css, |
| 36 | + name, |
| 37 | + }) |
| 38 | + await storage.setItem(name, newCss || '') |
| 39 | + if (css) { |
| 40 | + res.body = html.replace(style, `<link href="/_css/${name}" rel="stylesheet" />`) |
| 41 | + } |
| 42 | + return |
| 43 | + } |
| 44 | + if (item) { |
| 45 | + res.body = html.replace(styleReg, `<link href="/_css/${name}" rel="stylesheet" />`) |
| 46 | + } |
| 47 | + }) |
26 | 48 | }) |
0 commit comments