@esbuild/freebsd-x64
0.28.2 · 8 Aug 2026MIT11.9M / weekRepositoryHomepagenpmAtom feed
113 stable releases, newest first, by release line. Notes are quoted as the maintainers published them.
- 0.19.x
0.19.2
14 Aug 2023Update how CSS nesting is parsed again
CSS nesting syntax has been changed again, and esbuild has been updated to match. Type selectors may now be used with CSS nesting:
.foo { div { color: red; } }Previously this was disallowed in the CSS specification because it's ambiguous whether an identifier is a declaration or a nested rule starting with a type selector without requiring unbounded lookahead in the parser. It has now been allowed because the CSS working group has decided that requiring unbounded lookahead is acceptable after all.
Note that this change means esbuild no longer considers any existing browser to support CSS nesting since none of the existing browsers support this new syntax. CSS nesting will now always be transformed when targeting a browser. This situation will change in the future as browsers add support for this new syntax.
Fix a scope-related bug with
--drop-labels=The recently-released
--drop-labels=feature previously had a bug where esbuild's internal scope stack wasn't being restored properly when a statement with a label was dropped. This could manifest as a tree-shaking issue, although it's possible that this could have also been causing other subtle problems too. The bug has been fixed in this release.Make renamed CSS names unique across entry points
Previously esbuild's generated names for local names in CSS were only unique within a given entry point (or across all entry points when code splitting was enabled). That meant that building multiple entry points with esbuild could result in local names being renamed to the same identifier even when those entry points were built simultaneously within a single esbuild API call. This problem was especially likely to happen with minification enabled. With this release, esbuild will now avoid renaming local names from two separate entry points to the same name if those entry points were built with a single esbuild API call, even when code splitting is disabled.
Update how CSS nesting is parsed again
CSS nesting syntax has been changed again, and esbuild has been updated to match. Type selectors may now be used with CSS nesting:
.foo { div { color: red; } }Previously this was disallowed in the CSS specification because it's ambiguous whether an identifier is a declaration or a nested rule starting with a type selector without requiring unbounded lookahead in the parser. It has now been allowed because the CSS working group has decided that requiring unbounded lookahead is acceptable after all.
Note that this change means esbuild no longer considers any existing browser to support CSS nesting since none of the existing browsers support this new syntax. CSS nesting will now always be transformed when targeting a browser. This situation will change in the future as browsers add support for this new syntax.
Fix a scope-related bug with
--drop-labels=The recently-released
--drop-labels=feature previously had a bug where esbuild's internal scope stack wasn't being restored properly when a statement with a label was dropped. This could manifest as a tree-shaking issue, although it's possible that this could have also been causing other subtle problems too. The bug has been fixed in this release.Make renamed CSS names unique across entry points
Previously esbuild's generated names for local names in CSS were only unique within a given entry point (or across all entry points when code splitting was enabled). That meant that building multiple entry points with esbuild could result in local names being renamed to the same identifier even when those entry points were built simultaneously within a single esbuild API call. This problem was especially likely to happen with minification enabled. With this release, esbuild will now avoid renaming local names from two separate entry points to the same name if those entry points were built with a single esbuild API call, even when code splitting is disabled.
Fix CSS ordering bug with
@layerbefore@importCSS lets you put
@layerrules before@importrules to define the order of layers in a stylesheet. Previously esbuild's CSS bundler incorrectly ordered these after the imported files because before the introduction of cascade layers to CSS, imported files could be bundled by removing the@importrules and then joining files together in the right order. But with@layer, CSS files may now need to be split apart into multiple pieces in the bundle. For example:/* Original code */ @layer start; @import "data:text/css,@layer inner.start;"; @import "data:text/css,@layer inner.end;"; @layer end; /* Old output (with --bundle) */ @layer inner.start; @layer inner.end; @layer start; @layer end; /* New output (with --bundle) */ @layer start; @layer inner.start; @layer inner.end; @layer end;
Unwrap nested duplicate
@mediarulesWith this release, esbuild's CSS minifier will now automatically unwrap duplicate nested
@mediarules:/* Original code */ @media (min-width: 1024px) { .foo { color: red } @media (min-width: 1024px) { .bar { color: blue } } } /* Old output (with --minify) */ @media (min-width: 1024px){.foo{color:red}@media (min-width: 1024px){.bar{color:#00f}}} /* New output (with --minify) */ @media (min-width: 1024px){.foo{color:red}.bar{color:#00f}}These rules are unlikely to be authored manually but may result from using frameworks such as Tailwind to generate CSS.
0.19.1
11 Aug 2023Fix a regression with
baseURLintsconfig.jsonThe previous release moved
tsconfig.jsonpath resolution before--packages=externalchecks to allow thepathsfield intsconfig.jsonto avoid a package being marked as external. However, that reordering accidentally broke the behavior of thebaseURLfield fromtsconfig.json. This release moves these path resolution rules around again in an attempt to allow both of these cases to work.Parse TypeScript type arguments for JavaScript decorators
When parsing JavaScript decorators in TypeScript (i.e. with
experimentalDecoratorsdisabled), esbuild previously didn't parse type arguments. Type arguments will now be parsed starting with this release. For example:@foo<number> @bar<number, string>() class Foo {}Fix glob patterns matching extra stuff at the end
Previously glob patterns such as
./*.jswould incorrectly behave like./*.js*during path matching (also matching.js.mapfiles, for example). This was never intentional behavior, and has now been fixed.
Fix a regression with
baseURLintsconfig.jsonThe previous release moved
tsconfig.jsonpath resolution before--packages=externalchecks to allow thepathsfield intsconfig.jsonto avoid a package being marked as external. However, that reordering accidentally broke the behavior of thebaseURLfield fromtsconfig.json. This release moves these path resolution rules around again in an attempt to allow both of these cases to work.Parse TypeScript type arguments for JavaScript decorators
When parsing JavaScript decorators in TypeScript (i.e. with
experimentalDecoratorsdisabled), esbuild previously didn't parse type arguments. Type arguments will now be parsed starting with this release. For example:@foo<number> @bar<number, string>() class Foo {}Fix glob patterns matching extra stuff at the end
Previously glob patterns such as
./*.jswould incorrectly behave like./*.js*during path matching (also matching.js.mapfiles, for example). This was never intentional behavior, and has now been fixed.Change the permissions of esbuild's generated output files
This release changes the permissions of the output files that esbuild generates to align with the default behavior of node's
fs.writeFileSyncfunction. Since most tools written in JavaScript usefs.writeFileSync, this should make esbuild more consistent with how other JavaScript build tools behave.The full Unix-y details: Unix permissions use three-digit octal notation where the three digits mean "user, group, other" in that order. Within a digit, 4 means "read" and 2 means "write" and 1 means "execute". So 6 == 4 + 2 == read + write. Previously esbuild uses 0644 permissions (the leading 0 means octal notation) but the permissions for
fs.writeFileSyncdefaults to 0666, so esbuild will now use 0666 permissions. This does not necessarily mean that the files esbuild generates will end up having 0666 permissions, however, as there is another Unix feature called "umask" where the operating system masks out some of these bits. If your umask is set to 0022 then the generated files will have 0644 permissions, and if your umask is set to 0002 then the generated files will have 0664 permissions.Fix a subtle CSS ordering issue with
@importand@layerWith this release, esbuild may now introduce additional
@layerrules when bundling CSS to better preserve the layer ordering of the input code. Here's an example of an edge case where this matters:/* entry.css */ @import "a.css"; @import "b.css"; @import "a.css";
/* a.css */ @layer a { body { background: red; } }/* b.css */ @layer b { body { background: green; } }This CSS should set the body background to
green, which is what happens in the browser. Previously esbuild generated the following output which incorrectly sets the body background tored:/* b.css */ @layer b { body { background: green; } } /* a.css */ @layer a { body { background: red; } }This difference in behavior is because the browser evaluates
a.css+b.css+a.css(in CSS, each@importis replaced with a copy of the imported file) while esbuild was only writing outb.css+a.css. The first copy ofa.csswasn't being written out by esbuild for two reasons: 1) bundlers care about code size and try to avoid emitting duplicate CSS and 2) when there are multiple copies of a CSS file, normally only the last copy matters since the last declaration with equal specificity wins in CSS.However,
@layerwas recently added to CSS and for@layerthe first copy matters because layers are ordered using their first location in source code order. This introduction of@layermeans esbuild needs to change its bundling algorithm. An easy solution would be for esbuild to write outa.csstwice, but that would be inefficient. So what I'm going to try to have esbuild do with this release is to write out an abbreviated form of the first copy of a CSS file that only includes the@layerinformation, and then still only write out the full CSS file once for the last copy. So esbuild's output for this edge case now looks like this:/* a.css */ @layer a; /* b.css */ @layer b { body { background: green; } } /* a.css */ @layer a { body { background: red; } }The behavior of the bundled CSS now matches the behavior of the unbundled CSS. You may be wondering why esbuild doesn't just write out
a.cssfirst followed byb.css. That would work in this case but it doesn't work in general because for any rules outside of a@layerrule, the last copy should still win instead of the first copy.Fix a bug with esbuild's TypeScript type definitions
This release fixes a copy/paste error with the TypeScript type definitions for esbuild's JS API:
export interface TsconfigRaw { compilerOptions?: { - baseUrl?: boolean + baseUrl?: string ... } }This fix was contributed
0.19.0
8 Aug 2023Path aliases in
tsconfig.jsonno longer count as packages (#2792, #3003, #3160, #3238)Setting
--packages=externaltells esbuild to make all import paths external when they look like a package path. For example, an import of./foo/baris not a package path and won't be external while an import offoo/baris a package path and will be external. However, thepathsfield intsconfig.jsonallows you to create import paths that look like package paths but that do not resolve to packages. People do not want these paths to count as package paths. So with this release, the behavior of--packages=externalhas been changed to happen after thetsconfig.jsonpath remapping step.Use the
local-cssloader for.module.cssfiles by defaultWith this release the
cssloader is still used for.cssfiles except that.module.cssfiles now use thelocal-cssloader. This is a common convention in the web development community. If you need.module.cssfiles to use thecssloader instead, then you can override this behavior with--loader:.module.css=css.
This release deliberately contains backwards-incompatible changes. To avoid automatically picking up releases like this, you should either be pinning the exact version of
esbuildin yourpackage.jsonfile (recommended) or be using a version range syntax that only accepts patch upgrades such as^0.18.0or~0.18.0. See npm's documentation about semver for more information.Handle import paths containing wildcards (#56, #700, #875, #976, #2221, #2515)
This release introduces wildcards in import paths in two places:
Entry points
You can now pass a string containing glob-style wildcards such as
./src/*.tsas an entry point and esbuild will search the file system for files that match the pattern. This can be used to easily pass esbuild all files with a certain extension on the command line in a cross-platform way. Previously you had to rely on the shell to perform glob expansion, but that is obviously shell-dependent and didn't work at all on Windows. Note that to use this feature on the command line you will have to quote the pattern so it's passed verbatim to esbuild without any expansion by the shell. Here's an example:esbuild --minify "./src/*.ts" --outdir=out
Specifically the
*character will match any character except for the/character, and the/**/character sequence will match a path separator followed by zero or more path elements. Other wildcard operators found in glob patterns such as?and[...]are not supported.Run-time import paths
Import paths that are evaluated at run-time can now be bundled in certain limited situations. The import path expression must be a form of string concatenation and must start with either
./or../. Each non-string expression in the string concatenation chain becomes a wildcard. The*wildcard is chosen unless the previous character is a/, in which case the/**/*character sequence is used. Some examples:// These two forms are equivalent const json1 = await import('./data/' + kind + '.json') const json2 = await import(`./data/${kind}.json`)This feature works with
require(...)andimport(...)because these can all accept run-time expressions. It does not work withimportandexportstatements because these cannot accept run-time expressions. If you want to prevent esbuild from trying to bundle these imports, you should move the string concatenation expression outside of therequire(...)orimport(...). For example:// This will be bundled const json1 = await import('./data/' + kind + '.json') // This will not be bundled const path = './data/' + kind + '.json' const json2 = await import(path)Note that using this feature means esbuild will potentially do a lot of file system I/O to find all possible files that might match the pattern. This is by design, and is not a bug. If this is a concern, I recommend either avoiding the
/**/pattern (e.g. by not putting a/before a wildcard) or using this feature only in directory subtrees which do not have many files that don't match the pattern (e.g. making a subdirectory for your JSON files and explicitly including that subdirectory in the pattern).
Path aliases in
tsconfig.jsonno longer count as packages (#2792, #3003, #3160, #3238)Setting
--packages=externaltells esbuild to make all import paths external when they look like a package path. For example, an import of./foo/baris not a package path and won't be external while an import offoo/baris a package path and will be external. However, thepathsfield intsconfig.jsonallows you to create import paths that look like package paths but that do not resolve to packages. People do not want these paths to count as package paths. So with this release, the behavior of--packages=externalhas been changed to happen after thetsconfig.jsonpath remapping step.Use the
local-cssloader for.module.cssfiles by defaultWith this release the
cssloader is still used for.cssfiles except that.module.cssfiles now use thelocal-cssloader. This is a common convention in the web development community. If you need.module.cssfiles to use thecssloader instead, then you can override this behavior with--loader:.module.css=css.
- 0.18.x
0.18.20
8 Aug 2023Support advanced CSS
@importrules (#953, #3137)CSS
@importstatements have been extended to allow additional trailing tokens after the import path. These tokens sort of make the imported file behave as if it were wrapped in a@layer,@supports, and/or@mediarule. Here are some examples:@import url(foo.css); @import url(foo.css) layer; @import url(foo.css) layer(bar); @import url(foo.css) layer(bar) supports(display: flex); @import url(foo.css) layer(bar) supports(display: flex) print; @import url(foo.css) layer(bar) print; @import url(foo.css) supports(display: flex); @import url(foo.css) supports(display: flex) print; @import url(foo.css) print;
You can read more about this advanced syntax here. With this release, esbuild will now bundle
@importrules with these trailing tokens and will wrap the imported files in the corresponding rules. Note that this now means a given imported file can potentially appear in multiple places in the bundle. However, esbuild will still only load it once (e.g. on-load plugins will only run once per file, not once per import).
0.18.19
7 Aug 2023Implement
composesfrom CSS modulesThis release implements the
composesannotation from the CSS modules specification. It provides a way for class selectors to reference other class selectors (assuming you are using thelocal-cssloader). And with thefromsyntax, this can even work with local names across CSS files. For example:// app.js import { submit } from './style.css' const div = document.createElement('div') div.className = submit document.body.appendChild(div)/* style.css */ .button { composes: pulse from "anim.css"; display: inline-block; } .submit { composes: button; font-weight: bold; }/* anim.css */ @keyframes pulse { from, to { opacity: 1 } 50% { opacity: 0.5 } } .pulse { animation: 2s ease-in-out infinite pulse; }Bundling this with esbuild using
--bundle --outdir=dist --loader:.css=local-cssnow gives the following:(() => { // style.css var submit = "anim_pulse style_button style_submit"; // app.js var div = document.createElement("div"); div.className = submit; document.body.appendChild(div); })();/* anim.css */ @keyframes anim_pulse { from, to { opacity: 1; } 50% { opacity: 0.5; } } .anim_pulse { animation: 2s ease-in-out infinite anim_pulse; } /* style.css */ .style_button { display: inline-block; } .style_submit { font-weight: bold; }Import paths in the
composes: ... fromsyntax are resolved using the newcomposes-fromimport kind, which can be intercepted by plugins during import path resolution when bundling is enabled.Note that the order in which composed CSS classes from separate files appear in the bundled output file is deliberately undefined by design (see the specification for details). You are not supposed to declare the same CSS property in two separate class selectors and then compose them together. You are only supposed to compose CSS class selectors that declare non-overlapping CSS properties.
Issue #20 (the issue tracking CSS modules) is esbuild's most-upvoted issue! With this change, I now consider esbuild's implementation of CSS modules to be complete. There are still improvements to make and there may also be bugs with the current implementation, but these can be tracked in separate issues.
Fix non-determinism with
tsconfig.jsonand symlinksThis release fixes an issue that could cause esbuild to sometimes emit incorrect build output in cases where a file under the effect of
tsconfig.jsonis inconsistently referenced through a symlink. It can happen when usingnpm linkto create a symlink withinnode_modulesto an unpublished package. The build result was non-deterministic because esbuild runs module resolution in parallel and the result of thetsconfig.jsonlookup depended on whether the import through the symlink or not through the symlink was resolved first. This problem was fixed by moving therealpathoperation before thetsconfig.jsonlookup.Add a
hashproperty to output files (#3084, #3293)As a convenience, every output file in esbuild's API now includes a
hashproperty that is a hash of thecontentsfield. This is the hash that's used internally by esbuild to detect changes between builds for esbuild's live-reload feature. You may also use it to detect changes between your own builds if its properties are sufficient for your use case.This feature has been added directly to output file objects since it's just a hash of the
contentsfield, so it makes conceptual sense to store it in the same location. Another benefit of putting it there instead of including it as a part of the watch mode API is that it can be used without watch mode enabled. You can use it to compare the output of two independent builds that were done at different times.The hash algorithm (currently XXH64) is implementation-dependent and may be changed at any time in between esbuild versions. If you don't like esbuild's choice of hash algorithm then you are welcome to hash the contents yourself instead. As with any hash algorithm, note that while two different hashes mean that the contents are different, two equal hashes do not necessarily mean that the contents are equal. You may still want to compare the contents in addition to the hashes to detect with certainty when output files have been changed.
Implement
composesfrom CSS modulesThis release implements the
composesannotation from the CSS modules specification. It provides a way for class selectors to reference other class selectors (assuming you are using thelocal-cssloader). And with thefromsyntax, this can even work with local names across CSS files. For example:// app.js import { submit } from './style.css' const div = document.createElement('div') div.className = submit document.body.appendChild(div)/* style.css */ .button { composes: pulse from "anim.css"; display: inline-block; } .submit { composes: button; font-weight: bold; }/* anim.css */ @keyframes pulse { from, to { opacity: 1 } 50% { opacity: 0.5 } } .pulse { animation: 2s ease-in-out infinite pulse; }Bundling this with esbuild using
--bundle --outdir=dist --loader:.css=local-cssnow gives the following:(() => { // style.css var submit = "anim_pulse style_button style_submit"; // app.js var div = document.createElement("div"); div.className = submit; document.body.appendChild(div); })();/* anim.css */ @keyframes anim_pulse { from, to { opacity: 1; } 50% { opacity: 0.5; } } .anim_pulse { animation: 2s ease-in-out infinite anim_pulse; } /* style.css */ .style_button { display: inline-block; } .style_submit { font-weight: bold; }Import paths in the
composes: ... fromsyntax are resolved using the newcomposes-fromimport kind, which can be intercepted by plugins during import path resolution when bundling is enabled.Note that the order in which composed CSS classes from separate files appear in the bundled output file is deliberately undefined by design (see the specification for details). You are not supposed to declare the same CSS property in two separate class selectors and then compose them together. You are only supposed to compose CSS class selectors that declare non-overlapping CSS properties.
Issue #20 (the issue tracking CSS modules) is esbuild's most-upvoted issue! With this change, I now consider esbuild's implementation of CSS modules to be complete. There are still improvements to make and there may also be bugs with the current implementation, but these can be tracked in separate issues.
Fix non-determinism with
tsconfig.jsonand symlinksThis release fixes an issue that could cause esbuild to sometimes emit incorrect build output in cases where a file under the effect of
tsconfig.jsonis inconsistently referenced through a symlink. It can happen when usingnpm linkto create a symlink withinnode_modulesto an unpublished package. The build result was non-deterministic because esbuild runs module resolution in parallel and the result of thetsconfig.jsonlookup depended on whether the import through the symlink or not through the symlink was resolved first. This problem was fixed by moving therealpathoperation before thetsconfig.jsonlookup.Add a
hashproperty to output files (#3084, #3293)As a convenience, every output file in esbuild's API now includes a
hashproperty that is a hash of thecontentsfield. This is the hash that's used internally by esbuild to detect changes between builds for esbuild's live-reload feature. You may also use it to detect changes between your own builds if its properties are sufficient for your use case.This feature has been added directly to output file objects since it's just a hash of the
contentsfield, so it makes conceptual sense to store it in the same location. Another benefit of putting it there instead of including it as a part of the watch mode API is that it can be used without watch mode enabled. You can use it to compare the output of two independent builds that were done at different times.The hash algorithm (currently XXH64) is implementation-dependent and may be changed at any time in between esbuild versions. If you don't like esbuild's choice of hash algorithm then you are welcome to hash the contents yourself instead. As with any hash algorithm, note that while two different hashes mean that the contents are different, two equal hashes do not necessarily mean that the contents are equal. You may still want to compare the contents in addition to the hashes to detect with certainty when output files have been changed.
Avoid generating duplicate prefixed declarations in CSS
There was a request for esbuild's CSS prefixer to avoid generating a prefixed declaration if a declaration by that name is already present in the same rule block. So with this release, esbuild will now avoid doing this:
/* Original code */ body { backdrop-filter: blur(30px); -webkit-backdrop-filter: blur(45px); } /* Old output (with --target=safari12) */ body { -webkit-backdrop-filter: blur(30px); backdrop-filter: blur(30px); -webkit-backdrop-filter: blur(45px); } /* New output (with --target=safari12) */ body { backdrop-filter: blur(30px); -webkit-backdrop-filter: blur(45px); }This can result in a visual difference in certain cases (for example if the browser understands
blur(30px)but notblur(45px), it will be able to fall back toblur(30px)). But this change means esbuild now matches the behavior of Autoprefixer which is probably a good representation of how people expect this feature to work.
0.18.18
5 Aug 2023Fix asset references with the
--line-limitflagThe recently-released
--line-limitflag tells esbuild to terminate long lines after they pass this length limit. This includes automatically wrapping long strings across multiple lines using escaped newline syntax. However, using this could cause esbuild to generate incorrect code for references from generated output files to assets in the bundle (i.e. files loaded with thefileorcopyloaders). This is because esbuild implements asset references internally using find-and-replace with a randomly-generated string, but the find operation fails if the string is split by an escaped newline due to line wrapping. This release fixes the problem by not wrapping these strings. This issue affected asset references in both JS and CSS files.Support local names in CSS for
@keyframe,@counter-style, and@containerThis release extends support for local names in CSS files loaded with the
local-cssloader to cover the@keyframe,@counter-style, and@containerrules (and alsoanimation,list-style, andcontainerdeclarations). Here's an example:@keyframes pulse { from, to { opacity: 1 } 50% { opacity: 0.5 } } @counter-style moon { system: cyclic; symbols: 🌕 🌖 🌗 🌘 🌑 🌒 🌓 🌔; } @container squish { li { float: left } } ul { animation: 2s ease-in-out infinite pulse; list-style: inside moon; container: squish / size; }With the
local-cssloader enabled, that CSS will be turned into something like this (with the local name mapping exposed to JS):@keyframes stdin_pulse { from, to { opacity: 1; } 50% { opacity: 0.5; } } @counter-style stdin_moon { system: cyclic; symbols: 🌕 🌖 🌗 🌘 🌑 🌒 🌓 🌔; } @container stdin_squish { li { float: left; } } ul { animation: 2s ease-in-out infinite stdin_pulse; list-style: inside stdin_moon; container: stdin_squish / size; }If you want to use a global name within a file loaded with the
local-cssloader, you can use a:globalselector to do that:div { /* All symbols are global inside this scope (i.e. * "pulse", "moon", and "squish" are global below) */ :global { animation: 2s ease-in-out infinite pulse; list-style: inside moon; container: squish / size; } }If you want to use
@keyframes,@counter-style, or@containerwith a global name, make sure it's in a file that uses thecssorglobal-cssloader instead of thelocal-cssloader. For example, you can configure--loader:.module.css=local-cssso that thelocal-cssloader only applies to*.module.cssfiles.Support strings as keyframe animation names in CSS
With this release, esbuild will now parse animation names that are specified as strings and will convert them to identifiers. The CSS specification allows animation names to be specified using either identifiers or strings but Chrome only understands identifiers, so esbuild will now always convert string names to identifier names for Chrome compatibility:
/* Original code */ @keyframes "hide menu" { from { opacity: 1 } to { opacity: 0 } } menu.hide { animation: 0.5s ease-in-out "hide menu"; } /* Old output */ @keyframes "hide menu" { from { opacity: 1 } to { opacity: 0 } } menu.hide { animation: 0.5s ease-in-out "hide menu"; } /* New output */ @keyframes hide\ menu { from { opacity: 1; } to { opacity: 0; } } menu.hide { animation: 0.5s ease-in-out hide\ menu; }
0.18.17
26 Jul 2023Reading the note…
0.18.16
23 Jul 2023Reading the note…
0.18.15
20 Jul 2023Reading the note…
0.18.14
18 Jul 2023Reading the note…
0.18.13
15 Jul 2023Reading the note…
0.18.12
13 Jul 2023Reading the note…
0.18.11
1 Jul 2023Reading the note…
0.18.10
26 Jun 2023Reading the note…
0.18.9
26 Jun 2023Reading the note…
0.18.8
25 Jun 2023Reading the note…
0.18.7
24 Jun 2023Reading the note…
0.18.6
20 Jun 2023Reading the note…
0.18.5
20 Jun 2023Reading the note…
0.18.4
16 Jun 2023Reading the note…
0.18.3
15 Jun 2023Reading the note…
0.18.2
13 Jun 2023Reading the note…
0.18.1
12 Jun 2023Reading the note…
0.18.0
9 Jun 2023Add a way to try esbuild online
There is now a way to try esbuild live on esbuild's website without installing it: esbuild.github.io/try/. In addition to being able to more easily evaluate esbuild, this should also make it more efficient to generate esbuild bug reports. For example, you can use it to compare the behavior of different versions of esbuild on the same input. The state of the page is stored in the URL for easy sharing. Many thanks to @hyrious for creating hyrious.me/esbuild-repl/, which was the main inspiration for this addition to esbuild's website.
Two forms of build options are supported: either CLI-style (example) or JS-style (example). Both are converted into a JS object that's passed to esbuild's WebAssembly API. The CLI-style argument parser is a custom one that simulates shell quoting rules, and the JS-style argument parser is also custom and parses a superset of JSON (basically JSON5 + regular expressions). So argument parsing is an approximate simulation of what happens for real but hopefully it should be close enough.
Changes to esbuild's
tsconfig.jsonsupport (#3019):This release makes the following changes to esbuild's
tsconfig.jsonsupport:These changes are intended to improve esbuild's compatibility with
tscand reduce the number of unfortunate behaviors regardingtsconfig.jsonand esbuild.Add a workaround for bugs in Safari 16.2 and earlier
Safari's JavaScript parser had a bug (which has now been fixed) where at least something about unary/binary operators nested inside default arguments nested inside either a function or class expression was incorrectly considered a syntax error if that expression was the target of a property assignment. Here are some examples that trigger this Safari bug:
❱ x(function (y = -1) {}.z = 2) SyntaxError: Left hand side of operator '=' must be a reference. ❱ x(class { f(y = -1) {} }.z = 2) SyntaxError: Left hand side of operator '=' must be a reference.It's not clear what the exact conditions are that trigger this bug. However, a workaround for this bug appears to be to post-process your JavaScript to wrap any in function and class declarations that are the direct target of a property access expression in parentheses. That's the workaround that UglifyJS applies for this issue: mishoo/UglifyJS#2056. So that's what esbuild now does starting with this release:
// Original code x(function (y = -1) {}.z = 2, class { f(y = -1) {} }.z = 2) // Old output (with --minify --target=safari16.2) x(function(c=-1){}.z=2,class{f(c=-1){}}.z=2); // New output (with --minify --target=safari16.2) x((function(c=-1){}).z=2,(class{f(c=-1){}}).z=2);This fix is not enabled by default. It's only enabled when
--target=contains Safari 16.2 or earlier, such as with--target=safari16.2. You can also explicitly enable or disable this specific transform (calledfunction-or-class-property-access) with--supported:function-or-class-property-access=false.
This release deliberately contains backwards-incompatible changes. To avoid automatically picking up releases like this, you should either be pinning the exact version of
esbuildin yourpackage.jsonfile (recommended) or be using a version range syntax that only accepts patch upgrades such as^0.17.0or~0.17.0. See npm's documentation about semver for more information.The breaking changes in this release mainly focus on fixing some long-standing issues with esbuild's handling of
tsconfig.jsonfiles. Here are all the changes in this release, in detail:Add a way to try esbuild online
There is now a way to try esbuild live on esbuild's website without installing it: esbuild.github.io/try/. In addition to being able to more easily evaluate esbuild, this should also make it more efficient to generate esbuild bug reports. For example, you can use it to compare the behavior of different versions of esbuild on the same input. The state of the page is stored in the URL for easy sharing. Many thanks to @hyrious for creating hyrious.me/esbuild-repl/, which was the main inspiration for this addition to esbuild's website.
Two forms of build options are supported: either CLI-style (example) or JS-style (example). Both are converted into a JS object that's passed to esbuild's WebAssembly API. The CLI-style argument parser is a custom one that simulates shell quoting rules, and the JS-style argument parser is also custom and parses a superset of JSON (basically JSON5 + regular expressions). So argument parsing is an approximate simulation of what happens for real but hopefully it should be close enough.
Changes to esbuild's
tsconfig.jsonsupport (#3019):This release makes the following changes to esbuild's
tsconfig.jsonsupport:Using experimental decorators now requires
"experimentalDecorators": truePreviously esbuild would always compile decorators in TypeScript code using TypeScript's experimental decorator transform. Now that standard JavaScript decorators are close to being finalized, esbuild will now require you to use
"experimentalDecorators": trueto do this. This new requirement makes it possible for esbuild to introduce a transform for standard JavaScript decorators in TypeScript code in the future. Such a transform has not been implemented yet, however.TypeScript's
targetno longer affects esbuild'stargetSome people requested that esbuild support TypeScript's
targetsetting, so support for it was added (in version 0.12.4). However, esbuild supports reading from multipletsconfig.jsonfiles within a single build, which opens up the possibility that different files in the build have different language targets configured. There isn't really any reason to do this and it can lead to unexpected results. So with this release, thetargetsetting intsconfig.jsonwill no longer affect esbuild's owntargetsetting. You will have to use esbuild's own target setting instead (which is a single, global value).TypeScript's
jsxsetting no longer causes esbuild to preserve JSX syntaxTypeScript has a setting called
jsxthat controls how to transform JSX into JS. The tool-agnostic transform is calledreact, and the React-specific transform is calledreact-jsx(orreact-jsxdev). There is also a setting calledpreservewhich indicates JSX should be passed through untransformed. Previously people would run esbuild with"jsx": "preserve"in theirtsconfig.jsonfiles and then be surprised when esbuild preserved their JSX. So with this release, esbuild will now ignore"jsx": "preserve"intsconfig.jsonfiles. If you want to preserve JSX syntax with esbuild, you now have to use--jsx=preserve.Note: Some people have suggested that esbuild's equivalent
jsxsetting override the one intsconfig.json. However, some projects need to legitimately have different files within the same build use different transforms (i.e.reactvs.react-jsx) and having esbuild's globaljsxsetting overridetsconfig.jsonwould prevent this from working. This release ignores"jsx": "preserve"but still allows otherjsxvalues intsconfig.jsonfiles to override esbuild's globaljsxsetting to keep the ability for multiple files within the same build to use different transforms.useDefineForClassFieldsbehavior has changed (#2584, #2993)Class fields in TypeScript look like this (
xis a class field):class Foo { x = 123 }TypeScript has legacy behavior that uses assignment semantics instead of define semantics for class fields when
useDefineForClassFieldsis enabled (in which case class fields in TypeScript behave differently than they do in JavaScript, which is arguably "wrong").This legacy behavior exists because TypeScript added class fields to TypeScript before they were added to JavaScript. The TypeScript team decided to go with assignment semantics and shipped their implementation. Much later on TC39 decided to go with define semantics for class fields in JavaScript instead. This behaves differently if the base class has a setter with the same name:
class Base { set x(_) { console.log('x:', _) } } // useDefineForClassFields: false class AssignSemantics extends Base { constructor() { super() this.x = 123 } } // useDefineForClassFields: true class DefineSemantics extends Base { constructor() { super() Object.defineProperty(this, 'x', { value: 123 }) } } console.log( new AssignSemantics().x, // Calls the setter new DefineSemantics().x // Doesn't call the setter )When you run
tsc, the value ofuseDefineForClassFieldsdefaults tofalsewhen it's not specified and thetargetintsconfig.jsonis present but earlier thanES2022. This sort of makes sense because the class field language feature was added in ES2022, so before ES2022 class fields didn't exist (and thus TypeScript's legacy behavior is active). However, TypeScript'stargetsetting currently defaults toES3which unfortunately means that theuseDefineForClassFieldssetting currently defaults to false (i.e. to "wrong"). In other words if you runtscwith all default settings, class fields will behave incorrectly.Previously esbuild tried to do what
tscdid. That meant esbuild's version ofuseDefineForClassFieldswasfalseby default, and was alsofalseif esbuild's--target=was present but earlier thanes2022. However, TypeScript's legacy class field behavior is becoming increasingly irrelevant and people who expect class fields in TypeScript to work like they do in JavaScript are confused when they use esbuild with default settings. It's also confusing that the behavior of class fields would change if you changed the language target (even though that's exactly how TypeScript works).So with this release, esbuild will now only use the information in
tsconfig.jsonto determine whetheruseDefineForClassFieldsis true or not. SpecificallyuseDefineForClassFieldswill be respected if present, otherwise it will befalseiftargetis present intsconfig.jsonand isES2021or earlier, otherwise it will betrue. Targets passed to esbuild's--target=setting will no longer affectuseDefineForClassFields.Note that this means different directories in your build can have different values for this setting since esbuild allows different directories to have different
tsconfig.jsonfiles within the same build. This should let you migrate your code one directory at a time without esbuild's--target=setting affecting the semantics of your code.Add support for
verbatimModuleSyntaxfrom TypeScript 5.0TypeScript 5.0 added a new option called
verbatimModuleSyntaxthat deprecates and replaces two older options,preserveValueImportsandimportsNotUsedAsValues. SettingverbatimModuleSyntaxto true intsconfig.jsontells esbuild to not drop unused import statements. Specifically esbuild now treats"verbatimModuleSyntax": trueas if you had specified both"preserveValueImports": trueand"importsNotUsedAsValues": "preserve".Add multiple inheritance for
tsconfig.jsonfrom TypeScript 5.0TypeScript 5.0 now allows multiple inheritance for
tsconfig.jsonfiles. You can now pass an array of filenames via theextendsparameter and yourtsconfig.jsonwill start off containing properties from all of those configuration files, in order. This release of esbuild adds support for this new TypeScript feature.Remove support for
moduleSuffixesThe community has requested that esbuild remove support for TypeScript's
moduleSuffixesfeature, so it has been removed in this release. Instead you can use esbuild's--resolve-extensions=feature to select which module suffix you want to build with.Apply
--tsconfig=overrides tostdinand virtual files (#385, #2543)When you override esbuild's automatic
tsconfig.jsonfile detection with--tsconfig=to pass a specifictsconfig.jsonfile, esbuild previously didn't apply these settings to source code passed via thestdinAPI option or to TypeScript files from plugins that weren't in thefilenamespace. This release changes esbuild's behavior so that settings fromtsconfig.jsonalso apply to these source code files as well.Support
--tsconfig-raw=in build API calls (#943, #2440)Previously if you wanted to override esbuild's automatic
tsconfig.jsonfile detection, you had to create a newtsconfig.jsonfile and pass the file name to esbuild via the--tsconfig=flag. With this release, you can now optionally use--tsconfig-raw=instead to pass the contents oftsconfig.jsonto esbuild directly instead of passing the file name. For example, you can now use--tsconfig-raw={"compilerOptions":{"experimentalDecorators":true}}to enable TypeScript experimental decorators directly using a command-line flag (assuming you escape the quotes correctly using your current shell's quoting rules). The--tsconfig-raw=flag previously only worked with transform API calls but with this release, it now works with build API calls too.Ignore all
tsconfig.jsonfiles innode_modules(#276, #2386)This changes esbuild's behavior that applies
tsconfig.jsonto all files in the subtree of the directory containingtsconfig.json. In version 0.12.7, esbuild started ignoringtsconfig.jsonfiles insidenode_modulesfolders. The rationale is that people typically do this by mistake and that doing this intentionally is a rare use case that doesn't need to be supported. However, this change only applied to certain syntax-specific settings (e.g.jsxFactory) but did not apply to path resolution settings (e.g.paths). With this release, esbuild will now ignore alltsconfig.jsonfiles innode_modulesinstead of only ignoring certain settings.Ignore
tsconfig.jsonwhen resolving paths withinnode_modulesPreviously fields in
tsconfig.jsonrelated to path resolution (e.g.paths) were respected for all files in the subtree containing thattsconfig.jsonfile, even within a nestednode_modulessubdirectory. This meant that a project'spathssettings could potentially affect any bundled packages. With this release, esbuild will no longer usetsconfig.jsonsettings during path resolution inside nestednode_modulessubdirectories.Prefer
.jsover.tswithinnode_modulesThe default list of implicit extensions that esbuild will try appending to import paths contains
.tsbefore.js. This makes it possible to bundle TypeScript projects that reference other files in the project using extension-less imports (e.g../some-fileto load./some-file.tsinstead of./some-file.js). However, this behavior is undesirable withinnode_modulesdirectories. Some package authors publish both their original TypeScript code and their compiled JavaScript code side-by-side. In these cases, esbuild should arguably be using the compiled JavaScript files instead of the original TypeScript files because the TypeScript compilation settings for files within the package should be determined by the package author, not the user of esbuild. So with this release, esbuild will now prefer implicit.jsextensions over.tswhen searching for import paths withinnode_modules.
These changes are intended to improve esbuild's compatibility with
tscand reduce the number of unfortunate behaviors regardingtsconfig.jsonand esbuild.Add a workaround for bugs in Safari 16.2 and earlier
Safari's JavaScript parser had a bug (which has now been fixed) where at least something about unary/binary operators nested inside default arguments nested inside either a function or class expression was incorrectly considered a syntax error if that expression was the target of a property assignment. Here are some examples that trigger this Safari bug:
❱ x(function (y = -1) {}.z = 2) SyntaxError: Left hand side of operator '=' must be a reference. ❱ x(class { f(y = -1) {} }.z = 2) SyntaxError: Left hand side of operator '=' must be a reference.It's not clear what the exact conditions are that trigger this bug. However, a workaround for this bug appears to be to post-process your JavaScript to wrap any in function and class declarations that are the direct target of a property access expression in parentheses. That's the workaround that UglifyJS applies for this issue: mishoo/UglifyJS#2056. So that's what esbuild now does starting with this release:
// Original code x(function (y = -1) {}.z = 2, class { f(y = -1) {} }.z = 2) // Old output (with --minify --target=safari16.2) x(function(c=-1){}.z=2,class{f(c=-1){}}.z=2); // New output (with --minify --target=safari16.2) x((function(c=-1){}).z=2,(class{f(c=-1){}}).z=2);This fix is not enabled by default. It's only enabled when
--target=contains Safari 16.2 or earlier, such as with--target=safari16.2. You can also explicitly enable or disable this specific transform (calledfunction-or-class-property-access) with--supported:function-or-class-property-access=false.Fix esbuild's TypeScript type declarations to forbid unknown properties
Version 0.17.0 of esbuild introduced a specific form of function overloads in the TypeScript type definitions for esbuild's API calls that looks like this:
interface TransformOptions { legalComments?: 'none' | 'inline' | 'eof' | 'external' } interface TransformResult<ProvidedOptions extends TransformOptions = TransformOptions> { legalComments: string | (ProvidedOptions['legalComments'] extends 'external' ? never : undefined) } declare function transformSync<ProvidedOptions extends TransformOptions>(input: string, options?: ProvidedOptions): TransformResult<ProvidedOptions> declare function transformSync(input: string, options?: TransformOptions): TransformResultThis more accurately reflects how esbuild's JavaScript API behaves. The result object returned by
transformSynconly has thelegalCommentsproperty if you passlegalComments: 'external':// These have type "string | undefined" transformSync('').legalComments transformSync('', { legalComments: 'eof' }).legalComments // This has type "string" transformSync('', { legalComments: 'external' }).legalCommentsHowever, this form of function overloads unfortunately allows typos (e.g.
egalComments) to pass the type checker without generating an error as TypeScript allows all objects with unknown properties to extendTransformOptions. These typos result in esbuild's API throwing an error at run-time.To prevent typos during type checking, esbuild's TypeScript type definitions will now use a different form that looks like this:
type SameShape<Out, In extends Out> = In & { [Key in Exclude<keyof In, keyof Out>]: never } interface TransformOptions { legalComments?: 'none' | 'inline' | 'eof' | 'external' } interface TransformResult<ProvidedOptions extends TransformOptions = TransformOptions> { legalComments: string | (ProvidedOptions['legalComments'] extends 'external' ? never : undefined) } declare function transformSync<T extends TransformOptions>(input: string, options?: SameShape<TransformOptions, T>): TransformResult<T>This change should hopefully not affect correct code. It should hopefully introduce type errors only for incorrect code.
Fix CSS nesting transform for pseudo-elements
This release fixes esbuild's CSS nesting transform for pseudo-elements (e.g.
::beforeand::after). The CSS nesting specification says that the nesting selector does not work with pseudo-elements. This can be seen in the example below: esbuild does not carry the parent pseudo-element::beforethrough the nesting selector&. However, that doesn't apply to pseudo-elements that are within the same selector. Previously esbuild had a bug where it considered pseudo-elements in both locations as invalid. This release changes esbuild to only consider those from the parent selector invalid, which should align with the specification:/* Original code */ a, b::before { &.c, &::after { content: 'd'; } } /* Old output (with --target=chrome90) */ a:is(.c, ::after) { content: "d"; } /* New output (with --target=chrome90) */ a.c, a::after { content: "d"; }Forbid
&before a type selector in nested CSSThe people behind the work-in-progress CSS nesting specification have very recently decided to forbid nested CSS that looks like
&div. You will have to use eitherdiv&or&:is(div)instead. This release of esbuild has been updated to take this new change into consideration. Doing this now generates a warning. The suggested fix is slightly different depending on where in the overall selector it happened:▲ [WARNING] Cannot use type selector "input" directly after nesting selector "&" [css-syntax-error] example.css:2:3: 2 │ &input { │ ~~~~~ ╵ :is(input) CSS nesting syntax does not allow the "&" selector to come before a type selector. You can wrap this selector in ":is()" as a workaround. This restriction exists to avoid problems with SASS nesting, where the same syntax means something very different that has no equivalent in real CSS (appending a suffix to the parent selector). ▲ [WARNING] Cannot use type selector "input" directly after nesting selector "&" [css-syntax-error] example.css:6:8: 6 │ .form &input { │ ~~~~~~ ╵ input& CSS nesting syntax does not allow the "&" selector to come before a type selector. You can move the "&" to the end of this selector as a workaround. This restriction exists to avoid problems with SASS nesting, where the same syntax means something very different that has no equivalent in real CSS (appending a suffix to the parent selector).
- 0.17.x
0.17.19
13 May 2023Reading the note…
0.17.18
22 Apr 2023Reading the note…
0.17.17
16 Apr 2023Reading the note…
0.17.16
10 Apr 2023Reading the note…
0.17.15
1 Apr 2023Reading the note…
0.17.14
26 Mar 2023Reading the note…
0.17.13
24 Mar 2023Reading the note…
0.17.12
17 Mar 2023Reading the note…
0.17.11
3 Mar 2023Fix the
aliasfeature to always prefer the longest matchIt's possible to configure conflicting aliases such as
--alias:a=band--alias:a/c=d, which is ambiguous for the import patha/c/x(since it could map to eitherb/c/xord/x). Previously esbuild would pick the first matchingalias, which would non-deterministically pick between one of the possible matches. This release fixes esbuild to always deterministically pick the longest possible match.Minify calls to some global primitive constructors
With this release, esbuild's minifier now replaces calls to
Boolean/Number/String/BigIntwith equivalent shorter code when relevant:// Original code console.log( Boolean(a ? (b | c) !== 0 : (c & d) !== 0), Number(e ? '1' : '2'), String(e ? '1' : '2'), BigInt(e ? 1n : 2n), ) // Old output (with --minify) console.log(Boolean(a?(b|c)!==0:(c&d)!==0),Number(e?"1":"2"),String(e?"1":"2"),BigInt(e?1n:2n)); // New output (with --minify) console.log(!!(a?b|c:c&d),+(e?"1":"2"),e?"1":"2",e?1n:2n);
Adjust some feature compatibility tables for node
This release makes the following adjustments to esbuild's internal feature compatibility tables for node, which tell esbuild which versions of node are known to support all aspects of that feature:
Each of these adjustments was identified by comparing against data from the
node-compat-tablepackage and was manually verified using old node executables downloaded from nodejs.org/download/release/.
0.17.10
20 Feb 2023Reading the note…
0.17.9
19 Feb 2023Reading the note…
0.17.8
13 Feb 2023Reading the note…
0.17.7
9 Feb 2023Reading the note…
0.17.6
6 Feb 2023Reading the note…
0.17.5
27 Jan 2023Reading the note…
0.17.4
22 Jan 2023Reading the note…
0.17.3
18 Jan 2023Reading the note…
0.17.2
17 Jan 2023Reading the note…
0.17.1
16 Jan 2023Make it possible to cancel a build
The context object introduced in version 0.17.0 has a new
cancel()method. You can use it to cancel a long-running build so that you can start a new one without needing to wait for the previous one to finish. When this happens, the previous build should always have at least one error and have no output files (i.e. it will be a failed build).Using it might look something like this:
This API is a quick implementation and isn't maximally efficient, so the build may continue to do some work for a little bit before stopping. For example, I have added stop points between each top-level phase of the bundler and in the main module graph traversal loop, but I haven't added fine-grained stop points within the internals of the linker. How quickly esbuild stops can be improved in future releases. This means you'll want to wait for
cancel()and/or the previousrebuild()to finish (i.e. await the returned promise in JavaScript) before starting a new build, otherwiserebuild()will give you the just-canceled build that still hasn't ended yet. Note thatonEndcallbacks will still be run regardless of whether or not the build was canceled.Fix server-sent events without
servedirThe server-sent events for live reload were incorrectly using
servedirto calculate the path to modified output files. This means events couldn't be sent whenservedirwasn't specified. This release uses the internal output directory (which is always present) instead ofservedir(which might be omitted), so live reload should now work whenservediris not specified.Custom entry point output paths now work with the
copyloaderEntry points can optionally provide custom output paths to change the path of the generated output file. For example,
esbuild foo=abc.js bar=xyz.js --outdir=outgenerates the filesout/foo.jsandout/bar.js. However, this previously didn't work when using thecopyloader due to an oversight. This bug has been fixed. For example, you can now doesbuild foo=abc.html bar=xyz.html --outdir=out --loader:.html=copyto generate the filesout/foo.htmlandout/bar.html.
Make it possible to cancel a build
The context object introduced in version 0.17.0 has a new
cancel()method. You can use it to cancel a long-running build so that you can start a new one without needing to wait for the previous one to finish. When this happens, the previous build should always have at least one error and have no output files (i.e. it will be a failed build).Using it might look something like this:
JS:
let ctx = await esbuild.context({ // ... }) let rebuildWithTimeLimit = timeLimit => { let timeout = setTimeout(() => ctx.cancel(), timeLimit) return ctx.rebuild().finally(() => clearTimeout(timeout)) } let build = await rebuildWithTimeLimit(500)Go:
ctx, err := api.Context(api.BuildOptions{ // ... }) if err != nil { return } rebuildWithTimeLimit := func(timeLimit time.Duration) api.BuildResult { t := time.NewTimer(timeLimit) go func() { <-t.C ctx.Cancel() }() result := ctx.Rebuild() t.Stop() return result } build := rebuildWithTimeLimit(500 * time.Millisecond)
This API is a quick implementation and isn't maximally efficient, so the build may continue to do some work for a little bit before stopping. For example, I have added stop points between each top-level phase of the bundler and in the main module graph traversal loop, but I haven't added fine-grained stop points within the internals of the linker. How quickly esbuild stops can be improved in future releases. This means you'll want to wait for
cancel()and/or the previousrebuild()to finish (i.e. await the returned promise in JavaScript) before starting a new build, otherwiserebuild()will give you the just-canceled build that still hasn't ended yet. Note thatonEndcallbacks will still be run regardless of whether or not the build was canceled.Fix server-sent events without
servedirThe server-sent events for live reload were incorrectly using
servedirto calculate the path to modified output files. This means events couldn't be sent whenservedirwasn't specified. This release uses the internal output directory (which is always present) instead ofservedir(which might be omitted), so live reload should now work whenservediris not specified.Custom entry point output paths now work with the
copyloaderEntry points can optionally provide custom output paths to change the path of the generated output file. For example,
esbuild foo=abc.js bar=xyz.js --outdir=outgenerates the filesout/foo.jsandout/bar.js. However, this previously didn't work when using thecopyloader due to an oversight. This bug has been fixed. For example, you can now doesbuild foo=abc.html bar=xyz.html --outdir=out --loader:.html=copyto generate the filesout/foo.htmlandout/bar.html.The JS API can now take an array of objects
Previously it was not possible to specify two entry points with the same custom output path using the JS API, although it was possible to do this with the Go API and the CLI. This will not cause a collision if both entry points use different extensions (e.g. if one uses
.jsand the other uses.css). You can now pass the JS API an array of objects to work around this API limitation:// The previous API didn't let you specify duplicate output paths let result = await esbuild.build({ entryPoints: { // This object literal contains a duplicate key, so one is ignored 'dist': 'foo.js', 'dist': 'bar.css', }, }) // You can now specify duplicate output paths as an array of objects let result = await esbuild.build({ entryPoints: [ { in: 'foo.js', out: 'dist' }, { in: 'bar.css', out: 'dist' }, ], })
0.17.0
14 Jan 2023Move everything related to incremental builds to a new
contextAPI (#1037, #1606, #2280, #2418)This change removes the
incrementalandwatchoptions as well as theserve()method, and introduces a newcontext()method. The context method takes the same arguments as thebuild()method but only validates its arguments and does not do an initial build. Instead, builds can be triggered using therebuild(),watch(), andserve()methods on the returned context object. The new context API looks like this:// Create a context for incremental builds const context = await esbuild.context({ entryPoints: ['app.ts'], bundle: true, }) // Manually do an incremental build const result = await context.rebuild() // Enable watch mode await context.watch() // Enable serve mode await context.serve() // Dispose of the context context.dispose()The switch to the context API solves a major issue with the previous API which is that if the initial build fails, a promise is thrown in JavaScript which prevents you from accessing the returned result object. That prevented you from setting up long-running operations such as watch mode when the initial build contained errors. It also makes tearing down incremental builds simpler as there is now a single way to do it instead of three separate ways.
In addition, this release also makes some subtle changes to how incremental builds work. Previously every call to
rebuild()started a new build. If you weren't careful, then builds could actually overlap. This doesn't cause any problems with esbuild itself, but could potentially cause problems with plugins (esbuild doesn't even give you a way to identify which overlapping build a given plugin callback is running on). Overlapping builds also arguably aren't useful, or at least aren't useful enough to justify the confusion and complexity that they bring. With this release, there is now only ever a single active build per context. Callingrebuild()before the previous rebuild has finished now "merges" with the existing rebuild instead of starting a new build.Allow using
watchandservetogether (#805, #1650, #2576)Previously it was not possible to use watch mode and serve mode together. The rationale was that watch mode is one way of automatically rebuilding your project and serve mode is another (since serve mode automatically rebuilds on every request). However, people want to combine these two features to make "live reloading" where the browser automatically reloads the page when files are changed on the file system.
This release now allows you to use these two features together. You can only call the
watch()andserve()APIs once each per context, but if you call them together on the same context then esbuild will automatically rebuild both when files on the file system are changed and when the server serves a request.Support "live reloading" through server-sent events
Server-sent events are a simple way to pass one-directional messages asynchronously from the server to the client. Serve mode now provides a
/esbuildendpoint with anchangeevent that triggers every time esbuild's output changes. So you can now implement simple "live reloading" (i.e. reloading the page when a file is edited and saved) like this:new EventSource('/esbuild').addEventListener('change', () => location.reload())The event payload is a JSON object with the following shape:
interface ChangeEvent { added: string[] removed: string[] updated: string[] }This JSON should also enable more complex live reloading scenarios. For example, the following code hot-swaps changed CSS
<link>tags in place without reloading the page (but still reloads when there are other types of changes):new EventSource('/esbuild').addEventListener('change', e => { const { added, removed, updated } = JSON.parse(e.data) if (!added.length && !removed.length && updated.length === 1) { for (const link of document.getElementsByTagName("link")) { const url = new URL(link.href) if (url.host === location.host && url.pathname === updated[0]) { const next = link.cloneNode() next.href = updated[0] + '?' + Math.random().toString(36).slice(2) next.onload = () => link.remove() link.parentNode.insertBefore(next, link.nextSibling) return } } } location.reload() })Implementing live reloading like this has a few known caveats:
This release deliberately contains backwards-incompatible changes. To avoid automatically picking up releases like this, you should either be pinning the exact version of
esbuildin yourpackage.jsonfile (recommended) or be using a version range syntax that only accepts patch upgrades such as^0.16.0or~0.16.0. See npm's documentation about semver for more information.At a high level, the breaking changes in this release fix some long-standing issues with the design of esbuild's incremental, watch, and serve APIs. This release also introduces some exciting new features such as live reloading. In detail:
Move everything related to incremental builds to a new
contextAPI (#1037, #1606, #2280, #2418)This change removes the
incrementalandwatchoptions as well as theserve()method, and introduces a newcontext()method. The context method takes the same arguments as thebuild()method but only validates its arguments and does not do an initial build. Instead, builds can be triggered using therebuild(),watch(), andserve()methods on the returned context object. The new context API looks like this:// Create a context for incremental builds const context = await esbuild.context({ entryPoints: ['app.ts'], bundle: true, }) // Manually do an incremental build const result = await context.rebuild() // Enable watch mode await context.watch() // Enable serve mode await context.serve() // Dispose of the context context.dispose()The switch to the context API solves a major issue with the previous API which is that if the initial build fails, a promise is thrown in JavaScript which prevents you from accessing the returned result object. That prevented you from setting up long-running operations such as watch mode when the initial build contained errors. It also makes tearing down incremental builds simpler as there is now a single way to do it instead of three separate ways.
In addition, this release also makes some subtle changes to how incremental builds work. Previously every call to
rebuild()started a new build. If you weren't careful, then builds could actually overlap. This doesn't cause any problems with esbuild itself, but could potentially cause problems with plugins (esbuild doesn't even give you a way to identify which overlapping build a given plugin callback is running on). Overlapping builds also arguably aren't useful, or at least aren't useful enough to justify the confusion and complexity that they bring. With this release, there is now only ever a single active build per context. Callingrebuild()before the previous rebuild has finished now "merges" with the existing rebuild instead of starting a new build.Allow using
watchandservetogether (#805, #1650, #2576)Previously it was not possible to use watch mode and serve mode together. The rationale was that watch mode is one way of automatically rebuilding your project and serve mode is another (since serve mode automatically rebuilds on every request). However, people want to combine these two features to make "live reloading" where the browser automatically reloads the page when files are changed on the file system.
This release now allows you to use these two features together. You can only call the
watch()andserve()APIs once each per context, but if you call them together on the same context then esbuild will automatically rebuild both when files on the file system are changed and when the server serves a request.Support "live reloading" through server-sent events
Server-sent events are a simple way to pass one-directional messages asynchronously from the server to the client. Serve mode now provides a
/esbuildendpoint with anchangeevent that triggers every time esbuild's output changes. So you can now implement simple "live reloading" (i.e. reloading the page when a file is edited and saved) like this:new EventSource('/esbuild').addEventListener('change', () => location.reload())The event payload is a JSON object with the following shape:
interface ChangeEvent { added: string[] removed: string[] updated: string[] }This JSON should also enable more complex live reloading scenarios. For example, the following code hot-swaps changed CSS
<link>tags in place without reloading the page (but still reloads when there are other types of changes):new EventSource('/esbuild').addEventListener('change', e => { const { added, removed, updated } = JSON.parse(e.data) if (!added.length && !removed.length && updated.length === 1) { for (const link of document.getElementsByTagName("link")) { const url = new URL(link.href) if (url.host === location.host && url.pathname === updated[0]) { const next = link.cloneNode() next.href = updated[0] + '?' + Math.random().toString(36).slice(2) next.onload = () => link.remove() link.parentNode.insertBefore(next, link.nextSibling) return } } } location.reload() })Implementing live reloading like this has a few known caveats:
These events only trigger when esbuild's output changes. They do not trigger when files unrelated to the build being watched are changed. If your HTML file references other files that esbuild doesn't know about and those files are changed, you can either manually reload the page or you can implement your own live reloading infrastructure instead of using esbuild's built-in behavior.
The
EventSourceAPI is supposed to automatically reconnect for you. However, there's a bug in Firefox that breaks this if the server is ever temporarily unreachable: bugzilla.mozilla.org/show_bug.cgi. Workarounds are to use any other browser, to manually reload the page if this happens, or to write more complicated code that manually closes and re-creates theEventSourceobject if there is a connection error. I'm hopeful that this bug will be fixed.Browser vendors have decided to not implement HTTP/2 without TLS. This means that each
/esbuildevent source will take up one of your precious 6 simultaneous per-domain HTTP/1.1 connections. So if you open more than six HTTP tabs that use this live-reloading technique, you will be unable to use live reloading in some of those tabs (and other things will likely also break). The workaround is to enable HTTPS, which is now possible to do in esbuild itself (see below).
Add built-in support for HTTPS
You can now tell esbuild's built-in development server to use HTTPS instead of HTTP. This is sometimes necessary because browser vendors have started making modern web features unavailable to HTTP websites. Previously you had to put a proxy in front of esbuild to enable HTTPS since esbuild's development server only supported HTTP. But with this release, you can now enable HTTPS with esbuild without an additional proxy.
To enable HTTPS with esbuild:
Generate a self-signed certificate. There are many ways to do this. Here's one way, assuming you have
opensslinstalled:openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 9999 -nodes -subj /CN=127.0.0.1
Add
--keyfile=key.pemand--certfile=cert.pemto your esbuild development server commandClick past the scary warning in your browser when you load your page
If you have more complex needs than this, you can still put a proxy in front of esbuild and use that for HTTPS instead. Note that if you see the message "Client sent an HTTP request to an HTTPS server" when you load your page, then you are using the incorrect protocol. Replace
http://withhttps://in your browser's URL bar.Keep in mind that esbuild's HTTPS support has nothing to do with security. The only reason esbuild now supports HTTPS is because browsers have made it impossible to do local development with certain modern web features without jumping through these extra hoops. Please do not use esbuild's development server for anything that needs to be secure. It's only intended for local development and no considerations have been made for production environments whatsoever.
Better support copying
index.htmlinto the output directory (#621, #1771)Right now esbuild only supports JavaScript and CSS as first-class content types. Previously this meant that if you were building a website with a HTML file, a JavaScript file, and a CSS file, you could use esbuild to build the JavaScript file and the CSS file into the output directory but not to copy the HTML file into the output directory. You needed a separate
cpcommand for that.Or so I thought. It turns out that the
copyloader added in version 0.14.44 of esbuild is sufficient to have esbuild copy the HTML file into the output directory as well. You can add something likeindex.html --loader:.html=copyand esbuild will copyindex.htmlinto the output directory for you. The benefits of this are a) you don't need a separatecpcommand and b) theindex.htmlfile will automatically be re-copied when esbuild is in watch mode and the contents ofindex.htmlare edited. This also goes for other non-HTML file types that you might want to copy.This pretty much already worked. The one thing that didn't work was that esbuild's built-in development server previously only supported implicitly loading
index.html(e.g. loading/about/index.htmlwhen you visit/about/) whenindex.htmlexisted on the file system. Previously esbuild didn't support implicitly loadingindex.htmlif it was a build result. That bug has been fixed with this release so it should now be practical to use thecopyloader to do this.Fix
onEndnot being called in serve modePrevious releases had a bug where plugin
onEndcallbacks weren't called when using the top-levelserve()API. This API no longer exists and the internals have been reimplemented such thatonEndcallbacks should now always be called at the end of every build.Incremental builds now write out build results differently
Previously build results were always written out after every build. However, this could cause the output directory to fill up with files from old builds if code splitting was enabled, since the file names for code splitting chunks contain content hashes and old files were not deleted.
With this release, incremental builds in esbuild will now delete old output files from previous builds that are no longer relevant. Subsequent incremental builds will also no longer overwrite output files whose contents haven't changed since the previous incremental build.
The
onRebuildwatch mode callback was removed (#980, #2499)Previously watch mode accepted an
onRebuildcallback which was called whenever watch mode rebuilt something. This was not great in practice because if you are running code after a build, you likely want that code to run after every build, not just after the second and subsequent builds. This release removes option to provide anonRebuildcallback. You can create a plugin with anonEndcallback instead. TheonEndplugin API already exists, and is a way to run some code after every build.You can now return errors from
onEndIt's now possible to add additional build errors and/or warnings to the current build from within your
onEndcallback by returning them in an array. This is identical to how theonStartcallback already works. The evaluation ofonEndcallbacks have been moved around a bit internally to make this possible.Note that the build will only fail (i.e. reject the promise) if the additional errors are returned from
onEnd. Adding additional errors to the result object that's passed toonEndwon't affect esbuild's behavior at all.Print URLs and ports from the Go and JS APIs
Previously esbuild's CLI printed out something like this when serve mode is active:
> Local: http://127.0.0.1:8000/ > Network: http://192.168.0.1:8000/
The CLI still does this, but now the JS and Go serve mode APIs will do this too. This only happens when the log level is set to
verbose,debug, orinfobut not when it's set towarning,error, orsilent.
Upgrade guide for existing code
Rebuild (a.k.a. incremental build):
Before:
const result = await esbuild.build({ ...buildOptions, incremental: true }); builds.push(result); for (let i = 0; i < 4; i++) builds.push(await result.rebuild()); await result.rebuild.dispose(); // To free resourcesAfter:
const ctx = await esbuild.context(buildOptions); for (let i = 0; i < 5; i++) builds.push(await ctx.rebuild()); await ctx.dispose(); // To free resources
Previously the first build was done differently than subsequent builds. Now both the first build and subsequent builds are done using the same API.
Serve:
Before:
const serveResult = await esbuild.serve(serveOptions, buildOptions); ... serveResult.stop(); await serveResult.wait; // To free resources
After:
const ctx = await esbuild.context(buildOptions); const serveResult = await ctx.serve(serveOptions); ... await ctx.dispose(); // To free resources
Watch:
Before:
const result = await esbuild.build({ ...buildOptions, watch: true }); ... result.stop(); // To free resourcesAfter:
const ctx = await esbuild.context(buildOptions); await ctx.watch(); ... await ctx.dispose(); // To free resources
Watch with
onRebuild:Before:
const onRebuild = (error, result) => { if (error) console.log('subsequent build:', error); else console.log('subsequent build:', result); }; try { const result = await esbuild.build({ ...buildOptions, watch: { onRebuild } }); console.log('first build:', result); ... result.stop(); // To free resources } catch (error) { console.log('first build:', error); }After:
const plugins = [{ name: 'my-plugin', setup(build) { let count = 0; build.onEnd(result => { if (count++ === 0) console.log('first build:', result); else console.log('subsequent build:', result); }); }, }]; const ctx = await esbuild.context({ ...buildOptions, plugins }); await ctx.watch(); ... await ctx.dispose(); // To free resourcesThe
onRebuildfunction has now been removed. The replacement is to make a plugin with anonEndcallback.Previously
onRebuilddid not fire for the first build (only for subsequent builds). This was usually problematic, so usingonEndinstead ofonRebuildis likely less error-prone. But if you need to emulate the old behavior ofonRebuildthat ignores the first build, then you'll need to manually count and ignore the first build in your plugin (as demonstrated above).
Notice how all of these API calls are now done off the new context object. You should now be able to use all three kinds of incremental builds (
rebuild,serve, andwatch) together on the same context object. Also notice how callingdisposeon the context is now the common way to discard the context and free resources in all of these situations.- 0.16.x
0.16.17
11 Jan 2023Fix additional comment-related regressions
This release fixes more edge cases where the new comment preservation behavior that was added in 0.16.14 could introduce syntax errors. Specifically:
x = () => (/* comment */ {}) for ((/* comment */ let).x of y) ; function *f() { yield (/* comment */class {}) }These cases caused esbuild to generate code with a syntax error in version 0.16.14 or above. These bugs have now been fixed.
0.16.16
8 Jan 2023Fix a regression caused by comment preservation
The new comment preservation behavior that was added in 0.16.14 introduced a regression where comments in certain locations could cause esbuild to omit certain necessary parentheses in the output. The outermost parentheses were incorrectly removed for the following syntax forms, which then introduced syntax errors:
(/* comment */ { x: 0 }).x; (/* comment */ function () { })(); (/* comment */ class { }).prototype;This regression has been fixed.
0.16.15
7 Jan 2023Reading the note…
0.16.14
4 Jan 2023Preserve some comments in expressions
Various tools give semantic meaning to comments embedded inside of expressions. For example, Webpack and Vite have special "magic comments" that can be used to affect code splitting behavior:
import(/* webpackChunkName: "foo" */ '../foo'); import(/* @vite-ignore */ dynamicVar); new Worker(/* webpackChunkName: "bar" */ new URL("../bar.ts", import.meta.url)); new Worker(new URL('./path', import.meta.url), /* @vite-ignore */ dynamicOptions);Since esbuild can be used as a preprocessor for these tools (e.g. to strip TypeScript types), it can be problematic if esbuild doesn't do additional work to try to retain these comments. Previously esbuild special-cased Webpack comments in these specific locations in the AST. But Vite would now like to use similar comments, and likely other tools as well.
So with this release, esbuild now will attempt to preserve some comments inside of expressions in more situations than before. This behavior is mainly intended to preserve these special "magic comments" that are meant for other tools to consume, although esbuild will no longer only preserve Webpack-specific comments so it should now be tool-agnostic. There is no guarantee that all such comments will be preserved (especially when
--minify-syntaxis enabled). So this change does not mean that esbuild is now usable as a code formatter. In particular comment preservation is more likely to happen with leading comments than with trailing comments. You should put comments that you want to be preserved before the relevant expression instead of after it. Also note that this change does not retain any more statement-level comments than before (i.e. comments not embedded inside of expressions). Comment preservation is not enabled when--minify-whitespaceis enabled (which is automatically enabled when you use--minify).
0.16.13
2 Jan 2023Publish a new bundle visualization tool
While esbuild provides bundle metadata via the
--metafileflag, previously esbuild left analysis of it completely up to third-party tools (well, outside of the rudimentary--analyzeflag). However, the esbuild website now has a built-in bundle visualization tool:You can pass
--metafileto esbuild to output bundle metadata, then upload that JSON file to this tool to visualize your bundle. This is helpful for answering questions such as:I'm publishing this tool because I think esbuild should provide some answer to "how do I visualize my bundle" without requiring people to reach for third-party tools. At the moment the tool offers two types of visualizations: a radial "sunburst chart" and a linear "flame chart". They serve slightly different but overlapping use cases (e.g. the sunburst chart is more keyboard-accessible while the flame chart is easier with the mouse). This tool may continue to evolve over time.
Fix
--metafileand--mangle-cachewith--watchThe CLI calls the Go API and then also writes out the metafile and/or mangle cache JSON files if those features are enabled. This extra step is necessary because these files are returned by the Go API as in-memory strings. However, this extra step accidentally didn't happen for all builds after the initial build when watch mode was enabled. This behavior used to work but it was broken in version 0.14.18 by the introduction of the mangle cache feature. This release fixes the combination of these features, so the metafile and mangle cache features should now work with watch mode. This behavior was only broken for the CLI, not for the JS or Go APIs.
Add an
originalfield to the metafileThe metadata file JSON now has an additional field: each import in an input file now contains the pre-resolved path in the
originalfield in addition to the post-resolved path in thepathfield. This means it's now possible to run certain additional analysis over your bundle. For example, you should be able to use this to detect when the same package subpath is represented multiple times in the bundle, either because multiple versions of a package were bundled or because a package is experiencing the dual-package hazard.
0.16.12
28 Dec 2022Reading the note…
A whole project to check? Paste its package.json in the dependency check: every deprecated, outdated or vulnerable dependency, with what to upgrade to. Free, no account.