js.go (1858B)
1 // Copyright 2020 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 // Package js provides functions for building JavaScript resources
15 package js
16
17 import (
18 "github.com/gohugoio/hugo/deps"
19 "github.com/gohugoio/hugo/resources"
20 "github.com/gohugoio/hugo/resources/resource"
21 "github.com/gohugoio/hugo/resources/resource_transformers/js"
22 "github.com/gohugoio/hugo/tpl/internal/resourcehelpers"
23 )
24
25 // New returns a new instance of the js-namespaced template functions.
26 func New(deps *deps.Deps) *Namespace {
27 if deps.ResourceSpec == nil {
28 return &Namespace{}
29 }
30 return &Namespace{
31 client: js.New(deps.BaseFs.Assets, deps.ResourceSpec),
32 }
33 }
34
35 // Namespace provides template functions for the "js" namespace.
36 type Namespace struct {
37 deps *deps.Deps
38 client *js.Client
39 }
40
41 // Build processes the given Resource with ESBuild.
42 func (ns *Namespace) Build(args ...any) (resource.Resource, error) {
43 var (
44 r resources.ResourceTransformer
45 m map[string]any
46 targetPath string
47 err error
48 ok bool
49 )
50
51 r, targetPath, ok = resourcehelpers.ResolveIfFirstArgIsString(args)
52
53 if !ok {
54 r, m, err = resourcehelpers.ResolveArgs(args)
55 if err != nil {
56 return nil, err
57 }
58 }
59
60 if targetPath != "" {
61 m = map[string]any{"targetPath": targetPath}
62 }
63
64 return ns.client.Process(r, m)
65 }