| 1 |
// Copyright 2024 The Hugo Authors. All rights reserved. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
//go:generate go run main.go |
| 15 |
package main |
| 16 |
|
| 17 |
import ( |
| 18 |
"fmt" |
| 19 |
"log" |
| 20 |
"os" |
| 21 |
"path/filepath" |
| 22 |
"strings" |
| 23 |
|
| 24 |
"github.com/evanw/esbuild/pkg/api" |
| 25 |
) |
| 26 |
|
| 27 |
var scripts = []string{ |
| 28 |
"greet.js", |
| 29 |
"renderkatex.js", |
| 30 |
} |
| 31 |
|
| 32 |
func main() { |
| 33 |
for _, script := range scripts { |
| 34 |
filename := filepath.Join("../js", script) |
| 35 |
err := buildJSBundle(filename) |
| 36 |
if err != nil { |
| 37 |
log.Fatal(err) |
| 38 |
} |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
func buildJSBundle(filename string) error { |
| 43 |
minify := true |
| 44 |
result := api.Build( |
| 45 |
api.BuildOptions{ |
| 46 |
EntryPoints: []string{filename}, |
| 47 |
Bundle: true, |
| 48 |
MinifyWhitespace: minify, |
| 49 |
MinifyIdentifiers: minify, |
| 50 |
MinifySyntax: minify, |
| 51 |
Target: api.ES2020, |
| 52 |
Outfile: strings.Replace(filename, ".js", ".bundle.js", 1), |
| 53 |
SourceRoot: "../js", |
| 54 |
}) |
| 55 |
|
| 56 |
if len(result.Errors) > 0 { |
| 57 |
return fmt.Errorf("build failed: %v", result.Errors) |
| 58 |
} |
| 59 |
if len(result.OutputFiles) != 1 { |
| 60 |
return fmt.Errorf("expected 1 output file, got %d", len(result.OutputFiles)) |
| 61 |
} |
| 62 |
|
| 63 |
of := result.OutputFiles[0] |
| 64 |
if err := os.WriteFile(filepath.FromSlash(of.Path), of.Contents, 0o644); err != nil { |
| 65 |
return fmt.Errorf("write file failed: %v", err) |
| 66 |
} |
| 67 |
return nil |
| 68 |
} |