HUGO
Menu
GitHub 87548 stars Mastodon

js.Build

Bundle, transpile, tree shake, and minify JavaScript resources.

Syntax

js.Build [OPTIONS] RESOURCE

Returns

resource.Resource

The js.Build function uses the evanw/esbuild package to:

  • Bundle
  • Transpile (TypeScript and JSX)
  • Tree shake
  • Minify
  • Create source maps
{{ with resources.Get "js/main.js" }}
  {{$opts := dict
    "minify" (not hugo.IsDevelopment)
    "sourceMap" (cond hugo.IsDevelopment "external" "")
    "targetPath" "js/main.js"
  }}
  {{ with . | js.Build $opts }}
    {{ if hugo.IsDevelopment }}
      <script src="{{ .RelPermalink }}"></script>
    {{ else }}
      {{ with . | fingerprint }}
        <script src="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous"></script>
      {{ end }}
    {{ end }}
  {{ end }}
{{ end }}

Options

targetPath
(string) If not set, the source path will be used as the base target path. Note that the target path’s extension may change if the target MIME type is different, e.g. when the source is TypeScript.
format
(string) The output format. One of: iife, cjs, esm. Default is iife, a self-executing function, suitable for inclusion as a <script> tag.
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);

Import JS code from the assets directory

js.Build has full support for the virtual union file system in Hugo Modules. You can see some simple examples in this test project, but in short this means that you can do this:

import { hello } from 'my/module';

And it will resolve to the top-most index.{js,ts,tsx,jsx} inside assets/my/module in the layered file system.

import { hello3 } from 'my/module/hello3';

Will resolve to hello3.{js,ts,tsx,jsx} inside assets/my/module.

Any imports starting with . are resolved relative to the current file:

import { hello4 } from './lib';

For other files (e.g. JSON, CSS) you need to use the relative path including any extension, e.g:

import * as data from 'my/module/data.json';

Any imports in a file outside assets or that does not resolve to a component inside assets will be resolved by ESBuild with the project directory as the resolve directory (used as the starting point when looking for node_modules etc.). Also see hugo mod npm pack. If you have any imported npm dependencies in your project, you need to make sure to run npm install before you run hugo.

Also note the new params option that can be passed from template to your JS files, e.g.:

{{ $js := resources.Get "js/main.js" | js.Build (dict "params" (dict "api" "https://example.org/api")) }}

And then in your JS file:

import * as params from '@params';

Hugo will, by default, generate a assets/jsconfig.json file that maps the imports. This is useful for navigation/intellisense help inside code editors, but if you don’t need/want it, you can turn it off.

Node.js dependencies

Use the js.Build function to include Node.js dependencies.

Any imports in a file outside assets or that does not resolve to a component inside assets will be resolved by esbuild with the project directory as the resolve directory (used as the starting point when looking for node_modules etc.). Also see hugo mod npm pack. If you have any imported npm dependencies in your project, you need to make sure to run npm install before you run hugo.

The start directory for resolving npm packages (aka. packages that live inside a node_modules directory) is always the main project directory.

If you’re developing a theme/component that is supposed to be imported and depends on dependencies inside package.json, we recommend reading about hugo mod npm pack, a tool to consolidate all the npm dependencies in a project.

Examples

{{ $built := resources.Get "js/index.js" | js.Build "main.js" }}

Or with options:

{{ $externals := slice "react" "react-dom" }}
{{ $defines := dict "process.env.NODE_ENV" `"development"` }}

{{ $opts := dict "targetPath" "main.js" "externals" $externals "defines" $defines }}
{{ $built := resources.Get "scripts/main.js" | js.Build $opts }}
<script src="{{ $built.RelPermalink }}" defer></script>

Last updated: January 1, 0001
Improve this page