Skip to content

Commit ff7e7f2

Browse files
Jack-sh1Jack-sh1zyyv
authored
fix(webpack): persistent cache (#5017)
Co-authored-by: Jack-sh1 <jack.sh1@gmail.com> Co-authored-by: Chris <hizyyv@gmail.com>
1 parent 8930816 commit ff7e7f2

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

packages-integrations/webpack/src/unplugin.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { UserConfigDefaults } from '@unocss/core'
2+
import type { Buffer } from 'node:buffer'
23
import type { ResolvedUnpluginOptions, UnpluginOptions } from 'unplugin'
34
import type { WebpackPluginOptions } from '.'
45
import { isAbsolute, normalize } from 'node:path'
@@ -100,6 +101,43 @@ export function unplugin<Theme extends object>(configOrPath?: WebpackPluginOptio
100101
})
101102
// replace the placeholders
102103
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
104+
// #419
105+
if (compiler.options.cache) {
106+
compilation.hooks.finishModules.tapPromise(PLUGIN_NAME, async (modules) => {
107+
const { RESOLVED_ID_RE } = await ctx.getVMPRegexes()
108+
const promises: Promise<any>[] = []
109+
110+
for (const module of modules) {
111+
const resource = (module as any).resource
112+
if (resource && isCssId(resource))
113+
continue
114+
if (resource && !RESOLVED_ID_RE.test(resource) && filter('', resource)) {
115+
// For Webpack 5 persistent cache, we need to manually read the file content
116+
// if the module is restored from cache, as loaders might be skipped.
117+
promises.push(
118+
(async () => {
119+
if (!compiler.inputFileSystem)
120+
return
121+
122+
const content = await new Promise<string | Buffer | undefined>((resolve, reject) => {
123+
compiler.inputFileSystem!.readFile(resource, (err, data) => {
124+
if (err)
125+
reject(err)
126+
else
127+
resolve(data)
128+
})
129+
}) // let it throw if error
130+
if (content != null)
131+
await ctx.extract(content.toString(), resource)
132+
})(),
133+
)
134+
}
135+
}
136+
137+
await Promise.all(promises)
138+
})
139+
}
140+
103141
const optimizeAssetsHook = compilation.hooks.processAssets /* webpack 5 & 6 */
104142
|| compilation.hooks.optimizeAssets /* webpack 4 */
105143

@@ -108,6 +146,7 @@ export function unplugin<Theme extends object>(configOrPath?: WebpackPluginOptio
108146
const files = Object.keys(compilation.assets)
109147

110148
await flushTasks()
149+
111150
const result = await ctx.uno.generate(tokens, { minify: true })
112151
const resolvedLayers = (await Promise.all(Array.from(entries)
113152
.map(i => resolveLayer(ctx, i))))

0 commit comments

Comments
 (0)