Debian Codegraph @

docs/content/en/functions/js/Build.md

raw
1 ---
2 title: js.Build
3 description: Returns a resource created by bundling, transpiling, tree shaking, and minifying the given JavaScript resource.
4 categories: []
5 keywords: []
6 params:
7 functions_and_methods:
8 aliases: []
9 returnType: resource.Resource
10 signatures: ['js.Build [OPTIONS] RESOURCE']
11 ---
12
13 > [!NOTE]
14 > The `js.Build` function is backed by the [`evanw/esbuild`][] package, providing a mature, high-performance foundation for bundling, transformation, and minification.
15
16 Use the `js.Build` function to:
17
18 - Bundle
19 - Transpile (TypeScript and JSX)
20 - Tree shake
21 - Minify
22 - Create source maps
23
24 ```go-html-template
25 {{ with resources.Get "js/main.js" }}
26 {{$opts := dict
27 "minify" (cond hugo.IsDevelopment false true)
28 "sourceMap" (cond hugo.IsDevelopment "linked" "none")
29 }}
30 {{ with . | js.Build $opts }}
31 {{ if hugo.IsDevelopment }}
32 <script src="{{ .RelPermalink }}"></script>
33 {{ else }}
34 {{ with . | fingerprint }}
35 <script src="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous"></script>
36 {{ end }}
37 {{ end }}
38 {{ end }}
39 {{ end }}
40 ```
41
42 ## Options
43
44 The `js.Build` function accepts an options map.
45
46 `format`
47 : (`string`) The output format. One of: `iife`, `cjs`, `esm`. Default is `iife`, a self-executing function, suitable for inclusion as a `<script>` tag.
48
49 `importContext`
50 : {{< new-in 0.165.0 />}}
51 : (`resource.ResourceGetter`) A [resource getter](g) to use when resolving import statements. Hugo searches this context first, matching by the path as written in the statement, before falling back to the file system.
52
53 `targetPath`
54 : (`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.
55
56 {{% include "/_common/functions/js/options.md" %}}
57
58 ## Import from the assets directory
59
60 `js.Build` has full support for Hugo's [unified file system](g). You can see some simple examples in this [test project][], but in short this means that you can do this:
61
62 ```js
63 import { hello } from 'my/module';
64 ```
65
66 And it will resolve to the top-most `index.{js,ts,tsx,jsx}` inside `assets/my/module` in the layered file system.
67
68 ```js
69 import { hello3 } from 'my/module/hello3';
70 ```
71
72 Will resolve to `hello3.{js,ts,tsx,jsx}` inside `assets/my/module`.
73
74 Any imports starting with `.` are resolved relative to the current file:
75
76 ```js
77 import { hello4 } from './lib';
78 ```
79
80 For other files (e.g. `JSON`, `CSS`) you need to use the relative path including any extension, e.g:
81
82 ```js
83 import * as data from 'my/module/data.json';
84 ```
85
86 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 build`.
87
88 Also note the new `params` option that can be passed from template to your JS files, e.g.:
89
90 ```go-html-template
91 {{ $js := resources.Get "js/main.js" | js.Build (dict "params" (dict "api" "https://example.org/api")) }}
92 ```
93
94 And then in your JS file:
95
96 ```js
97 import * as params from '@params';
98 ```
99
100 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][].
101
102 ## Node.js dependencies
103
104 Use the `js.Build` function to include Node dependencies.
105
106 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 build`.
107
108 The start directory for resolving npm packages (aka. packages that live inside a `node_modules` directory) is always the main project directory.
109
110 > [!NOTE]
111 > 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.
112
113 ## Artifacts
114
115 {{< new-in 0.165.0 />}}
116
117 In addition to the main output, Hugo may publish other files as part of the build:
118
119 - Files copied to the output directory by esbuild's `file` loader, such as fonts and images
120 - A source map, when the `sourceMap` option is `external` or `linked`
121
122 The `Data` method on the returned resource exposes these files as a slice of artifacts, where each artifact provides `MediaType`, `Permalink`, and `RelPermalink` methods.
123
124 For example, to render preload links for image files published by the build:
125
126 ```go-html-template
127 {{ with resources.Get "js/main.js" }}
128 {{ with . | js.Build }}
129 {{ range .Data.Artifacts }}
130 {{ if eq .MediaType.MainType "image" }}
131 <link rel="preload" href="{{ .RelPermalink }}" as="image" type="{{ .MediaType.Type }}">
132 {{ end }}
133 {{ end }}
134 <script src="{{ .RelPermalink }}"></script>
135 {{ end }}
136 {{ end }}
137 ```
138
139 ## Examples
140
141 ```go-html-template
142 {{ $built := resources.Get "js/index.js" | js.Build "main.js" }}
143 ```
144
145 Or with options:
146
147 ```go-html-template
148 {{ $externals := slice "react" "react-dom" }}
149 {{ $defines := dict "process.env.NODE_ENV" `"development"` }}
150
151 {{ $opts := dict "targetPath" "main.js" "externals" $externals "defines" $defines }}
152 {{ $built := resources.Get "scripts/main.js" | js.Build $opts }}
153 <script src="{{ $built.RelPermalink }}" defer></script>
154 ```
155
156 [`esbuild`]: https://esbuild.github.io/
157 [`evanw/esbuild`]: https://github.com/evanw/esbuild
158 [`hugo mod npm pack`]: /commands/hugo_mod_npm_pack/
159 [test project]: https://github.com/gohugoio/hugoTestProjectJSModImports
160 [turn it off]: /configuration/build/#nojsconfiginassets