-
Notifications
You must be signed in to change notification settings - Fork 1
/
esbundle.go
60 lines (51 loc) · 1.7 KB
/
esbundle.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
package esbundle
import (
"fmt"
"strings"
esbuild "github.com/evanw/esbuild/pkg/api"
"github.com/go-sourcemap/sourcemap"
)
// Result of the bundle process.
type Result struct {
CompiledContent string
SourceMapper SourceMapper
}
// SourceMapper can be used to find the origin of any line/column of the compiled content.
type SourceMapper func(genLine, genColumn int) (source, name string, line, column int, ok bool)
// Bundle returns either a Result or a list of Errors and an error.
func Bundle(inputFile string, define map[string]string) (Result, error) {
result := esbuild.Build(esbuild.BuildOptions{
EntryPoints: []string{inputFile},
Bundle: true,
Write: false,
MinifyWhitespace: false,
MinifyIdentifiers: false,
MinifySyntax: false,
LogLevel: esbuild.LogLevelInfo,
Platform: esbuild.PlatformNode,
Define: define,
Sourcemap: esbuild.SourceMapExternal,
Outdir: ".", // required for source maps
})
if len(result.Errors) > 0 {
// NOTE: esbuild prints the errors to the console by itself.
return Result{}, fmt.Errorf("esbuild failed")
}
var bundle Result
// result.OutputFiles should have generated two files: the compiles source (.js) and the source map (.map)
// map to result.{CompiledContent,SourceMapper}
for _, file := range result.OutputFiles {
if strings.HasSuffix(file.Path, ".map") {
smap, err := sourcemap.Parse("", file.Contents)
if err != nil {
panic(err)
}
bundle.SourceMapper = smap.Source
} else if strings.HasSuffix(file.Path, ".js") {
bundle.CompiledContent = string(file.Contents)
} else {
panic("unknown file: " + file.Path)
}
}
return bundle, nil
}