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 `loaders`
107 : (`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:
108
109 - `css`: Processes the file as a CSS file
110 - `dataurl`: Embeds the file as a base64-encoded data URL
111 - `empty`: Excludes the file from the bundle
112 - `file`: Copies the file to the output directory and rewrites the URL
113 - `text`: Loads the file content as a string
114
115 See [details][esb loader].
116
117 ```go-html-template
118 {{ $opts := dict "loaders" (dict ".png" "dataurl" ".svg" "dataurl") }}
119 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
120 ```
121
122 `mainFields`
123 : (`[]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].
124
125 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.
126
127 ```go-html-template
128 {{ $opts := dict "mainFields" (slice "css" "style" "main") }}
129 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
130 ```
131
132 `minify`
133 : (`bool`) Whether to minify the generated CSS code. Default is `false`. See [details][esb minify].
134
135 ```go-html-template
136 {{ $opts := dict "minify" true }}
137 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
138 ```
139
140 `sourceMap`
141 : (`string`) The type of source map to generate. One of `external`, `inline`, `linked`, or `none`. Default is `none`. See [details][esb sourcemap].
142
143 ```go-html-template
144 {{ $opts := dict "sourceMap" "linked" }}
145 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
146 ```
147
148 `sourcesContent`
149 : (`bool`) Whether to include the content of the source files in the source map. Default is `true`. See [details][esb sourcesContent].
150
151 ```go-html-template
152 {{ $opts := dict "sourceMap" "linked" "sourcesContent" false }}
153 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
154 ```
155
156 `target`
157 : (`[]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].
158
159 ```go-html-template
160 {{ $target := slice "chrome115" "edge115" "firefox116" "ios16.4" "opera101" "safari16.4" }}
161 {{ $opts := dict "target" $target }}
162 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
163 ```
164
165 In the example above, the target environment is roughly equivalent to the [browserlist][] "baseline widely available" profile as of March 2026.
166
167 `targetPath`
168 : (`string`) The path to the generated CSS file, relative to the project's [`publishDir`][]. If unset, this defaults to the asset's original path with a `.css` extension.
169
170 ```go-html-template
171 {{ $opts := dict "targetPath" "css/styles.css" }}
172 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
173 ```
174
175 `vars`
176 : {{< new-in 0.160.0 />}}
177 : (`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.
178
179 ```go-html-template
180 {{ $vars := dict
181 "font-family" "\"Times New Roman\", Times, serif"
182 "font-size" "24px"
183 "primary-color" "blue"
184 }}
185 {{ $opts := dict "vars" $vars }}
186 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
187 ```
188
189 In the example above, using the identifier in your CSS allows you to access the values using standard CSS variable syntax.
190
191 ```css
192 @import 'hugo:vars';
193
194 .element {
195 color: var(--primary-color);
196 font-family: var(--font-family);
197 font-size: var(--font-size);
198 }
199 ```
200
201 The above produces output equivalent to:
202
203 ```css
204 :root {
205 --font-family:
206 "Times New Roman",
207 Times,
208 serif;
209 --font-size: 24px;
210 --primary-color: blue;
211 }
212
213 .element {
214 color: var(--primary-color);
215 font-family: var(--font-family);
216 font-size: var(--font-size);
217 }
218 ```
219
220 {{< new-in 0.161.0 />}}
221
222 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.
223
224 ```go-html-template
225 {{ $vars := dict
226 "font-family" "\"Times New Roman\", Times, serif"
227 "font-size" "24px"
228 "primary-color" "blue"
229 "mobile" (dict
230 "font-size" "12px"
231 "primary-color" "red"
232 )
233 }}
234 {{ $opts := dict "vars" $vars }}
235 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
236 ```
237
238 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.
239
240 ```css
241 @import 'hugo:vars';
242 @import 'hugo:vars/mobile' (max-width: 650px);
243
244 body {
245 background-color: var(--primary-color);
246 font-family: var(--font-family);
247 }
248 ```
249
250 The above produces output equivalent to:
251
252 ```css
253 :root {
254 --font-family: "Times New Roman", Times, serif;
255 --font-size: 24px;
256 --primary-color: blue;
257 }
258
259 @media (max-width: 650px) {
260 :root {
261 --font-size: 12px;
262 --primary-color: red;
263 }
264 }
265
266 body {
267 background-color: var(--primary-color);
268 font-family: var(--font-family);
269 }
270 ```
271
272 The `vars` option is useful for setting CSS variables within your project configuration.
273
274 {{< code-toggle file=hugo >}}
275 [params.theme.style]
276 font-family = '"Times New Roman", Times, serif'
277 font-size = '24px'
278 primary-color = 'blue'
279
280 [params.theme.style.mobile]
281 font-size = '12px'
282 primary-color = 'red'
283 {{< /code-toggle >}}
284
285 ```go-html-template
286 {{ $opts := dict "vars" site.Params.theme.style }}
287 {{ $r := resources.Get "css/main.css" | css.Build $opts }}
288 ```
289
290 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.
291
292 > [!NOTE]
293 > 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).
294
295 ## Example
296
297 The example below uses several of the [options](#options) described above to bundle, transform, and minify CSS code.
298
299 ```go-html-template {file="layouts/_partials/css.html" copy=true}
300 {{ with resources.Get "css/main.css" }}
301 {{ $opts := dict
302 "loaders" (dict ".png" "dataurl" ".svg" "dataurl")
303 "minify" (cond hugo.IsDevelopment false true)
304 "sourceMap" (cond hugo.IsDevelopment "linked" "none")
305 "target" (slice "chrome115" "edge115" "firefox116" "ios16.4" "opera101" "safari16.4")
306 "targetPath" "css/styles.css"
307 }}
308 {{ with . | css.Build $opts }}
309 {{ if hugo.IsDevelopment }}
310 <link rel="stylesheet" href="{{ .RelPermalink }}">
311 {{ else }}
312 {{ with . | fingerprint }}
313 <link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous">
314 {{ end }}
315 {{ end }}
316 {{ end }}
317 {{ end }}
318 ```
319
320 Using the options above, Hugo does the following:
321
322 - Embeds PNG and SVG images as data URLs in the generated CSS code
323 - Minifies the output in production but not in development
324 - Generates an external source map in development but not in production
325 - Transforms syntax for compatibility with the targeted browser versions
326 - Adds vendor prefixes for compatibility with the targeted browser versions
327 - Publishes the generated CSS code to `css/styles.css`
328 - In production, adds an SRI hash and inserts a file hash into the filename
329
330 ## Common patterns
331
332 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.
333
334 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.
335
336 ### Files in the assets directory
337
338 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.
339
340 ```css {file="/assets/css/main.css"}
341 /* A bare path */
342 @import "variables.css";
343
344 /* A relative path */
345 @import "./theme.css";
346 @import "../layout.css";
347
348 /* A root-relative path */
349 @import "/css/grid.css";
350
351 /* A url() reference using the same resolution logic */
352 .logo { background: url("/images/logo.svg"); }
353 ```
354
355 ### Node packages
356
357 When referencing a Node package by name, Hugo consults the `package.json` file within that package to find the entry point.
358
359 ```css {file="/assets/css/main.css"}
360 @import "bootstrap";
361 ```
362
363 ### Files within a package
364
365 To reference a specific file within a Node package, provide the path starting with the package name.
366
367 ```css {file="/assets/css/main.css"}
368 @import "bootstrap/dist/css/bootstrap-grid.css";
369 ```
370
371 [`css.Quoted`]: /functions/css/quoted/
372 [`evanw/esbuild`]: https://github.com/evanw/esbuild
373 [`publishDir`]: /configuration/all/#publishdir
374 [browserlist]: https://browsersl.ist
375 [esb external]: https://esbuild.github.io/api/#external
376 [esb loader]: https://esbuild.github.io/api/#loader
377 [esb mainfields]: https://esbuild.github.io/api/#main-fields
378 [esb minify]: https://esbuild.github.io/api/#minify
379 [esb sourcemap]: https://esbuild.github.io/api/#sourcemap
380 [esb sourcesContent]: https://esbuild.github.io/api/#sources-content
381 [esb target]: https://esbuild.github.io/api/#target