/
index.ts
85 lines (77 loc) · 2.74 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
import process from 'node:process'
import type { Plugin } from 'vite'
import type { UnocssPluginContext, UserConfigDefaults } from '@unocss/core'
import UnocssInspector from '@unocss/inspector'
import { createContext } from './integration'
import { ChunkModeBuildPlugin } from './modes/chunk-build'
import { GlobalModeDevPlugin, GlobalModePlugin } from './modes/global'
import { PerModuleModePlugin } from './modes/per-module'
import { VueScopedPlugin } from './modes/vue-scoped'
import { ShadowDomModuleModePlugin } from './modes/shadow-dom'
import { ConfigHMRPlugin } from './config-hmr'
import type { VitePluginConfig } from './types'
import { createTransformerPlugins } from './transformers'
import { createDevtoolsPlugin } from './devtool'
export * from './types'
export * from './modes/chunk-build'
export * from './modes/global'
export * from './modes/per-module'
export * from './modes/vue-scoped'
export function defineConfig<Theme extends object>(config: VitePluginConfig<Theme>) {
return config
}
export interface UnocssVitePluginAPI {
getContext(): UnocssPluginContext<VitePluginConfig>
getMode(): VitePluginConfig['mode']
}
export default function UnocssPlugin<Theme extends object>(
configOrPath?: VitePluginConfig<Theme> | string,
defaults: UserConfigDefaults = {},
): Plugin[] {
const ctx = createContext<VitePluginConfig>(configOrPath as any, {
envMode: process.env.NODE_ENV === 'development' ? 'dev' : 'build',
...defaults,
})
const inlineConfig = (configOrPath && typeof configOrPath !== 'string') ? configOrPath : {}
const mode = inlineConfig.mode ?? 'global'
const plugins = [
ConfigHMRPlugin(ctx),
...createTransformerPlugins(ctx),
...createDevtoolsPlugin(ctx),
{
name: 'unocss:api',
api: <UnocssVitePluginAPI>{
getContext: () => ctx,
getMode: () => mode,
},
},
]
if (inlineConfig.inspector !== false)
plugins.push(UnocssInspector(ctx))
if (mode === 'per-module') {
plugins.push(...PerModuleModePlugin(ctx))
}
else if (mode === 'vue-scoped') {
plugins.push(VueScopedPlugin(ctx))
}
// @ts-expect-error alerts users who were already using this mode before it became its own package
else if (mode === 'svelte-scoped') {
throw new Error('[unocss] svelte-scoped mode is now its own package, please use @unocss/svelte-scoped according to the docs')
}
else if (mode === 'shadow-dom') {
plugins.push(ShadowDomModuleModePlugin(ctx))
}
else if (mode === 'global') {
plugins.push(...GlobalModePlugin(ctx))
}
else if (mode === 'dist-chunk') {
plugins.push(
ChunkModeBuildPlugin(ctx),
...GlobalModeDevPlugin(ctx),
)
}
else {
throw new Error(`[unocss] unknown mode "${mode}"`)
}
return plugins.filter(Boolean) as Plugin[]
}