/
javascript.go
62 lines (54 loc) · 1.5 KB
/
javascript.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
package compile
import (
"bytes"
"context"
"fmt"
"os/exec"
"path/filepath"
"regexp"
"time"
)
var _ Refiner = &RefineJavascript{}
var reJavascriptMatch = regexp.MustCompile(`(?i)\.(js|json|jsx)$`)
// RefineJavascript compiles a Javascript file to ESNext.
type RefineJavascript struct {
passthrough
}
// Match returns true if pattern fits the file path.
func (rf *RefineJavascript) Match(p string) bool {
if reMinPass.MatchString(p) {
return false // skip already minified assets
}
return reJavascriptMatch.MatchString(p)
}
// Debug preserves the comments and keeps Javascript readable.
func (rf *RefineJavascript) Debug(destination, source string) error {
return rf.compile(source, destination, true)
}
// Refine runs the compilation and minification.
func (rf *RefineJavascript) Refine(destination, source string) error {
return rf.compile(source, destination, false)
}
func (rf *RefineJavascript) compile(file, output string, debug bool) error {
// exec.LookPath(`esbuild`) // TODO: should I check if it is installed?
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*5)
defer cancel() // interrupts the process running
args := []string{
filepath.Base(file),
`--outfile=` + output,
`--bundle`,
}
if !debug {
args = append(args, `--minify`)
}
p := exec.CommandContext(ctx, `esbuild`, args...)
var b bytes.Buffer
p.Stderr = &b
p.Stdout = &b
p.Dir = filepath.Dir(file)
err := p.Run()
if err != nil {
return fmt.Errorf(`%s: %s`, filepath.Dir(file), b.String())
}
return nil
}