-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathstyle-inlining.ts
54 lines (48 loc) · 1.68 KB
/
style-inlining.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { addVitePlugin, defineNuxtModule, useNuxt } from '@nuxt/kit'
import purgehtml from 'purgecss-from-html'
import { PurgeCSS } from 'purgecss'
import { dirname, isAbsolute, join, relative } from 'pathe'
export default defineNuxtModule({
meta: {
name: 'style-inlining',
},
setup() {
const nuxt = useNuxt()
let css: string
let cssFilename: string
const inlineStyles = (html: string, css: string, filename: string) => {
const resolvedCSS = css.replace(/(?<=url\()[^)]+(?=\))/g, (url) => {
if (isAbsolute(url)) return url
return './' + relative(dirname(filename.replace(/^\/*/, '')), join(cssFilename, '..', url))
})
return html
.replace(/<\/head>/g, `<style>${resolvedCSS}</style></head>`)
.replace(/<link[^>]+\.css">/g, '')
}
addVitePlugin({
name: 'entry-css',
writeBundle(_options, bundle) {
for (const asset of Object.values(bundle)) {
if (asset.type === 'asset' && asset.fileName.match(/entry.*\.css$/)) {
cssFilename = asset.fileName
css = asset.source.toString()
return
}
}
},
})
nuxt.hook('nitro:init', (nitro) => {
nitro.hooks.hook('prerender:generate', async (route) => {
if (!route.fileName?.endsWith('.html') || !route.contents) return
const [result] = await new PurgeCSS().purge({
content: [{ raw: route.contents, extension: 'html' }],
css: [{ raw: css }],
extractors: [{ extensions: ['html'], extractor: purgehtml }],
})
if (result) {
route.contents = inlineStyles(route.contents, result.css, route.fileName)
}
})
})
},
})