-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathesbuild_scss.go
232 lines (198 loc) · 5.82 KB
/
esbuild_scss.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package main
import (
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/bep/godartsass/v2"
"github.com/evanw/esbuild/pkg/api"
"github.com/evanw/esbuild/pkg/cli"
_ "embed"
)
//go:embed version.txt
var version string
type NodeModulesImportResolver struct {
build api.PluginBuild
inputPath string
includeFiles []string
}
type SassCompileResult struct {
output string
includeFiles []string
err error
}
func NodeResolve(filePath string, build api.PluginBuild) (string, []api.Message) {
result := build.Resolve(filePath, api.ResolveOptions{
Kind: api.ResolveCSSImportRule,
ResolveDir: ".",
})
return result.Path, result.Errors
}
func LocalFile(dir string, filePath string) (string, error) {
localFilePath := filepath.Join(dir, filePath)
if _, err := os.Stat(localFilePath); os.IsNotExist(err) {
return "", err
}
return localFilePath, nil
}
func LocalOrNodeResolve(filePath string, dir string, build api.PluginBuild) (string, error) {
nodeResult, errs := NodeResolve(filePath, build)
if errs == nil {
return nodeResult, nil
}
localFilePath, err := LocalFile(dir, filePath)
if err == nil {
return localFilePath, nil
}
return "", fmt.Errorf("not found")
}
func (resolver *NodeModulesImportResolver) CanonicalizeURL(filePath string) (string, error) {
dir, _ := filepath.Split(resolver.inputPath)
if !strings.HasSuffix(filePath, "scss") {
filePath = filePath + ".scss"
}
u, err := url.Parse(filePath)
if err == nil && u.Scheme == "file" {
filePath = u.Path
dir = ""
}
file, err := LocalOrNodeResolve(filePath, dir, resolver.build)
if err == nil {
resolver.includeFiles = append(resolver.includeFiles, file)
return "file://" + file, nil
}
packagePath, fileName := filepath.Split(filePath)
fileWithPrefix := filepath.Join(packagePath, "_"+fileName)
filePrefix, err := LocalOrNodeResolve(fileWithPrefix, dir, resolver.build)
if err == nil {
resolver.includeFiles = append(resolver.includeFiles, filePrefix)
return "file://" + filePrefix, nil
}
return "", err
}
func (resolver NodeModulesImportResolver) Load(canonicalizedURL string) (godartsass.Import, error) {
u, err := url.Parse(canonicalizedURL)
if err == nil && u.Scheme == "file" {
canonicalizedURL = u.Path
}
content, err := os.ReadFile(canonicalizedURL)
if err != nil {
return godartsass.Import{}, err
}
// Return the parsed import data
return godartsass.Import{
Content: string(content),
SourceSyntax: findSourceSyntax(canonicalizedURL),
}, nil
}
func compileSass(inputPath string, build api.PluginBuild) SassCompileResult {
// Read the input Sass/SCSS file
input, err := os.ReadFile(inputPath)
if err != nil {
return SassCompileResult{err: err}
}
// add sass to the path
current, err := os.Executable()
if err != nil {
return SassCompileResult{err: err}
}
bin := filepath.Dir(current)
pack := filepath.Dir(bin)
dartSass := filepath.Join(filepath.Dir(pack), "dart-sass", "sass")
sourceSyntax := findSourceSyntax(inputPath)
// Create a Dart Sass compiler
compiler, err := godartsass.Start(godartsass.Options{
DartSassEmbeddedFilename: dartSass,
})
if err != nil {
return SassCompileResult{err: err}
}
defer compiler.Close()
resolver := NodeModulesImportResolver{
build,
inputPath,
[]string{},
}
// Compile the Sass/SCSS to CSS
output, err := compiler.Execute(godartsass.Args{
Source: string(input),
OutputStyle: godartsass.OutputStyleCompressed,
SourceSyntax: sourceSyntax,
IncludePaths: []string{filepath.Dir(inputPath)},
EnableSourceMap: true,
ImportResolver: &resolver,
})
if err != nil {
return SassCompileResult{err: err}
}
return SassCompileResult{output: output.CSS, includeFiles: resolver.includeFiles, err: nil}
}
func findSourceSyntax(inputPath string) godartsass.SourceSyntax {
extension := filepath.Ext(inputPath)
var sourceSyntax = godartsass.SourceSyntaxSCSS
if extension == ".sass" {
sourceSyntax = godartsass.SourceSyntaxSASS
}
return sourceSyntax
}
var scssPlugin = api.Plugin{
Name: "sass-loader",
Setup: func(build api.PluginBuild) {
build.OnLoad(api.OnLoadOptions{Filter: `^.*(scss|sass)$`},
func(args api.OnLoadArgs) (api.OnLoadResult, error) {
// Compile the Sass/SCSS file to CSS
extension := filepath.Ext(args.Path)
filenameWithoutExtension := strings.TrimSuffix(args.Path, extension)
outputPath := filenameWithoutExtension + ".css"
result := compileSass(args.Path, build)
if result.err != nil {
return api.OnLoadResult{}, result.err
}
// Modify the import path to the generated CSS file
args.Path = outputPath
return api.OnLoadResult{Contents: &result.output, Loader: api.LoaderCSS, WatchFiles: result.includeFiles}, nil
})
},
}
func main() {
osArgs := os.Args[1:]
argsEnd := 0
for _, arg := range osArgs {
switch {
case arg == "--version":
fmt.Printf("%s", version)
os.Exit(0)
case arg == "--watch" || arg == "--watch=forever":
go func() {
// This just discards information from stdin because we don't use
// it and we can avoid unnecessarily allocating space for it
buffer := make([]byte, 512)
for {
_, err := os.Stdin.Read(buffer)
if err != nil {
// Only exit cleanly if stdin was closed cleanly
if err == io.EOF {
os.Exit(0)
} else {
os.Exit(1)
}
}
// Some people attempt to keep esbuild's watch mode open by piping
// an infinite stream of data to stdin such as with "< /dev/zero".
// This will make esbuild spin at 100% CPU. To avoid this, put a
// small delay after we read some data from stdin.
time.Sleep(4 * time.Millisecond)
}
}()
if arg != "--watch" {
osArgs = append(osArgs[:argsEnd], osArgs[argsEnd+1:]...)
osArgs = append(osArgs, "--watch")
}
}
argsEnd++
}
os.Exit(cli.RunWithPlugins(osArgs, []api.Plugin{scssPlugin}))
}