-
-
Notifications
You must be signed in to change notification settings - Fork 779
/
index.ts
110 lines (98 loc) · 2.9 KB
/
index.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { AstroIntegration } from 'astro'
import type { VitePluginConfig } from '@unocss/vite'
import VitePlugin from '@unocss/vite'
import type { UserConfigDefaults } from '@unocss/core'
import type { Plugin } from 'vite'
const UNO_INJECT_ID = 'uno-astro'
const UNO_QUERY_KEY = 'uno-with-astro-key'
interface AstroVitePluginOptions {
injects: string[]
}
function AstroVitePlugin(options: AstroVitePluginOptions): Plugin {
const { injects } = options
return {
name: 'unocss:astro',
apply: 'serve',
enforce: 'pre',
resolveId(id, importer) {
if (id === UNO_INJECT_ID)
return id
if (importer?.endsWith(UNO_INJECT_ID))
return `${id}${id.includes('?') ? '&' : '?'}${UNO_QUERY_KEY}`
},
load(id, options) {
if (id.endsWith(UNO_INJECT_ID))
return injects.join('\n')
if (
!options?.ssr
&& id.includes(UNO_QUERY_KEY)
&& id.includes('.css')
)
return ''
},
}
}
export interface AstroIntegrationConfig<Theme extends {} = {}> extends VitePluginConfig<Theme> {
/**
* Include reset styles
* When passing `true`, `@unocss/reset/tailwind.css` will be used
* @default false
*/
injectReset?: string | boolean
/**
* Inject UnoCSS entry import for every astro page
* @default true
*/
injectEntry?: boolean | string
/**
* Inject extra imports for every astro page
* @default []
*/
injectExtra?: string[]
}
export default function UnoCSSAstroIntegration<Theme extends {}>(
options: AstroIntegrationConfig<Theme> = {},
defaults?: UserConfigDefaults,
): AstroIntegration {
const {
injectEntry = true,
injectReset = false,
injectExtra = [],
} = options
return {
name: 'unocss',
hooks: {
'astro:config:setup': async ({ config, updateConfig, injectScript }) => {
// Adding components to UnoCSS's extra content
options.extraContent ||= {}
options.extraContent.filesystem ||= []
options.extraContent.filesystem.push(resolve(fileURLToPath(config.srcDir), 'components/**/*').replace(/\\/g, '/'))
const injects: string[] = []
if (injectReset) {
const resetPath = typeof injectReset === 'string'
? injectReset
: '@unocss/reset/tailwind.css'
injects.push(`import "${resetPath}"`)
}
if (injectEntry) {
injects.push(typeof injectEntry === 'string'
? injectEntry
: 'import "uno.css"')
}
if (injectExtra.length > 0)
injects.push(...injectExtra)
updateConfig({
vite: {
plugins: [AstroVitePlugin({
injects,
}), ...VitePlugin(options, defaults)],
},
})
if (injects?.length)
injectScript('page-ssr', `import ${JSON.stringify(UNO_INJECT_ID)}`)
},
},
}
}