-
Notifications
You must be signed in to change notification settings - Fork 0
/
amp-custom.js
72 lines (61 loc) · 1.69 KB
/
amp-custom.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const CleanCSS = require('clean-css')
class AmpCustom {
constructor (option) {
this.MAX_BYTE = 75000
this.encode = 'utf-8'
this.removeStyles = [
/@charset (.+?);/g,
/@import (.+?);/g,
/@namespace (.+?);/g,
/@viewport ([\s\S]*?)}/gm,
/@-ms-viewport ([\s\S]*?)}/gm,
/@page ([\s\S]*?)}/gm,
/@document(.+?)\{(?:[^{}]*\{[^{}]*\})*[^{}]*\}/gm,
/@supports(.+?)\{(?:[^{}]*\{[^{}]*\})*[^{}]*\}/gm,
/!important/g
]
this.cleanCss = new CleanCSS(option)
}
/**
* getSize
* @param {string} cssSource - CSS source you want to measure.
* @returns {number|boolean} - Number of bytes in CSS source.
*/
getSize (cssSource) {
if (!cssSource) {
console.error(new Error('Error: CSS source is not a string.'))
return false
}
return Buffer.byteLength(cssSource, this.encode)
}
/**
* isOverMaxByte
* @param {string} cssSource - CSS source you want to check.
* @return {boolean} - Whether the CSS byte capacity does not exceed the maximum value.
*/
isOverMaxByte (cssSource) {
if (typeof cssSource !== 'string') {
return false
}
if (this.getSize(cssSource) > this.MAX_BYTE) {
return true
}
return false
}
/**
* optimize
* @param {string} cssSource - CSS source you want to optimize.
* @return {string} - Optimized CSS source.
*/
optimize (cssSource) {
if (typeof cssSource !== 'string') {
return cssSource
}
this.removeStyles.forEach((style) => {
cssSource = cssSource.replace(style, '')
})
return this.cleanCss.minify(cssSource).styles
}
}
module.exports = AmpCustom
module.exports.default = AmpCustom