-
Notifications
You must be signed in to change notification settings - Fork 18
feat(svg): adds sprite hash manifest for cache busting #471
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 6 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
4ee0928
feat(svg): adds sprite hash manifest for cache busting
firestar300 f1042f0
feat(Svg): add cache system
firestar300 d341e94
feat(Svg): add query args
firestar300 811aa1f
fix(Svg): phpcs issue
firestar300 729e0d5
feat(Svg): allow width and height attributes to Svg elements
firestar300 2d10d9c
feat(webpack-svg-sprite-hashes): add returnFormat option to output ph…
firestar300 97a49f8
fix(Svg): psalm issue
firestar300 847082c
refactor(svg): remove json return format
firestar300 ce82a75
Potential fix for code scanning alert no. 5: Incomplete string escapi…
firestar300 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| const fs = require('fs') | ||
| const path = require('path') | ||
| const crypto = require('crypto') | ||
|
|
||
| const ALLOWED_RETURN_FORMATS = ['json', 'php'] | ||
|
|
||
| /** | ||
| * Webpack plugin to generate content hashes for SVG sprite files. | ||
| * Creates a sprite-hashes.json (or sprite-hashes.asset.php) file in the dist folder. | ||
| * | ||
| * @param {Object} options Plugin options. | ||
| * @param {string} [options.returnFormat='json'] Output format: 'json' or 'php'. | ||
| * When 'php', generates a .asset.php file (outputFilename .json → .asset.php). | ||
| * @param {string} [options.outputPath='dist'] Output directory. | ||
| * @param {string} [options.spritePath='dist/icons'] Sprite SVG directory. | ||
| * @param {string} [options.outputFilename='sprite-hashes.json'] Output file name. | ||
| * @param {number} [options.hashLength=8] Hash length in characters. | ||
| */ | ||
| class SpriteHashPlugin { | ||
| constructor(options = {}) { | ||
| const returnFormat = options.returnFormat || 'json' | ||
| if (!ALLOWED_RETURN_FORMATS.includes(returnFormat)) { | ||
| throw new Error(`SpriteHashPlugin: returnFormat must be one of ${ALLOWED_RETURN_FORMATS.join(', ')}`) | ||
| } | ||
|
|
||
| this.options = { | ||
| outputPath: options.outputPath || 'dist', | ||
| spritePath: options.spritePath || 'dist/icons', | ||
| outputFilename: options.outputFilename || 'sprite-hashes.' + returnFormat, | ||
| hashLength: options.hashLength || 8, | ||
| returnFormat, | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Formats a plain object as a PHP associative array string. | ||
| * | ||
| * @param {Record<string, string>} obj Key-value pairs. | ||
| * @return {string} PHP array literal. | ||
| */ | ||
| formatPhpArray(obj) { | ||
| const entries = Object.entries(obj).map(([key, value]) => { | ||
| const escapedKey = key.replace(/'/g, "\\'") | ||
| const escapedValue = String(value).replace(/'/g, "\\'") | ||
|
||
| return `\t'${escapedKey}' => '${escapedValue}'` | ||
| }) | ||
| return `array(\n${entries.join(',\n')}\n)` | ||
| } | ||
|
|
||
| apply(compiler) { | ||
| compiler.hooks.afterEmit.tapAsync('SpriteHashPlugin', (compilation, callback) => { | ||
| const spriteDir = path.resolve(compiler.options.context, this.options.spritePath) | ||
| const outputFilename = | ||
| this.options.returnFormat === 'php' | ||
| ? this.options.outputFilename.replace(/\.json$/i, '.asset.php') | ||
| : this.options.outputFilename | ||
| const outputFile = path.resolve(compiler.options.context, this.options.outputPath, outputFilename) | ||
|
|
||
| if (!fs.existsSync(spriteDir)) { | ||
| console.warn(`SpriteHashPlugin: Sprite directory not found: ${spriteDir}`) | ||
| callback() | ||
| return | ||
| } | ||
|
|
||
| const hashes = {} | ||
| const files = fs.readdirSync(spriteDir).filter((file) => file.endsWith('.svg')) | ||
|
|
||
| files.forEach((file) => { | ||
| const filePath = path.join(spriteDir, file) | ||
| const content = fs.readFileSync(filePath) | ||
| const hash = crypto.createHash('md5').update(content).digest('hex').substring(0, this.options.hashLength) | ||
|
|
||
| // Store with relative path as key | ||
| const relativePath = `icons/${file}` | ||
| hashes[relativePath] = hash | ||
| }) | ||
|
|
||
| if (this.options.returnFormat === 'php') { | ||
| const phpLines = [ | ||
| '<?php', | ||
| '/**', | ||
| ' * Sprite file hashes. Generated by SpriteHashPlugin.', | ||
| ' *', | ||
| ' * @return array<string, string> Path => hash.', | ||
| ' */', | ||
| 'return ' + this.formatPhpArray(hashes) + ';', | ||
| '', | ||
| ] | ||
| fs.writeFileSync(outputFile, phpLines.join('\n')) | ||
| } else { | ||
| fs.writeFileSync(outputFile, JSON.stringify(hashes, null, 2)) | ||
| } | ||
| console.log(`SpriteHashPlugin: Generated ${outputFilename} with ${Object.keys(hashes).length} sprites`) | ||
|
|
||
| callback() | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| module.exports = SpriteHashPlugin | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.