-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptimizedCssHash.js
58 lines (45 loc) · 2.17 KB
/
optimizedCssHash.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const generateCssClass = require('css-class-generator');
const loaderUtils = require('loader-utils');
const createFileShortDef = fileHashedName => {
return {name: fileHashedName, lastUsed: -1, ruleNames: {}};
};
const createGenerator = ({baseInterpolateName} = {baseInterpolateName: '[hash:base64:5]'}) => {
const files = new Map();
// eslint-disable-next-line max-params, max-statements
return (loaderContext, localIdentName, localName) => {
// css-loader config.localIdentName should contain [pathHash] for correct word
if (!/\[pathHash]/.test(localIdentName)) {
console.warn(
`You should provide [pathHash] to localIdentName to use this plugin feature. \n Your localIdentName is: ${localIdentName}`,
);
// emulate default css-loader getLocalIdentName behavior
// https://github.com/webpack-contrib/css-loader/blob/e27ab5ead47c6bcf8b218dbce52ddd692111e833/src/utils.js#L803
return null;
}
let fileShort = files.get(loaderContext.resourcePath);
if (!fileShort) {
const fileHashedName = loaderUtils.interpolateName(
loaderContext.context,
baseInterpolateName,
{
// any file should contaiil unique resuourse path. So it will be key for every classname in the file
content: `${loaderContext.resourcePath}`,
},
);
const fileShortDef = createFileShortDef(fileHashedName);
files.set(loaderContext.resourcePath, fileShortDef);
fileShort = fileShortDef;
}
const ruleName = fileShort.ruleNames[localName];
if (!ruleName) {
fileShort.lastUsed += 1;
const generatedClassname = `${generateCssClass(fileShort.lastUsed)}${fileShort.name}`;
fileShort.ruleNames[localName] = generatedClassname;
}
return loaderUtils
.interpolateName(loaderContext, localIdentName, {content: localName})
.replace('[local]', localName)
.replace('[pathHash]', fileShort.ruleNames[localName]);
};
};
module.exports = {createGenerator};