HUGO
Menu
GitHub 87548 stars Mastodon

js.Batch

Build JavaScript bundle groups with global code splitting and flexible hooks/runners setup.

Syntax

js.Batch [ID]

Returns

js.Batcher

For a runnable example of this feature, see this test and demo repo.

The Batch ID is used to create the base directory for this batch. Forward slashes are allowed. js.Batch returns an object with an API with this structure:

Group

The Group method take an ID (string) as argument. No slashes. It returns an object with these methods:

Script

The Script method takes an ID (string) as argument. No slashes. It returns an OptionsSetter that can be used to set script options for this script.

{{ with js.Batch "js/mybatch" }}
  {{ with .Group "mygroup" }}
      {{ with .Script "myscript" }}
          {{ .SetOptions (dict "resource" (resources.Get "myscript.js")) }}
      {{ end }}
  {{ end }}
{{ end }}

SetOptions takes a script options map. Note that if you want the script to be handled by a runner, you need to set the export option to match what you want to pass on to the runner (default is *).

Instance

The Instance method takes two string arguments SCRIPT_ID and INSTANCE_ID. No slashes. It returns an OptionsSetter that can be used to set params options for this instance.

{{ with js.Batch "js/mybatch" }}
  {{ with .Group "mygroup" }}
      {{ with .Instance "myscript" "myinstance" }}
          {{ .SetOptions (dict "params" (dict "param1" "value1")) }}
      {{ end }}
  {{ end }}
{{ end }}

SetOptions takes a params options map. The instance options will be passed to any runner script in the same group, as JSON.

Runner

The Runner method takes an ID (string) as argument. No slashes. It returns an OptionsSetter that can be used to set script options for this runner.

{{ with js.Batch "js/mybatch" }}
  {{ with .Group "mygroup" }}
      {{ with .Runner "myrunner" }}
          {{ .SetOptions (dict "resource" (resources.Get "myrunner.js")) }}
      {{ end }}
  {{ end }}
{{ end }}

SetOptions takes a script options map.

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.

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:

{
    "id": "leaflet",
    "scripts": [
        {
            "id": "mapjsx",
            "binding": JAVASCRIPT_BINDING,
            "instances": [
                {
                    "id": "0",
                    "params": {
                        "c": "h-64",
                        "lat": 48.8533173846729,
                        "lon": 2.3497416090232535,
                        "r": "map.jsx",
                        "title": "Cathédrale Notre-Dame de Paris",
                        "zoom": 23
                    }
                },
                {
                    "id": "1",
                    "params": {
                        "c": "h-64",
                        "lat": 59.96300872062237,
                        "lon": 10.663529183196863,
                        "r": "map.jsx",
                        "title": "Holmenkollen",
                        "zoom": 3
                    }
                }
            ]
        }
    ]
}

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 (default is the default value for runner scripts) (runnable versions of examples on this page can be found at js.Batch Demo Repo):

import * as ReactDOM from 'react-dom/client';
import * as React from 'react';

export default function Run(group) {
  console.log('Running react-create-elements.js', group);
  const scripts = group.scripts;
  for (const script of scripts) {
    for (const instance of script.instances) {
      /* This is a convention in this project. */
      let elId = `${script.id}-${instance.id}`;
      let el = document.getElementById(elId);
      if (!el) {
        console.warn(`Element with id ${elId} not found`);
        continue;
      }
      const root = ReactDOM.createRoot(el);
      const reactEl = React.createElement(script.binding, instance.params);
      root.render(reactEl);
    }
  }
}

Config

Returns an OptionsSetter that can be used to set build options for the batch.

These are mostly the same as for js.Build, but note that:

  • targetPath is set automatically (there may be multiple outputs).
  • format must be esm, currently the only format supporting code splitting.
  • params will be available in the @params/config namespace in the scripts. This way you can import both the script or runner params and the config params with:
import * as params from "@params";
import * as config from "@params/config";

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):

{{ with js.Batch "js/mybatch" }}
  {{ with .Config }}
       {{ .SetOptions (dict
        "target" "es2023"
        "format" "esm"
        "jsx" "automatic"
        "loaders" (dict ".png" "dataurl")
        "minify" true
        "params" (dict "param1" "value1")
        )
      }}
  {{ end }}
{{ end }}

Options

Build options

format
(string) Currently only esm is supported in ESBuild’s code splitting.
params
(mapslice) 可以在 JS 文件中作為 JSON 導入的參數,例如:
{{ $js := resources.Get "js/main.js" | js.Build (dict "params" (dict "api" "https://example.org/api")) }}

然後在您的 JS 文件中:

import * as params from '@params';

請注意,這適用於小型數據集,例如配置設置。對於較大數據集,請將文件放入/掛載到 assets 並直接導入。

minify
(bool) 是否讓 js.Build 處理壓縮。
loaders
New in v0.140.0
(map) 為給定文件類型配置加載器允許您使用 import 語句或 require 調用加載該文件類型。例如,將 .png 文件擴展名配置為使用數據 URL 加載器意味著導入 .png 文件會為您提供包含該圖像內容的數據 URL。可用的加載器包括 nonebase64binarycopycssdataurldefaultemptyfileglobal-cssjsjsonjsxlocal-csstexttstsx。請參閱 https://esbuild.github.io/api/#loader
inject
(slice) 此選項允許您自動將全局變量替換為來自另一個文件的導入。路徑名必須相對於 assets。請參閱 https://esbuild.github.io/api/#inject
shims
(map) 此選項允許將組件替換為另一個組件。一個常見的用例是在生產環境中從 CDN 加載依賴項(如 React)(使用 shims),但在開發期間使用完整的捆綁 node_modules 依賴項運行:
{{ $shims := dict "react" "js/shims/react.js"  "react-dom" "js/shims/react-dom.js" }}
{{ $js = $js | js.Build dict "shims" $shims }}

