Debian Codegraph @

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

raw
1 ---
2 title: css.Build
3 description: Bundle, transform, and minify CSS resources.
4 categories: []
5 keywords: []
6 params:
7 functions_and_methods:
8 aliases: []
9 returnType: resource.Resource
10 signatures: ['css.Build [OPTIONS] RESOURCE']
11 ---
12
13 {{< new-in 0.158.0 />}}
14
15 > [!NOTE]
16 > The `css.Build` function is backed by the [`evanw/esbuild`][] package, providing a mature, high-performance foundation for bundling, transformation, and minification.
17
18 Use the `css.Build` function to:
19
20 - Recursively replace `@import` statements in CSS files with the content of the imported files
21 - Transform syntax for browser compatibility
22 - Apply vendor prefixes for browser compatibility
23 - Minify the bundled CSS code
24 - Create a source map
25
26 If an `@import` statement includes a media query, a feature query, or a cascade layer assignment, the function wraps the imported content in the corresponding `@media`, `@supports`, or `@layer` rule.
27
28 ## Usage
29
30 In this example, Hugo bundles the local files referenced by `@import` statements to create and publish a single resource with inline content.
31
32 ```tree
33 assets/
34 └── css/
35 ├── components/
36 │ ├── a.css
37 │ └── b.css
38 └── main.css
39 ```
40
41 ```css {file="assets/css/main.css" copy=true}
42 @import url('https://cdn.jsdelivr.net/npm/the-new-css-reset/css/reset.min.css');
43
44 @import './components/a.css';
45 @import './components/b.css';
46
47 .c {color: blue; }
48 ```
49
50 ```css {file="assets/css/components/a.css" copy=true}
51 .a { color: red; }
52 ```
53
54 ```css {file="assets/css/components/b.css" copy=true}
55 .b { color: green; }
56 ```
57
58 ```go-html-template {file="layouts/_partials/css.html" copy=true}
59 {{ with resources.Get "css/main.css" | css.Build }}
60 {{ if hugo.IsDevelopment }}
61 <link rel="stylesheet" href="{{ .RelPermalink }}">
62 {{ else }}
63 {{ with . | fingerprint }}
64 <link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous">
65 {{ end }}
66 {{ end }}
67 {{ end }}
68 ```
69
70 ```go-html-template {file="layouts/baseof.html" copy=true}
71 {{ partialCached "css.html" . }}
72 ```
73
74 The generated CSS code:
75
76 ```css {file="public/css/main.css"}
77 @import "https://cdn.jsdelivr.net/npm/the-new-css-reset/css/reset.min.css";
78
79 .a {
80 color: red;
81 }
82
83 .b {
84 color: green;
85 }
86
87 .c {
88 color: blue;
89 }
90 ```
91
92 To minify the generated CSS code, use the [`minify`](#minify) option as described below.
93
94 ## Options
95
96 The `css.Build` function accepts an options map to fine-tune bundling, minification, and browser compatibility.
97
98 `externals`
99 : (`[]string`) A slice of path patterns to exclude from bundling. The `@import` statements for these patterns remain as-is in the generated CSS code. See [details][esb external].
100
101 ```go-html-template
102 {{ $opts := dict "externals" (slice "./exclude-these/*" "./exclude-these-too/*") }}
103 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
104 ```
105
106 `importContext`
107 : {{< new-in 0.165.0 />}}
108 : (`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 `@import` statement, before falling back to the file system.
109
110 `loaders`
111 : (`map`) A map of file extensions to loader types. This determines how files with a given extension are processed during bundling. By default, Hugo uses the `css` loader for `.css` files and the `file` loader for all others. Common loaders include:
112
113 - `css`: Processes the file as a CSS file
114 - `dataurl`: Embeds the file as a base64-encoded data URL
115 - `empty`: Excludes the file from the bundle
116 - `file`: Copies the file to the output directory and rewrites the URL
117 - `text`: Loads the file content as a string
118
119 See [details][esb loader].
120
121 ```go-html-template
122 {{ $opts := dict "loaders" (dict ".png" "dataurl" ".svg" "dataurl") }}
123 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
124 ```
125
126 `mainFields`
127 : (`[]string`) A prioritized slice of field names in a `package.json` file that determine the CSS entry point of a Node package. The default is `["style", "main"]`. See [details][esb mainfields].
128
129 When an `@import` statement references a Node package, Hugo consults the metadata in the `package.json` file to find the stylesheet. Use this option to support packages that define a CSS entry point using non-standard fields.
130
131 ```go-html-template
132 {{ $opts := dict "mainFields" (slice "css" "style" "main") }}
133 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
134 ```
135
136 `minify`
137 : (`bool`) Whether to minify the generated CSS code. Default is `false`. See [details][esb minify].
138
139 ```go-html-template
140 {{ $opts := dict "minify" true }}
141 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
142 ```
143
144 `sourceMap`
145 : (`string`) The type of source map to generate. One of `external`, `inline`, `linked`, or `none`. Default is `none`. See [details][esb sourcemap].
146
147 ```go-html-template
148 {{ $opts := dict "sourceMap" "linked" }}
149 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
150 ```
151
152 `sourcesContent`
153 : (`bool`) Whether to include the content of the source files in the source map. Default is `true`. See [details][esb sourcesContent].
154
155 ```go-html-template
156 {{ $opts := dict "sourceMap" "linked" "sourcesContent" false }}
157 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
158 ```
159
160 `target`
161 : (`[]string`) The target environment for the generated CSS code. This determines which syntax transformations to perform and which vendor prefixes to apply. If unset, no transformations or prefixing are performed. Each element consists of a target name and a version number. Supported targets include `chrome`, `edge`, `firefox`, `ie`, `ios`, `opera`, and `safari`. See [details][esb target].
162
163 ```go-html-template
164 {{ $target := slice "chrome115" "edge115" "firefox116" "ios16.4" "opera101" "safari16.4" }}
165 {{ $opts := dict "target" $target }}
166 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
167 ```
168
169 In the example above, the target environment is roughly equivalent to the [browserlist][] "baseline widely available" profile as of March 2026.
170
171 `targetPath`
172 : (`string`) The target path of the resource, relative to the [`publishDir`][]. If unset, the target path defaults to the asset's original path with a `.css` extension.
173
174 ```go-html-template
175 {{ $opts := dict "targetPath" "css/styles.css" }}
176 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
177 ```
178
179 `vars`
180 : {{< new-in 0.160.0 />}}
181 : (`map`) A map of key-value pairs used to generate CSS variables. The `css.Build` function injects these variables into the stylesheet when it encounters the `hugo:vars` internal identifier within an `@import` statement.
182
183 ```go-html-template
184 {{ $vars := dict
185 "font-family" "\"Times New Roman\", Times, serif"
186 "font-size" "24px"
187 "primary-color" "blue"
188 }}
189 {{ $opts := dict "vars" $vars }}
190 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
191 ```
192
193 In the example above, using the identifier in your CSS allows you to access the values using standard CSS variable syntax.
194
195 ```css
196 @import 'hugo:vars';
197
198 .element {
199 color: var(--primary-color);
200 font-family: var(--font-family);
201 font-size: var(--font-size);
202 }
203 ```
204
205 The above produces output equivalent to:
206
207 ```css
208 :root {
209 --font-family:
210 "Times New Roman",
211 Times,
212 serif;
213 --font-size: 24px;
214 --primary-color: blue;
215 }
216
217 .element {
218 color: var(--primary-color);
219 font-family: var(--font-family);
220 font-size: var(--font-size);
221 }
222 ```
223
224 {{< new-in 0.161.0 />}}
225
226 The map may optionally contain nested maps. Each nested map is exposed as a separate `hugo:vars/<name>` namespace, where `<name>` is the key of the nested map (lowercased). Top-level scalar values and nested maps are independent. A top-level `@import 'hugo:vars'` only includes scalar values, while `@import 'hugo:vars/<name>'` only includes the scalars from the named nested map.
227
228 ```go-html-template
229 {{ $vars := dict
230 "font-family" "\"Times New Roman\", Times, serif"
231 "font-size" "24px"
232 "primary-color" "blue"
233 "mobile" (dict
234 "font-size" "12px"
235 "primary-color" "red"
236 )
237 }}
238 {{ $opts := dict "vars" $vars }}
239 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
240 ```
241
242 Because nested imports follow the same rules as regular `@import` statements, you can attach a media query, feature query, or cascade layer assignment to a `hugo:vars/<name>` import.
243
244 ```css
245 @import 'hugo:vars';
246 @import 'hugo:vars/mobile' (max-width: 650px);
247
248 body {
249 background-color: var(--primary-color);
250 font-family: var(--font-family);
251 }
252 ```
253
254 The above produces output equivalent to:
255
256 ```css
257 :root {
258 --font-family: "Times New Roman", Times, serif;
259 --font-size: 24px;
260 --primary-color: blue;
261 }
262
263 @media (max-width: 650px) {
264 :root {
265 --font-size: 12px;
266 --primary-color: red;
267 }
268 }
269
270 body {
271 background-color: var(--primary-color);
272 font-family: var(--font-family);
273 }
274 ```
275
276 The `vars` option is useful for setting CSS variables within your project configuration.
277
278 {{< code-toggle file=hugo >}}
279 [params.theme.style]
280 font-family = '"Times New Roman", Times, serif'
281 font-size = '24px'
282 primary-color = 'blue'
283
284 [params.theme.style.mobile]
285 font-size = '12px'
286 primary-color = 'red'
287 {{< /code-toggle >}}
288
289 ```go-html-template
290 {{ $opts := dict "vars" site.Params.theme.style }}
291 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
292 ```
293
294 When passing a `vars` map to the `css.Build` function, you can use the [`css.Quoted`][] function to explicitly indicate that a value must be treated as a quoted string, most commonly for `font-family` names or the `content` property.
295
296 > [!NOTE]
297 > If you're using TailwindCSS and want to use the `vars` option to inject CSS variables, see [this section in the TailwindCSS documentation](./TailwindCSS.md#inject-css-variables).
298
299 ## Example
300
301 The example below uses several of the [options](#options) described above to bundle, transform, and minify CSS code.
302
303 ```go-html-template {file="layouts/_partials/css.html" copy=true}
304 {{ with resources.Get "css/main.css" }}
305 {{ $opts := dict
306 "loaders" (dict ".png" "dataurl" ".svg" "dataurl")
307 "minify" (cond hugo.IsDevelopment false true)
308 "sourceMap" (cond hugo.IsDevelopment "linked" "none")
309 "target" (slice "chrome115" "edge115" "firefox116" "ios16.4" "opera101" "safari16.4")
310 "targetPath" "css/styles.css"
311 }}
312 {{ with . | css.Build $opts }}
313 {{ if hugo.IsDevelopment }}
314 <link rel="stylesheet" href="{{ .RelPermalink }}">
315 {{ else }}
316 {{ with . | fingerprint }}
317 <link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous">
318 {{ end }}
319 {{ end }}
320 {{ end }}
321 {{ end }}
322 ```
323
324 Using the options above, Hugo does the following:
325
326 - Embeds PNG and SVG images as data URLs in the generated CSS code
327 - Minifies the output in production but not in development
328 - Generates an external source map in development but not in production
329 - Transforms syntax for compatibility with the targeted browser versions
330 - Adds vendor prefixes for compatibility with the targeted browser versions
331 - Publishes the generated CSS code to `css/styles.css`
332 - In production, adds an SRI hash and inserts a file hash into the filename
333
334 ## Artifacts
335
336 {{< new-in 0.165.0 />}}
337
338 In addition to the main output, Hugo may publish other files as part of the build:
339
340 - Files copied to the output directory by the `file` loader, such as fonts and images
341 - A source map, when the [`sourceMap`](#sourcemap) option is `external` or `linked`
342
343 The `Data` method on the returned resource exposes these files as a slice of artifacts, where each artifact provides `MediaType`, `Permalink`, and `RelPermalink` methods.
344
345 For example, to render preload links for font files published by the build:
346
347 ```go-html-template {file="layouts/_partials/css.html"}
348 {{ with resources.Get "css/main.css" }}
349 {{ with . | css.Build }}
350 {{ range .Data.Artifacts }}
351 {{ if eq .MediaType.MainType "font" }}
352 <link rel="preload" href="{{ .RelPermalink }}" as="font" type="{{ .MediaType.Type }}" crossorigin>
353 {{ end }}
354 {{ end }}
355 <link rel="stylesheet" href="{{ .RelPermalink }}">
356 {{ end }}
357 {{ end }}
358 ```
359
360 ## Common patterns
361
362 The examples below cover the most frequent use cases for referencing resources within your project or within Node packages. These patterns apply to both `@import` statements and the `url()` functional notation used for images and fonts.
363
364 All resources referenced by a path, including images, fonts, and stylesheets, must reside in the `assets` directory of the [unified file system](g), or within a Node package.
365
366 ### Files in the assets directory
367
368 To include a stylesheet from the `assets` directory, you can use a bare path, a relative path, or a root-relative path. When you use a bare path, Hugo searches relative to the current stylesheet, then relative to the `assets` directory.
369
370 ```css {file="/assets/css/main.css"}
371 /* A bare path */
372 @import "variables.css";
373
374 /* A relative path */
375 @import "./theme.css";
376 @import "../layout.css";
377
378 /* A root-relative path */
379 @import "/css/grid.css";
380
381 /* A url() reference using the same resolution logic */
382 .logo { background: url("/images/logo.svg"); }
383 ```
384
385 ### Node packages
386
387 When referencing a Node package by name, Hugo consults the `package.json` file within that package to find the entry point.
388
389 ```css {file="/assets/css/main.css"}
390 @import "bootstrap";
391 ```
392
393 ### Files within a package
394
395 To reference a specific file within a Node package, provide the path starting with the package name.
396
397 ```css {file="/assets/css/main.css"}
398 @import "bootstrap/dist/css/bootstrap-grid.css";
399 ```
400
401 [`css.Quoted`]: /functions/css/quoted/
402 [`evanw/esbuild`]: https://github.com/evanw/esbuild
403 [`publishDir`]: /configuration/all/#publishdir
404 [browserlist]: https://browsersl.ist
405 [esb external]: https://esbuild.github.io/api/#external
406 [esb loader]: https://esbuild.github.io/api/#loader
407 [esb mainfields]: https://esbuild.github.io/api/#main-fields
408 [esb minify]: https://esbuild.github.io/api/#minify
409 [esb sourcemap]: https://esbuild.github.io/api/#sourcemap
410 [esb sourcesContent]: https://esbuild.github.io/api/#sources-content
411 [esb target]: https://esbuild.github.io/api/#target