-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathesbuild-dev-server.go
64 lines (57 loc) · 1.27 KB
/
esbuild-dev-server.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 devserver
import (
"log"
plugin "github.com/Falldot/esbuild-dev-server/internal/api"
"github.com/evanw/esbuild/pkg/api"
)
type Options struct {
Port string
Index string
StaticDir string
WatchDir string
OnBeforeRebuild func()
OnAfterRebuild func()
}
func Start(build api.BuildResult, options Options) {
if !errorHandler(build.Errors, nil) {
log.Fatalln("esbuild error!")
}
var server plugin.DevServer
server = plugin.DevServer{
Port: options.Port,
Index: options.Index,
StaticDir: options.StaticDir,
WatchDir: options.WatchDir,
OnReload: func() {
if options.OnBeforeRebuild != nil {
options.OnBeforeRebuild()
}
result := build.Rebuild()
if errorHandler(result.Errors, server.SendError) {
server.SendReload()
}
if options.OnAfterRebuild != nil {
options.OnAfterRebuild()
}
},
}
if err := server.Start(); err != nil {
log.Fatalln(err)
}
}
func errorHandler(errors []api.Message, callback func(string)) bool {
if len(errors) > 0 {
str := api.FormatMessages(errors, api.FormatMessagesOptions{
Kind: api.ErrorMessage,
Color: true,
})
for _, err := range str {
log.Println(err)
if callback != nil {
callback(err)
}
}
return false
}
return true
}