shim 文件可能如下所示:

// js/shims/react.js
module.exports = window.React;
// js/shims/react-dom.js
module.exports = window.ReactDOM;

使用上述內容,這些導入應該在兩種情況下都有效:

import * as React from 'react';
import * as ReactDOM from 'react-dom/client';
target
(string) 語言目標。其中之一:es5es2015es2016es2017es2018es2019es2020es2021es2022es2023es2024esnext。默認為 esnext
platform
New in v0.140.0
(string) 其中之一 browsernodeneutral。默認為 browser。請參閱 https://esbuild.github.io/api/#platform
externals
(slice) 外部依賴項。使用此選項可以修剪您知道永遠不會執行的依賴項。請參閱 https://esbuild.github.io/api/#external
defines
(map) 此選項允許您定義一組在構建時執行的字符串替換。它必須是一個映射,其中每個鍵將被其值替換。
{{ $defines := dict "process.env.NODE_ENV" `"development"` }}
drop
New in v0.144.0
(string) 在構建之前編輯源代碼以刪除某些構造:其中之一 debuggerconsole
請參閱 https://esbuild.github.io/api/#drop
sourceMap
(string) 是否從 esbuild 生成 inlinelinkedexternal 源映射。Linked 和 external 源映射將寫入目標目錄,文件名為輸出文件名 + “.map”。當使用 linked 時,sourceMappingURL 也將寫入輸出文件。默認情況下,不創建源映射。請注意,linked 選項是在 Hugo 0.140.0 中添加的。
sourcesContent
New in v0.140.0
(bool) 是否在源映射中包含源文件的內容。默認情況下,這是 true
JSX
(string) 如何處理/轉換 JSX 語法。其中之一:transformpreserveautomatic。默認為 transform。特別是,automatic 轉換是在 React 17+ 中引入的,將自動導入必要的 JSX 輔助函數。請參閱 https://esbuild.github.io/api/#jsx
JSXImportSource
(string) 自動導入其 JSX 輔助函數的庫。這僅在 JSX 設置為 automatic 時有效。指定的庫需要通過 npm 安裝並公開某些導出。請參閱 https://esbuild.github.io/api/#jsx-import-source

JSXJSXImportSource 的組合對於您想使用非 React JSX 庫(如 Preact)很有用,例如:

{{ $js := resources.Get "js/main.jsx" | js.Build (dict "JSX" "automatic" "JSXImportSource" "preact") }}

使用上述內容,您可以使用 Preact 組件和 JSX,而無需每次都手動導入 hFragment

import { render } from 'preact';

const App = () => <>Hello world!</>;

const container = document.getElementById('app');
if (container) render(<App />, container);

Script options

resource
The resource to build. This can be a file resource or a virtual resource.
export
The export to bind the runner to. Set it to * to export the entire namespace. Default is default for runner scripts and * for other scripts.
importContext
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.
params
A map of parameters that will be passed to the script as JSON. These gets bound to the @params namespace:
import * as params from '@params';

Params options

params
A map of parameters that will be passed to the script as JSON.

Import context

Hugo will, by default, first try to resolve any import in assets 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.

{{ $common := resources.Match "/js/headlessui/*.*" }}
{{ $importContext := (slice $.Page ($common.Mount "/js/headlessui" ".")) }}

You can pass any object that implements Resource.Get. Pass a slice to set multiple contexts.

The example above uses Resources.Mount to resolve a directory inside assets relative to the page bundle.

OptionsSetter

An OptionsSetter is a special object that is returned once only. This means that you should wrap it with with:

{{ with .Script "myscript" }}
    {{ .SetOptions (dict "resource" (resources.Get "myscript.js"))}}
{{ end }}

Build

The Build method returns an object with the following structure:

Each Resource will be of media type application/javascript or text/css.

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:

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.

See this discussion for more.

{{ $group := .group }}
{{ with (templates.Defer (dict "key" $group "data" $group )) }}
  {{ with (js.Batch "js/mybatch") }}
    {{ with .Build }}
      {{ with index .Groups $ }}
        {{ range . }}
          {{ $s := . }}
          {{ if eq $s.MediaType.SubType "css" }}
            <link href="{{ $s.RelPermalink }}" rel="stylesheet" />
          {{ else }}
            <script src="{{ $s.RelPermalink }}" type="module"></script>
          {{ end }}
        {{ end }}
      {{ end }}
  {{ end }}
{{ end }}

Known Issues

In the official documentation for ESBuild’s code splitting, there’s a warning note in the header. The two issues are:

  • esm is currently the only implemented output format. This means that it will not work for very old browsers. See caniuse.
  • There’s a known import ordering issue.

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:

  1. Undefined execution order of imports, see this comment
  2. Only one execution order of imports, see this comment

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.

import './lib2.js';
import './lib1.js';

console.log('entrypoints-workaround.js');

Last updated: January 1, 0001
Improve this page