/
index.ts
171 lines (152 loc) · 5.8 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import type { UserConfig, UserConfigDefaults } from '@unocss/core'
import type { ResolvedUnpluginOptions, UnpluginOptions } from 'unplugin'
import { createUnplugin } from 'unplugin'
import WebpackSources from 'webpack-sources'
import { createContext } from '../../shared-integration/src/context'
import { getHash } from '../../shared-integration/src/hash'
import { HASH_PLACEHOLDER_RE, LAYER_MARK_ALL, LAYER_PLACEHOLDER_RE, getHashPlaceholder, getLayerPlaceholder, resolveId, resolveLayer } from '../../shared-integration/src/layers'
import { applyTransformers } from '../../shared-integration/src/transformers'
import { getPath, isCssId } from '../../shared-integration/src/utils'
export interface WebpackPluginOptions<Theme extends {} = {}> extends UserConfig<Theme> {}
const PLUGIN_NAME = 'unocss:webpack'
const UPDATE_DEBOUNCE = 10
export function defineConfig<Theme extends {}>(config: WebpackPluginOptions<Theme>) {
return config
}
export default function WebpackPlugin<Theme extends {}>(
configOrPath?: WebpackPluginOptions<Theme> | string,
defaults?: UserConfigDefaults,
) {
return createUnplugin(() => {
const ctx = createContext<WebpackPluginOptions>(configOrPath as any, defaults)
const { uno, tokens, filter, extract, onInvalidate } = ctx
let timer: any
onInvalidate(() => {
clearTimeout(timer)
timer = setTimeout(updateModules, UPDATE_DEBOUNCE)
})
const nonPreTransformers = ctx.uno.config.transformers?.filter(i => i.enforce !== 'pre')
if (nonPreTransformers?.length) {
console.warn(
// eslint-disable-next-line prefer-template
'[unocss] webpack integration only supports "pre" enforce transformers currently.'
+ 'the following transformers will be ignored\n'
+ nonPreTransformers.map(i => ` - ${i.name}`).join('\n'),
)
}
const tasks: Promise<any>[] = []
const entries = new Set<string>()
const hashes = new Map<string, string>()
const plugin = <UnpluginOptions>{
name: 'unocss:webpack',
enforce: 'pre',
transformInclude(id) {
return filter('', id) && !id.match(/\.html$/)
},
async transform(code, id) {
const result = await applyTransformers(ctx, code, id, 'pre')
if (isCssId(id))
return result
if (result == null)
tasks.push(extract(code, id))
else
tasks.push(extract(result.code, id))
return result
},
resolveId(id) {
const entry = resolveId(id)
if (entry === id)
return
if (entry) {
let query = ''
const queryIndex = id.indexOf('?')
if (queryIndex >= 0)
query = id.slice(queryIndex)
entries.add(entry)
// preserve the input query
return entry + query
}
},
loadInclude(id) {
const layer = getLayer(id)
return !!layer
},
// serve the placeholders in virtual module
load(id) {
const layer = getLayer(id)
const hash = hashes.get(id)
if (layer)
return (hash ? getHashPlaceholder(hash) : '') + getLayerPlaceholder(layer)
},
webpack(compiler) {
// replace the placeholders
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.optimizeAssets.tapPromise(PLUGIN_NAME, async () => {
const files = Object.keys(compilation.assets)
await Promise.all(tasks)
const result = await uno.generate(tokens, { minify: true })
for (const file of files) {
// https://github.com/unocss/unocss/pull/1428
if (file === '*')
return
let code = compilation.assets[file].source().toString()
let replaced = false
code = code.replace(HASH_PLACEHOLDER_RE, '')
code = code.replace(LAYER_PLACEHOLDER_RE, (_, quote, layer) => {
replaced = true
const css = layer === LAYER_MARK_ALL
? result.getLayers(undefined, Array.from(entries)
.map(i => resolveLayer(i)).filter((i): i is string => !!i))
: result.getLayer(layer) || ''
if (!quote)
return css
// the css is in a js file, escaping
let escaped = JSON.stringify(css).slice(1, -1)
// in `eval()`, escaping twice
if (quote === '\\"')
escaped = JSON.stringify(escaped).slice(1, -1)
return quote + escaped
})
if (replaced)
compilation.assets[file] = new WebpackSources.RawSource(code) as any
}
})
})
},
} as Required<ResolvedUnpluginOptions>
let lastTokenSize = tokens.size
async function updateModules() {
if (!plugin.__vfsModules)
return
await Promise.all(tasks)
const result = await uno.generate(tokens)
if (lastTokenSize === tokens.size)
return
lastTokenSize = tokens.size
Array.from(plugin.__vfsModules)
.forEach((id) => {
const path = id.slice(plugin.__virtualModulePrefix.length).replace(/\\/g, '/')
const layer = resolveLayer(path)
if (!layer)
return
const code = layer === LAYER_MARK_ALL
? result.getLayers(undefined, Array.from(entries)
.map(i => resolveLayer(i)).filter((i): i is string => !!i))
: result.getLayer(layer) || ''
const hash = getHash(code)
hashes.set(path, hash)
plugin.__vfs.writeModule(id, code)
})
}
return plugin
}).webpack()
}
function getLayer(id: string) {
let layer = resolveLayer(getPath(id))
if (!layer) {
const entry = resolveId(id)
if (entry)
layer = resolveLayer(entry)
}
return layer
}