-
Notifications
You must be signed in to change notification settings - Fork 0
/
css-minifier.go
64 lines (54 loc) · 1.49 KB
/
css-minifier.go
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
package main
import (
"log"
"os"
"regexp"
"strings"
)
type CssMinifier struct {
*Minifier
}
func NewCssMinifier(minifier *Minifier) MinifierInterface {
return &CssMinifier{
Minifier: minifier,
}
}
func (minifier *CssMinifier) ReadFile() {
content, err := os.ReadFile(minifier.InputFilename)
if err != nil {
log.Fatal(err.Error())
}
minifier.Content = string(content)
}
func (minifier *CssMinifier) Minify() {
minifier.removeComments()
minifier.removeWhiteSpace()
}
func (minifier *CssMinifier) WriteFile() {
outputFilename := minifier.OutputFilename
if minifier.OutputFilename == "" {
outputFilename = strings.Replace(minifier.InputFilename, ".css", ".min.css", 1)
}
minifier.OutputFilename = outputFilename
err := os.WriteFile(outputFilename, []byte(minifier.Content), 0644)
if err != nil {
panic(err)
}
}
func (minifier *CssMinifier) removeComments() {
// Remove block comments
blockCommentRegex := regexp.MustCompile(`/\*.*?\*/`)
minifier.Content = blockCommentRegex.ReplaceAllString(minifier.Content, "")
}
func (minifier *CssMinifier) removeWhiteSpace() {
// Remove extra white spaces and newlines
str := strings.Join(strings.Fields(minifier.Content), " ")
str = strings.ReplaceAll(str, "{ ", "{")
str = strings.ReplaceAll(str, " {", "{")
str = strings.ReplaceAll(str, "} ", "}")
str = strings.ReplaceAll(str, "; ", ";")
str = strings.ReplaceAll(str, ": ", ":")
str = strings.ReplaceAll(str, ", ", ",")
str = strings.ReplaceAll(str, ";}", "}")
minifier.Content = str
}