Skip to content

Commit 17492e8

Browse files
committed
feat(webpack): optimize static image processing in watch mode
Improve build performance by skipping image processing when no files in the input directory have changed. The plugin now registers the input directory as a context dependency and checks modified files during subsequent builds to avoid redundant processing.
1 parent 803eb39 commit 17492e8

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

config/webpack-static-images-plugin.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ class WebpackStaticImagesPlugin {
3030
silence: false,
3131
...options,
3232
}
33+
this.hasBeenBuiltOnce = false
3334
}
3435

3536
/**
@@ -49,6 +50,13 @@ class WebpackStaticImagesPlugin {
4950
return
5051
} // If Sharp is not installed, silently cancel.
5152

53+
compiler.hooks.compilation.tap('WebpackStaticImagesPlugin', (compilation) => {
54+
const inputPath = path.resolve(compiler.context, this.options.inputDir)
55+
if (fs.existsSync(inputPath)) {
56+
compilation.contextDependencies.add(inputPath)
57+
}
58+
})
59+
5260
// Use afterEmit to ensure that Webpack has created the dist folder.
5361
compiler.hooks.afterEmit.tapPromise('WebpackStaticImagesPlugin', async (compilation) => {
5462
const { context } = compiler
@@ -61,6 +69,24 @@ class WebpackStaticImagesPlugin {
6169
return
6270
}
6371

72+
// Skip re-processing in watch when nothing under inputDir changed (see WebpackImageSizesPlugin).
73+
let hasChanges = false
74+
if (this.hasBeenBuiltOnce && compilation.modifiedFiles) {
75+
for (const filePath of compilation.modifiedFiles) {
76+
if (this.isFileUnderDir(filePath, inputPath)) {
77+
hasChanges = true
78+
break
79+
}
80+
}
81+
}
82+
83+
if (this.hasBeenBuiltOnce && !hasChanges) {
84+
this.log('log', `✅ No changes detected in ${this.options.inputDir}`)
85+
return
86+
}
87+
88+
this.hasBeenBuiltOnce = true
89+
6490
// Create the output directory if it doesn't exist.
6591
if (!fs.existsSync(outputPath)) {
6692
fs.mkdirSync(outputPath, { recursive: true })
@@ -76,6 +102,19 @@ class WebpackStaticImagesPlugin {
76102
})
77103
}
78104

105+
/**
106+
* Returns true if `filePath` is `inputDir` or a file inside it (cross-platform).
107+
*/
108+
isFileUnderDir(filePath, inputDirResolved) {
109+
const resolvedFile = path.resolve(filePath)
110+
const resolvedDir = path.resolve(inputDirResolved)
111+
if (resolvedFile === resolvedDir) {
112+
return true
113+
}
114+
const relative = path.relative(resolvedDir, resolvedFile)
115+
return !relative.startsWith('..') && !path.isAbsolute(relative)
116+
}
117+
79118
/**
80119
* Processes the images in the directory.
81120
*/

0 commit comments

Comments
 (0)