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
feat: add one-letter-css plugin #1181
Open
denisx
wants to merge
7
commits into
webpack-contrib:master
Choose a base branch
from
denisx:feat/1028-v2
base: master
Could not load branches
Branch not found: {{ refName }}
Could not load tags
Nothing to show
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
bbe543a
feat: add one-letter-css plugin
denisx c742164
fix: add readme for css hash length
denisx d5c9c1d
feat: update scripts; add: tests
denisx c2938f8
fix: tests; fix: memory leak
denisx 1f513e9
fix: describtion
denisx 8185951
Merge branch 'master' into feat/1028-v2
denisx b06b840
Merge branch 'webpack-contrib:master' into feat/1028-v2
denisx File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains 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 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,59 @@ | ||
const PLUGIN_NAME = 'Hash length suggest'; | ||
|
||
export default class HashLenSuggest { | ||
constructor({ instance, selectedHashLen }) { | ||
this.instance = instance; | ||
this.selectedHashLen = selectedHashLen; | ||
this.logger = null; | ||
} | ||
|
||
apply(compiler) { | ||
compiler.plugin('done', this.run); | ||
|
||
this.logger = compiler.getInfrastructureLogger(PLUGIN_NAME); | ||
} | ||
|
||
run() { | ||
let data = this.instance.getStat(); | ||
const matchLen = {}; | ||
const base = {}; | ||
|
||
Object.values(data).forEach(({ name }) => { | ||
for (let len = 1; len <= name.length; len += 1) { | ||
base[len] = base[len] || {}; | ||
const hash = name.substr(0, len); | ||
|
||
if (base[len][hash]) { | ||
matchLen[len] = matchLen[len] || 0; | ||
matchLen[len] += 1; | ||
} else { | ||
base[len][hash] = 1; | ||
} | ||
} | ||
}); | ||
|
||
data = null; | ||
|
||
const { logger, selectedHashLen } = this; | ||
|
||
logger.log('Suggest Minify Plugin'); | ||
logger.log('Matched length (len: number):', matchLen); | ||
|
||
if (matchLen[selectedHashLen]) { | ||
logger.log( | ||
`🚫 You can't use selected hash length (${selectedHashLen}). Increase the hash length.` | ||
); | ||
process.exit(1); | ||
} else { | ||
logger.log(`Selected hash length (${selectedHashLen}) is OK.`); | ||
|
||
if (!matchLen[selectedHashLen - 1]) { | ||
logger.log( | ||
`🎉 You can decrease the hash length (${selectedHashLen} -> ${ | ||
selectedHashLen - 1 | ||
}).` | ||
); | ||
} | ||
} | ||
} | ||
} |
This file contains 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 |
---|---|---|
@@ -1,5 +1,7 @@ | ||
import importParser from "./postcss-import-parser"; | ||
import icssParser from "./postcss-icss-parser"; | ||
import urlParser from "./postcss-url-parser"; | ||
import importParser from './postcss-import-parser'; | ||
import icssParser from './postcss-icss-parser'; | ||
import urlParser from './postcss-url-parser'; | ||
import HashLenSuggest from './hash-len-suggest'; | ||
import OneLetterCss from './one-letter-css'; | ||
|
||
export { importParser, icssParser, urlParser }; | ||
export { HashLenSuggest, OneLetterCss, importParser, icssParser, urlParser }; |
This file contains 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,209 @@ | ||
const { interpolateName } = require('loader-utils'); | ||
|
||
/** | ||
* Change css-classes to 64-bit prefix (by class position at file) + hash postfix (by file path) | ||
*/ | ||
|
||
// Parse encoding string, or get default values | ||
const getRule = (externalRule) => { | ||
let iRule = { | ||
type: 'hash', | ||
rule: 'base64', | ||
hashLen: 8, | ||
val: '', | ||
}; | ||
|
||
iRule.val = `[${iRule.type}:${iRule.rule}:${iRule.hashLen}]`; | ||
|
||
const matchHashRule = | ||
externalRule | ||
.replace(/_/g, '') | ||
.match(/^(?:\[local])*\[([a-z\d]+):([a-z\d]+):(\d+)]$/) || []; | ||
|
||
if (matchHashRule.length >= 4) { | ||
const [, type, rule, hashLen] = matchHashRule; | ||
|
||
iRule = { | ||
type, | ||
rule, | ||
hashLen, | ||
val: `[${type}:${rule}:${hashLen}]`, | ||
}; | ||
} | ||
|
||
return iRule; | ||
}; | ||
|
||
export default class OneLetterCssClasses { | ||
constructor() { | ||
// Save separators points from ascii-table | ||
this.a = 'a'.charCodeAt(0); | ||
this.A = 'A'.charCodeAt(0); | ||
this.zero = '0'.charCodeAt(0); | ||
this.files = {}; | ||
// [a-zA-Z\d_-] | ||
this.encoderSize = 64; | ||
this.symbolsArea = { | ||
// a-z | ||
az: 26, | ||
// A-Z | ||
AZ: 52, | ||
// _ | ||
under: 53, | ||
// 0-9 | \d | ||
digit: 63, | ||
// - | ||
// dash: 64 | ||
}; | ||
// prevent loop hell | ||
this.maxLoop = 5; | ||
this.rootPathLen = process.cwd().length; | ||
} | ||
|
||
getSingleSymbol(n) { | ||
const { | ||
a, | ||
A, | ||
zero, | ||
encoderSize, | ||
symbolsArea: { az, AZ, under, digit }, | ||
} = this; | ||
|
||
if (!n) { | ||
// console.error(`!n, n=${n}`); | ||
return ''; | ||
} | ||
|
||
if (n > encoderSize) { | ||
// console.error(`n > ${encoderSize}, n=${n}`); | ||
return ''; | ||
} | ||
|
||
// work with 1 <= n <= 64 | ||
if (n <= az) { | ||
return String.fromCharCode(n - 1 + a); | ||
} | ||
|
||
if (n <= AZ) { | ||
return String.fromCharCode(n - 1 - az + A); | ||
} | ||
|
||
if (n <= under) { | ||
return '_'; | ||
} | ||
|
||
if (n <= digit) { | ||
return String.fromCharCode(n - 1 - under + zero); | ||
} | ||
|
||
return '-'; | ||
} | ||
|
||
/** Encode classname by position at file, 0 - a, 1 - b, etc */ | ||
getNamePrefix(num) { | ||
const { maxLoop, encoderSize } = this; | ||
|
||
if (!num) { | ||
return ''; | ||
} | ||
|
||
let loopCount = 0; | ||
let n = num; | ||
let res = ''; | ||
|
||
// Divide at loop for 64 | ||
// For example, from 1 to 64 - 1 step, from 65 to 4096 (64*64) - 2 steps, etc | ||
while (n && loopCount < maxLoop) { | ||
// Remainder of division, for 1-64 encode | ||
let tail = n % encoderSize; | ||
const origTail = tail; | ||
|
||
// Check limits, n === encoderSize. 64 % 64 = 0, but encoding for 64 | ||
if (tail === 0) { | ||
tail = encoderSize; | ||
} | ||
|
||
// Concat encoding result | ||
res = this.getSingleSymbol(tail) + res; | ||
|
||
// Check for new loop | ||
if (Math.floor((n - 1) / encoderSize)) { | ||
// Find the number of bits for next encoding cycle | ||
n = (n - origTail) / encoderSize; | ||
|
||
// At limit value (64), go to a new circle, | ||
// -1 to avoid (we have already encoded this) | ||
// | ||
if (origTail === 0) { | ||
n -= 1; | ||
} | ||
} else { | ||
n = 0; | ||
} | ||
|
||
loopCount += 1; | ||
} | ||
|
||
return res; | ||
} | ||
|
||
/** | ||
* Make hash | ||
*/ | ||
getLocalIdentWithFileHash(context, localIdentName, localName) { | ||
const { resourcePath } = context; | ||
const { files, rootPathLen } = this; | ||
|
||
// To fix difference between stands, work with file path from project root | ||
const resPath = resourcePath.substr(rootPathLen); | ||
|
||
// Filename at list, take his name | ||
let fileShort = files[resPath]; | ||
|
||
// Filename not at list, generate new name, save | ||
if (!fileShort) { | ||
// parse encoding rule | ||
const localIdentRule = getRule(localIdentName); | ||
|
||
const fileShortName = interpolateName(context, localIdentRule.val, { | ||
content: resPath, | ||
}); | ||
|
||
fileShort = { name: fileShortName, lastUsed: 0, ruleNames: {} }; | ||
files[resPath] = fileShort; | ||
} | ||
|
||
// Take rulename, if exists at current file | ||
let newRuleName = fileShort.ruleNames[localName]; | ||
|
||
// If rulename not exist - generate new, and save | ||
if (!newRuleName) { | ||
// Increase rules count | ||
fileShort.lastUsed += 1; | ||
|
||
// Generate new rulename | ||
newRuleName = this.getNamePrefix(fileShort.lastUsed) + fileShort.name; | ||
|
||
// Save rulename | ||
fileShort.ruleNames[localName] = newRuleName; | ||
} | ||
|
||
// Check encoding settings for local development (save original rulenames) | ||
const hasLocal = /\[local]/.test(localIdentName); | ||
|
||
// If develop mode - add prefix | ||
const res = hasLocal ? `${localName}__${newRuleName}` : newRuleName; | ||
|
||
// Add prefix '_' for classes with '-' or digit '\d' | ||
// or '_' (for fix collision) | ||
return /^[\d_-]/.test(res) ? `_${res}` : res; | ||
} | ||
|
||
getStat() { | ||
const stat = { ...this.files }; | ||
|
||
this.files = {}; | ||
|
||
return stat; | ||
} | ||
} |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Here potential memory leak in watch mode, if will have a lot of renamed files, the object will grow
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fixed at last call - getStat()