github.com/neohugo/neohugo@v0.123.8/tpl/js/js.go (about)

     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/neohugo/neohugo/deps"
    19  	"github.com/neohugo/neohugo/resources"
    20  	"github.com/neohugo/neohugo/resources/resource"
    21  	"github.com/neohugo/neohugo/resources/resource_transformers/js"
    22  	"github.com/neohugo/neohugo/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  	client *js.Client
    38  }
    39  
    40  // Build processes the given Resource with ESBuild.
    41  func (ns *Namespace) Build(args ...any) (resource.Resource, error) {
    42  	var (
    43  		r          resources.ResourceTransformer
    44  		m          map[string]any
    45  		targetPath string
    46  		err        error
    47  		ok         bool
    48  	)
    49  
    50  	r, targetPath, ok = resourcehelpers.ResolveIfFirstArgIsString(args)
    51  
    52  	if !ok {
    53  		r, m, err = resourcehelpers.ResolveArgs(args)
    54  		if err != nil {
    55  			return nil, err
    56  		}
    57  	}
    58  
    59  	if targetPath != "" {
    60  		m = map[string]any{"targetPath": targetPath}
    61  	}
    62  
    63  	return ns.client.Process(r, m)
    64  }