| 1 |
--- |
| 2 |
title: js.Batch |
| 3 |
description: Build JavaScript bundle groups with global code splitting and flexible hooks/runners setup. |
| 4 |
categories: [] |
| 5 |
keywords: [] |
| 6 |
params: |
| 7 |
functions_and_methods: |
| 8 |
aliases: [] |
| 9 |
returnType: js.Batcher |
| 10 |
signatures: ['js.Batch [ID]'] |
| 11 |
--- |
| 12 |
|
| 13 |
> [!NOTE] |
| 14 |
> The `js.Batch` function is backed by the [`evanw/esbuild`][] package, providing a mature, high-performance foundation for bundling, transformation, and minification. |
| 15 |
|
| 16 |
> [!NOTE] |
| 17 |
> For a runnable example of this feature, see [this test and demo repo][js_batch_demo]. |
| 18 |
|
| 19 |
The Batch `ID` is used to create the base directory for this batch. Forward slashes are allowed. The `js.Batch` function returns an object with an API with this structure: |
| 20 |
|
| 21 |
- [Group](#group) |
| 22 |
- [Script](#script) |
| 23 |
- [SetOptions](#optionssetter) |
| 24 |
- [Instance](#instance) |
| 25 |
- [SetOptions](#optionssetter) |
| 26 |
- [Runner](#runner) |
| 27 |
- [SetOptions](#optionssetter) |
| 28 |
- [Config](#config) |
| 29 |
- [SetOptions](#optionssetter) |
| 30 |
|
| 31 |
## Group |
| 32 |
|
| 33 |
The `Group` method take an `ID` (`string`) as argument. No slashes. It returns an object with these methods: |
| 34 |
|
| 35 |
### Script |
| 36 |
|
| 37 |
The `Script` method takes an `ID` (`string`) as argument. No slashes. It returns an [OptionsSetter](#optionssetter) that can be used to set [script options](#script-options) for this script. |
| 38 |
|
| 39 |
```go-html-template |
| 40 |
{{ with js.Batch "js/mybatch" }} |
| 41 |
{{ with .Group "mygroup" }} |
| 42 |
{{ with .Script "myscript" }} |
| 43 |
{{ .SetOptions (dict "resource" (resources.Get "myscript.js")) }} |
| 44 |
{{ end }} |
| 45 |
{{ end }} |
| 46 |
{{ end }} |
| 47 |
``` |
| 48 |
|
| 49 |
`SetOptions` takes a [script options](#script-options) map. Note that if you want the script to be handled by a [Runner](#runner), you need to set the `export` option to match what you want to pass on to the runner (default is `*`). |
| 50 |
|
| 51 |
### Instance |
| 52 |
|
| 53 |
The `Instance` method takes two `string` arguments `SCRIPT_ID` and `INSTANCE_ID`. No slashes. It returns an [OptionsSetter](#optionssetter) that can be used to set [params options](#params-options) for this instance. |
| 54 |
|
| 55 |
```go-html-template |
| 56 |
{{ with js.Batch "js/mybatch" }} |
| 57 |
{{ with .Group "mygroup" }} |
| 58 |
{{ with .Instance "myscript" "myinstance" }} |
| 59 |
{{ .SetOptions (dict "params" (dict "param1" "value1")) }} |
| 60 |
{{ end }} |
| 61 |
{{ end }} |
| 62 |
{{ end }} |
| 63 |
``` |
| 64 |
|
| 65 |
`SetOptions` takes a [params options](#params-options) map. The instance options will be passed to any [Runner](#runner) script in the same group, as JSON. |
| 66 |
|
| 67 |
### Runner |
| 68 |
|
| 69 |
The `Runner` method takes an `ID` (`string`) as argument. No slashes. It returns an [OptionsSetter](#optionssetter) that can be used to set [script options](#script-options) for this runner. |
| 70 |
|
| 71 |
```go-html-template |
| 72 |
{{ with js.Batch "js/mybatch" }} |
| 73 |
{{ with .Group "mygroup" }} |
| 74 |
{{ with .Runner "myrunner" }} |
| 75 |
{{ .SetOptions (dict "resource" (resources.Get "myrunner.js")) }} |
| 76 |
{{ end }} |
| 77 |
{{ end }} |
| 78 |
{{ end }} |
| 79 |
``` |
| 80 |
|
| 81 |
`SetOptions` takes a [script options](#script-options) map. |
| 82 |
|
| 83 |
The runner will receive a data structure with all instances for that group with a live binding of the [JavaScript import][] of the defined `export`. |
| 84 |
|
| 85 |
The runner script's export must be a function that takes one argument, the group data structure. An example of a group data structure as JSON is: |
| 86 |
|
| 87 |
```json |
| 88 |
{ |
| 89 |
"id": "leaflet", |
| 90 |
"scripts": [ |
| 91 |
{ |
| 92 |
"id": "mapjsx", |
| 93 |
"binding": JAVASCRIPT_BINDING, |
| 94 |
"instances": [ |
| 95 |
{ |
| 96 |
"id": "0", |
| 97 |
"params": { |
| 98 |
"c": "h-64", |
| 99 |
"lat": 48.8533173846729, |
| 100 |
"lon": 2.3497416090232535, |
| 101 |
"r": "map.jsx", |
| 102 |
"title": "Cathédrale Notre-Dame de Paris", |
| 103 |
"zoom": 23 |
| 104 |
} |
| 105 |
}, |
| 106 |
{ |
| 107 |
"id": "1", |
| 108 |
"params": { |
| 109 |
"c": "h-64", |
| 110 |
"lat": 59.96300872062237, |
| 111 |
"lon": 10.663529183196863, |
| 112 |
"r": "map.jsx", |
| 113 |
"title": "Holmenkollen", |
| 114 |
"zoom": 3 |
| 115 |
} |
| 116 |
} |
| 117 |
] |
| 118 |
} |
| 119 |
] |
| 120 |
} |
| 121 |
``` |
| 122 |
|
| 123 |
Below is an example of a runner script that uses React to render elements. Note that the export (`default`) must match the `export` option in the [script options](#script-options) (`default` is the default value for runner scripts). Runnable versions of the examples on this page can be found in this `js.Batch` [demonstration repository][js_batch_demo]. |
| 124 |
|
| 125 |
```js |
| 126 |
import * as ReactDOM from 'react-dom/client'; |
| 127 |
import * as React from 'react'; |
| 128 |
|
| 129 |
export default function Run(group) { |
| 130 |
console.log('Running react-create-elements.js', group); |
| 131 |
const scripts = group.scripts; |
| 132 |
for (const script of scripts) { |
| 133 |
for (const instance of script.instances) { |
| 134 |
/* This is a convention in this project. */ |
| 135 |
let elId = `${script.id}-${instance.id}`; |
| 136 |
let el = document.getElementById(elId); |
| 137 |
if (!el) { |
| 138 |
console.warn(`Element with id ${elId} not found`); |
| 139 |
continue; |
| 140 |
} |
| 141 |
const root = ReactDOM.createRoot(el); |
| 142 |
const reactEl = React.createElement(script.binding, instance.params); |
| 143 |
root.render(reactEl); |
| 144 |
} |
| 145 |
} |
| 146 |
} |
| 147 |
``` |
| 148 |
|
| 149 |
### Config |
| 150 |
|
| 151 |
Returns an [OptionsSetter](#optionssetter) that can be used to set [build options](#build-options) for the batch. |
| 152 |
|
| 153 |
These are mostly the same as for `js.Build`, but note that: |
| 154 |
|
| 155 |
- `targetPath` is set automatically (there may be multiple outputs). |
| 156 |
- `format` must be `esm`, currently the only format that supports [code splitting][]. |
| 157 |
- `params` will be available in the `@params/config` namespace in the scripts. This way you can import both the [Script](#script) or [Runner](#runner) params and the [Config](#config) params with: |
| 158 |
|
| 159 |
```js |
| 160 |
import * as params from "@params"; |
| 161 |
import * as config from "@params/config"; |
| 162 |
``` |
| 163 |
|
| 164 |
Setting the `Config` for a batch can be done from any template (including shortcode templates), but will only be set once (the first will win): |
| 165 |
|
| 166 |
```go-html-template |
| 167 |
{{ with js.Batch "js/mybatch" }} |
| 168 |
{{ with .Config }} |
| 169 |
{{ .SetOptions (dict |
| 170 |
"target" "es2023" |
| 171 |
"format" "esm" |
| 172 |
"jsx" "automatic" |
| 173 |
"loaders" (dict ".png" "dataurl") |
| 174 |
"minify" true |
| 175 |
"params" (dict "param1" "value1") |
| 176 |
) |
| 177 |
}} |
| 178 |
{{ end }} |
| 179 |
{{ end }} |
| 180 |
``` |
| 181 |
|
| 182 |
## Options |
| 183 |
|
| 184 |
### Build options |
| 185 |
|
| 186 |
`format` |
| 187 |
: (`string`) Currently, `esbuild` only supports `esm` output for [code splitting][]. |
| 188 |
|
| 189 |
{{% include "/_common/functions/js/options.md" %}} |
| 190 |
|
| 191 |
### Script options |
| 192 |
|
| 193 |
`resource` |
| 194 |
: The resource to build. This can be a file resource or a virtual resource. |
| 195 |
|
| 196 |
`export` |
| 197 |
: The export to bind the runner to. Set it to `*` to export the [entire namespace][]. Default is `default` for [Runner](#runner) scripts and `*` for other [scripts](#script). |
| 198 |
|
| 199 |
`importContext` |
| 200 |
: An additional context for resolving imports. Hugo will always check this one first before falling back to `assets` and `node_modules`. A common use of this is to resolve imports inside a page bundle. See [import context](#import-context). |
| 201 |
|
| 202 |
`params` |
| 203 |
: A map of parameters that will be passed to the script as JSON. These gets bound to the `@params` namespace: |
| 204 |
|
| 205 |
```js |
| 206 |
import * as params from '@params'; |
| 207 |
``` |
| 208 |
|
| 209 |
### Params options |
| 210 |
|
| 211 |
`params` |
| 212 |
: A map of parameters that will be passed to the script as JSON. |
| 213 |
|
| 214 |
### Import context |
| 215 |
|
| 216 |
Hugo will, by default, first try to resolve any import in the `assets` directory and, if not found, let `esbuild` resolve it (e.g. from `node_modules`). The `importContext` option can be used to set the first context for resolving imports. A common use of this is to resolve imports inside a [page bundle][]. |
| 217 |
|
| 218 |
```go-html-template |
| 219 |
{{ $common := resources.Match "/js/headlessui/*.*" }} |
| 220 |
{{ $importContext := (slice $.Page ($common.Mount "/js/headlessui" ".")) }} |
| 221 |
``` |
| 222 |
|
| 223 |
You can pass any object that implements [`Resource.Get`][]. Pass a slice to set multiple contexts. |
| 224 |
|
| 225 |
The example above uses [`Resources.Mount`][] to resolve a directory inside `assets` relative to the page bundle. |
| 226 |
|
| 227 |
### OptionsSetter |
| 228 |
|
| 229 |
An `OptionsSetter` is a special object that is returned once only. This means that you should wrap it with [`with`][]: |
| 230 |
|
| 231 |
```go-html-template |
| 232 |
{{ with .Script "myscript" }} |
| 233 |
{{ .SetOptions (dict "resource" (resources.Get "myscript.js"))}} |
| 234 |
{{ end }} |
| 235 |
``` |
| 236 |
|
| 237 |
## Build |
| 238 |
|
| 239 |
The `Build` method returns an object with the following structure: |
| 240 |
|
| 241 |
- Groups (map) |
| 242 |
- [`Resources`][] |
| 243 |
|
| 244 |
Each [`Resource`][] will be of media type `application/javascript` or `text/css`. |
| 245 |
|
| 246 |
In a template you would typically handle one group with a given `ID` (e.g., scripts for the current section). Because of the concurrent build, this needs to be done in a [`templates.Defer`][] block: |
| 247 |
|
| 248 |
> [!NOTE] |
| 249 |
> The [`templates.Defer`][] acts as a synchronisation point to handle scripts added concurrently by different templates. If you have a setup with where the batch is created in one go (in one template), you don't need it. |
| 250 |
> |
| 251 |
> See [this discussion][] for more information. |
| 252 |
|
| 253 |
```go-html-template |
| 254 |
{{ $group := .group }} |
| 255 |
{{ with (templates.Defer (dict "key" $group "data" $group )) }} |
| 256 |
{{ with (js.Batch "js/mybatch") }} |
| 257 |
{{ with .Build }} |
| 258 |
{{ with index .Groups $ }} |
| 259 |
{{ range . }} |
| 260 |
{{ $s := . }} |
| 261 |
{{ if eq $s.MediaType.SubType "css" }} |
| 262 |
<link href="{{ $s.RelPermalink }}" rel="stylesheet" /> |
| 263 |
{{ else }} |
| 264 |
<script src="{{ $s.RelPermalink }}" type="module"></script> |
| 265 |
{{ end }} |
| 266 |
{{ end }} |
| 267 |
{{ end }} |
| 268 |
{{ end }} |
| 269 |
{{ end }} |
| 270 |
``` |
| 271 |
|
| 272 |
## Known Issues |
| 273 |
|
| 274 |
In the official documentation for the `esbuild` [code splitting][] feature, there's a warning note in the header. The two issues are: |
| 275 |
|
| 276 |
- `esm` is currently the only implemented output format. This means that it will not work for legacy browsers. See [caniuse][]. |
| 277 |
- There's a known import ordering issue. |
| 278 |
|
| 279 |
We have not seen the ordering issue as a problem during our [extensive testing][] of this new feature with different libraries. There are two main cases: |
| 280 |
|
| 281 |
1. Undefined execution order of imports, see [this comment][comment-1] |
| 282 |
1. Only one execution order of imports, see [this comment][comment-2] |
| 283 |
|
| 284 |
Many would say that both of the above are [code smells][]. The first one has a simple workaround in Hugo. Define the import order in its own script and make sure it gets passed early to `esbuild`, e.g., by putting it in a script group with a name that comes early in the alphabet. |
| 285 |
|
| 286 |
```js |
| 287 |
import './lib2.js'; |
| 288 |
import './lib1.js'; |
| 289 |
|
| 290 |
console.log('entrypoints-workaround.js'); |
| 291 |
``` |
| 292 |
|
| 293 |
[JavaScript import]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import |
| 294 |
[`Resource.Get`]: /methods/page/resources/#get |
| 295 |
[`Resource`]: /methods/resource/ |
| 296 |
[`Resources.Mount`]: /methods/page/resources/#mount |
| 297 |
[`Resources`]: /methods/page/resources/ |
| 298 |
[`evanw/esbuild`]: https://github.com/evanw/esbuild |
| 299 |
[`templates.Defer`]: /functions/templates/defer/ |
| 300 |
[`with`]: /functions/go-template/with/ |
| 301 |
[caniuse]: https://caniuse.com/?search=ESM |
| 302 |
[code smells]: https://en.wikipedia.org/wiki/Code_smell |
| 303 |
[code splitting]: https://esbuild.github.io/api/#splitting |
| 304 |
[comment-1]: https://github.com/evanw/esbuild/issues/399#issuecomment-1458680887 |
| 305 |
[comment-2]: https://github.com/evanw/esbuild/issues/399#issuecomment-735355932 |
| 306 |
[entire namespace]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#namespace_import |
| 307 |
[extensive testing]: https://github.com/bep/hugojsbatchdemo |
| 308 |
[js_batch_demo]: https://github.com/bep/hugojsbatchdemo/ |
| 309 |
[page bundle]: /content-management/page-bundles/ |
| 310 |
[this discussion]: https://discourse.gohugo.io/t/js-batch-with-simple-global-script/53002/5 |