Skip to content

Commit c5a5fcc

Browse files
authoredMar 9, 2023
fix(cache): imporove cache performance and resolve cache mistake (#344)
1 parent c41e526 commit c5a5fcc

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed
 

‎src/core/ctx.ts

+11-9
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ ${dts}`.trim()}\n`
9797
}
9898

9999
const writeConfigFilesThrottled = throttle(500, writeConfigFiles, { noLeading: false })
100+
const writeFileThrottled = throttle(500, writeFile, { noLeading: false })
100101

101102
async function writeFile(filePath: string, content = '') {
102103
await fs.mkdir(dirname(filePath), { recursive: true })
@@ -151,12 +152,13 @@ ${dts}`.trim()}\n`
151152
return JSON.parse(str || '{}') as { [key: string]: Import[] }
152153
}
153154

154-
async function generateCache() {
155+
async function generateCache(): Promise<Record<string, Import[]>> {
155156
if (!cachePath)
156-
return
157+
return {}
157158

159+
let cacheData = {}
158160
try {
159-
const cacheData = await getCacheData(cachePath)
161+
cacheData = await getCacheData(cachePath)
160162
await Promise.allSettled(Object.keys(cacheData).map(async (filePath) => {
161163
try {
162164
const normalizeRoot = root.replaceAll(sep, posix.sep)
@@ -171,6 +173,8 @@ ${dts}`.trim()}\n`
171173
catch {
172174
await writeFile(cachePath, '{}')
173175
}
176+
177+
return cacheData
174178
}
175179

176180
let isInitialCache = false
@@ -180,18 +184,16 @@ ${dts}`.trim()}\n`
180184
return
181185

182186
isInitialCache = true
183-
await resolveCachePromise
187+
const cacheData = await resolveCachePromise
184188
await unimport.modifyDynamicImports(async (imports) => {
185-
const cacheData = await getCacheData(cachePath)
186-
187189
if (id && importList) {
188190
const filePath = posix.normalize(posix.relative(root, id))
189191
importList = importList.filter(i => (i.name ?? i.as) && i.name !== 'default')
190192
if (importList.length)
191193
cacheData[filePath] = importList
192194
else
193195
delete cacheData[filePath]
194-
await writeFile(cachePath, JSON.stringify(cacheData, null, 2))
196+
writeFileThrottled(cachePath, JSON.stringify(cacheData, null, 2))
195197
return imports.concat(importList)
196198
}
197199

@@ -206,11 +208,11 @@ ${dts}`.trim()}\n`
206208

207209
const res = await unimport.injectImports(s, id)
208210

211+
await updateCacheImports(id, res.imports)
212+
209213
if (!s.hasChanged())
210214
return
211215

212-
await updateCacheImports(id, res.imports)
213-
214216
writeConfigFilesThrottled()
215217

216218
return {

0 commit comments

Comments
 (0)
Please sign in to comment.