Update dependency esbuild to v0.23.0
This MR contains the following updates:
Package | Type | Update | Change |
---|---|---|---|
esbuild | dependencies | minor | 0.19.3 -> 0.23.0 |
Release Notes
evanw/esbuild (esbuild)
v0.23.0
This release deliberately contains backwards-incompatible changes. To avoid automatically picking up releases like this, you should either be pinning the exact version of esbuild
in your package.json
file (recommended) or be using a version range syntax that only accepts patch upgrades such as ^0.22.0
or ~0.22.0
. See npm's documentation about semver for more information.
-
Revert the recent change to avoid bundling dependencies for node (#3819)
This release reverts the recent change in version 0.22.0 that made
--packages=external
the default behavior with--platform=node
. The default is now back to--packages=bundle
.I've just been made aware that Amazon doesn't pin their dependencies in their "AWS CDK" product, which means that whenever esbuild publishes a new release, many people (potentially everyone?) using their SDK around the world instantly starts using it without Amazon checking that it works first. This change in version 0.22.0 happened to break their SDK. I'm amazed that things haven't broken before this point. This revert attempts to avoid these problems for Amazon's customers. Hopefully Amazon will pin their dependencies in the future.
In addition, this is probably a sign that esbuild is used widely enough that it now needs to switch to a more complicated release model. I may have esbuild use a beta channel model for further development.
-
Fix preserving collapsed JSX whitespace (#3818)
When transformed, certain whitespace inside JSX elements is ignored completely if it collapses to an empty string. However, the whitespace should only be ignored if the JSX is being transformed, not if it's being preserved. This release fixes a bug where esbuild was previously incorrectly ignoring collapsed whitespace with
--jsx=preserve
. Here is an example:// Original code <Foo> <Bar /> </Foo> // Old output (with --jsx=preserve) <Foo><Bar /></Foo>; // New output (with --jsx=preserve) <Foo> <Bar /> </Foo>;
v0.22.0
This release deliberately contains backwards-incompatible changes. To avoid automatically picking up releases like this, you should either be pinning the exact version of esbuild
in your package.json
file (recommended) or be using a version range syntax that only accepts patch upgrades such as ^0.21.0
or ~0.21.0
. See npm's documentation about semver for more information.
-
Omit packages from bundles by default when targeting node (#1874, #2830, #2846, #2915, #3145, #3294, #3323, #3582, #3809, #3815)
This breaking change is an experiment. People are commonly confused when using esbuild to bundle code for node (i.e. for
--platform=node
) because some packages may not be intended for bundlers, and may use node-specific features that don't work with a bundler. Even though esbuild's "getting started" instructions say to use--packages=external
to work around this problem, many people don't read the documentation and don't do this, and are then confused when it doesn't work. So arguably this is a bad default behavior for esbuild to have if people keep tripping over this.With this release, esbuild will now omit packages from the bundle by default when the platform is
node
(i.e. the previous behavior of--packages=external
is now the default in this case). Note that your dependencies must now be present on the file system when your bundle is run. If you don't want this behavior, you can do--packages=bundle
to allow packages to be included in the bundle (i.e. the previous default behavior). Note that--packages=bundle
doesn't mean all packages are bundled, just that packages are allowed to be bundled. You can still exclude individual packages from the bundle using--external:
even when--packages=bundle
is present.The
--packages=
setting considers all import paths that "look like" package imports in the original source code to be package imports. Specifically import paths that don't start with a path segment of/
or.
or..
are considered to be package imports. The only two exceptions to this rule are subpath imports (which start with a#
character) and TypeScript path remappings viapaths
and/orbaseUrl
intsconfig.json
(which are applied first). -
Drop support for older platforms (#3802)
This release drops support for the following operating systems:
- Windows 7
- Windows 8
- Windows Server 2008
- Windows Server 2012
This is because the Go programming language dropped support for these operating system versions in Go 1.21, and this release updates esbuild from Go 1.20 to Go 1.22.
Note that this only affects the binary esbuild executables that are published to the
esbuild
npm package. It's still possible to compile esbuild's source code for these older operating systems. If you need to, you can compile esbuild for yourself using an older version of the Go compiler (before Go version 1.21). That might look something like this:git clone https://github.com/evanw/esbuild.git cd esbuild go build ./cmd/esbuild ./esbuild.exe --version
In addition, this release increases the minimum required node version for esbuild's JavaScript API from node 12 to node 18. Node 18 is the oldest version of node that is still being supported (see node's release schedule for more information). This increase is because of an incompatibility between the JavaScript that the Go compiler generates for the
esbuild-wasm
package and versions of node before node 17.4 (specifically thecrypto.getRandomValues
function). -
Update
await using
behavior to match TypeScriptTypeScript 5.5 subtly changes the way
await using
behaves. This release updates esbuild to match these changes in TypeScript. You can read more about these changes in microsoft/TypeScript#58624. -
Allow
es2024
as a target environmentThe ECMAScript 2024 specification was just approved, so it has been added to esbuild as a possible compilation target. You can read more about the features that it adds here: https://2ality.com/2024/06/ecmascript-2024.html. The only addition that's relevant for esbuild is the regular expression
/v
flag. With--target=es2024
, regular expressions that use the/v
flag will now be passed through untransformed instead of being transformed into a call tonew RegExp
. -
Publish binaries for OpenBSD on 64-bit ARM (#3665, #3674)
With this release, you should now be able to install the
esbuild
npm package in OpenBSD on 64-bit ARM, such as on an Apple device with an M1 chip.This was contributed by @ikmckenz.
-
Publish binaries for WASI (WebAssembly System Interface) preview 1 (#3300, #3779)
The upcoming WASI (WebAssembly System Interface) standard is going to be a way to run WebAssembly outside of a JavaScript host environment. In this scenario you only need a
.wasm
file without any supporting JavaScript code. Instead of JavaScript providing the APIs for the host environment, the WASI standard specifies a "system interface" that WebAssembly code can access directly (e.g. for file system access).Development versions of the WASI specification are being released using preview numbers. The people behind WASI are currently working on preview 2 but the Go compiler has released support for preview 1, which from what I understand is now considered an unsupported legacy release. However, some people have requested that esbuild publish binary executables that support WASI preview 1 so they can experiment with them.
This release publishes esbuild precompiled for WASI preview 1 to the
@esbuild/wasi-preview1
package on npm (specifically the file@esbuild/wasi-preview1/esbuild.wasm
). This binary executable has not been tested and won't be officially supported, as it's for an old preview release of a specification that has since moved in another direction. If it works for you, great! If not, then you'll likely have to wait for the ecosystem to evolve before using esbuild with WASI. For example, it sounds like perhaps WASI preview 1 doesn't include support for opening network sockets so esbuild's local development server is unlikely to work with WASI preview 1. -
Warn about
onResolve
plugins not setting a path (#3790)Plugins that return values from
onResolve
without resolving the path (i.e. without setting eitherpath
orexternal: true
) will now cause a warning. This is because esbuild only uses return values fromonResolve
if it successfully resolves the path, and it's not good for invalid input to be silently ignored. -
Add a new Go API for running the CLI with plugins (#3539)
With esbuild's Go API, you can now call
cli.RunWithPlugins(args, plugins)
to pass an array of esbuild plugins to be used during the build process. This allows you to create a CLI that behaves similarly to esbuild's CLI but with additional Go plugins enabled.This was contributed by @edewit.
v0.21.5
-
Fix
Symbol.metadata
on classes without a class decorator (#3781)This release fixes a bug with esbuild's support for the decorator metadata proposal. Previously esbuild only added the
Symbol.metadata
property to decorated classes if there was a decorator on the class element itself. However, the proposal says that theSymbol.metadata
property should be present on all classes that have any decorators at all, not just those with a decorator on the class element itself. -
Allow unknown import attributes to be used with the
copy
loader (#3792)Import attributes (the
with
keyword onimport
statements) are allowed to alter how that path is loaded. For example, esbuild cannot assume that it knows how to load./bagel.js
as typebagel
:// This is an error with "--bundle" without also using "--external:./bagel.js" import tasty from "./bagel.js" with { type: "bagel" }
Because of that, bundling this code with esbuild is an error unless the file
./bagel.js
is external to the bundle (such as with--bundle --external:./bagel.js
).However, there is an additional case where it's ok for esbuild to allow this: if the file is loaded using the
copy
loader. That's because thecopy
loader behaves similarly to--external
in that the file is left external to the bundle. The difference is that thecopy
loader copies the file into the output folder and rewrites the import path while--external
doesn't. That means the following will now work with thecopy
loader (such as with--bundle --loader:.bagel=copy
):// This is no longer an error with "--bundle" and "--loader:.bagel=copy" import tasty from "./tasty.bagel" with { type: "bagel" }
-
Support import attributes with glob-style imports (#3797)
This release adds support for import attributes (the
with
option) to glob-style imports (dynamic imports with certain string literal patterns as paths). These imports previously didn't support import attributes due to an oversight. So code like this will now work correctly:async function loadLocale(locale: string): Locale { const data = await import(`./locales/${locale}.data`, { with: { type: 'json' } }) return unpackLocale(locale, data) }
Previously this didn't work even though esbuild normally supports forcing the JSON loader using an import attribute. Attempting to do this used to result in the following error:
✘ [ERROR] No loader is configured for ".data" files: locales/en-US.data example.ts:2:28: 2 │ const data = await import(`./locales/${locale}.data`, { with: { type: 'json' } }) ╵ ~~~~~~~~~~~~~~~~~~~~~~~~~~
In addition, this change means plugins can now access the contents of
with
for glob-style imports. -
Support
${configDir}
intsconfig.json
files (#3782)This adds support for a new feature from the upcoming TypeScript 5.5 release. The character sequence
${configDir}
is now respected at the start ofbaseUrl
andpaths
values, which are used by esbuild during bundling to correctly map import paths to file system paths. This feature lets basetsconfig.json
files specified viaextends
refer to the directory of the top-leveltsconfig.json
file. Here is an example:{ "compilerOptions": { "paths": { "js/*": ["${configDir}/dist/js/*"] } } }
You can read more in TypeScript's blog post about their upcoming 5.5 release. Note that this feature does not make use of template literals (you need to use
"${configDir}/dist/js/*"
not`${configDir}/dist/js/*`
). The syntax fortsconfig.json
is still just JSON with comments, and JSON syntax does not allow template literals. This feature only recognizes${configDir}
in strings for certain path-like properties, and only at the beginning of the string. -
Fix internal error with
--supported:object-accessors=false
(#3794)This release fixes a regression in 0.21.0 where some code that was added to esbuild's internal runtime library of helper functions for JavaScript decorators fails to parse when you configure esbuild with
--supported:object-accessors=false
. The reason is that esbuild introduced code that does{ get [name]() {} }
which uses both theobject-extensions
feature for the[name]
and theobject-accessors
feature for theget
, but esbuild was incorrectly only checking forobject-extensions
and not forobject-accessors
. Additional tests have been added to avoid this type of issue in the future. A workaround for this issue in earlier releases is to also add--supported:object-extensions=false
.
v0.21.4
-
Update support for import assertions and import attributes in node (#3778)
Import assertions (the
assert
keyword) have been removed from node starting in v22.0.0. So esbuild will now strip them and generate a warning with--target=node22
or above:▲ [WARNING] The "assert" keyword is not supported in the configured target environment ("node22") [assert-to-with] example.mjs:1:40: 1 │ import json from "esbuild/package.json" assert { type: "json" } │ ~~~~~~ ╵ with Did you mean to use "with" instead of "assert"?
Import attributes (the
with
keyword) have been backported to node 18 starting in v18.20.0. So esbuild will no longer strip them with--target=node18.N
ifN
is 20 or greater. -
Fix
for await
transform when a label is presentThis release fixes a bug where the
for await
transform, which wraps the loop in atry
statement, previously failed to also move the loop's label into thetry
statement. This bug only affects code that uses both of these features in combination. Here's an example of some affected code:// Original code async function test() { outer: for await (const x of [Promise.resolve([0, 1])]) { for (const y of x) if (y) break outer throw 'fail' } } // Old output (with --target=es6) function test() { return __async(this, null, function* () { outer: try { for (var iter = __forAwait([Promise.resolve([0, 1])]), more, temp, error; more = !(temp = yield iter.next()).done; more = false) { const x = temp.value; for (const y of x) if (y) break outer; throw "fail"; } } catch (temp) { error = [temp]; } finally { try { more && (temp = iter.return) && (yield temp.call(iter)); } finally { if (error) throw error[0]; } } }); } // New output (with --target=es6) function test() { return __async(this, null, function* () { try { outer: for (var iter = __forAwait([Promise.resolve([0, 1])]), more, temp, error; more = !(temp = yield iter.next()).done; more = false) { const x = temp.value; for (const y of x) if (y) break outer; throw "fail"; } } catch (temp) { error = [temp]; } finally { try { more && (temp = iter.return) && (yield temp.call(iter)); } finally { if (error) throw error[0]; } } }); }
-
Do additional constant folding after cross-module enum inlining (#3416, #3425)
This release adds a few more cases where esbuild does constant folding after cross-module enum inlining.
// Original code: enum.ts export enum Platform { WINDOWS = 'windows', MACOS = 'macos', LINUX = 'linux', } // Original code: main.ts import { Platform } from './enum'; declare const PLATFORM: string; export function logPlatform() { if (PLATFORM == Platform.WINDOWS) console.log('Windows'); else if (PLATFORM == Platform.MACOS) console.log('macOS'); else if (PLATFORM == Platform.LINUX) console.log('Linux'); else console.log('Other'); } // Old output (with --bundle '--define:PLATFORM="macos"' --minify --format=esm) function n(){"windows"=="macos"?console.log("Windows"):"macos"=="macos"?console.log("macOS"):"linux"=="macos"?console.log("Linux"):console.log("Other")}export{n as logPlatform}; // New output (with --bundle '--define:PLATFORM="macos"' --minify --format=esm) function n(){console.log("macOS")}export{n as logPlatform};
-
Pass import attributes to on-resolve plugins (#3384, #3639, #3646)
With this release, on-resolve plugins will now have access to the import attributes on the import via the
with
property of the arguments object. This mirrors thewith
property of the arguments object that's already passed to on-load plugins. In addition, you can now passwith
to theresolve()
API call which will then forward that value on to all relevant plugins. Here's an example of a plugin that can now be written:const examplePlugin = { name: 'Example plugin', setup(build) { build.onResolve({ filter: /.*/ }, args => { if (args.with.type === 'external') return { external: true } }) } } require('esbuild').build({ stdin: { contents: ` import foo from "./foo" with { type: "external" } foo() `, }, bundle: true, format: 'esm', write: false, plugins: [examplePlugin], }).then(result => { console.log(result.outputFiles[0].text) })
-
Formatting support for the
@position-try
rule (#3773)Chrome shipped this new CSS at-rule in version 125 as part of the CSS anchor positioning API. With this release, esbuild now knows to expect a declaration list inside of the
@position-try
body block and will format it appropriately. -
Always allow internal string import and export aliases (#3343)
Import and export names can be string literals in ES2022+. Previously esbuild forbid any usage of these aliases when the target was below ES2022. Starting with this release, esbuild will only forbid such usage when the alias would otherwise end up in output as a string literal. String literal aliases that are only used internally in the bundle and are "compiled away" are no longer errors. This makes it possible to use string literal aliases with esbuild's
inject
feature even when the target is earlier than ES2022.
v0.21.3
-
Implement the decorator metadata proposal (#3760)
This release implements the decorator metadata proposal, which is a sub-proposal of the decorators proposal. Microsoft shipped the decorators proposal in TypeScript 5.0 and the decorator metadata proposal in TypeScript 5.2, so it's important that esbuild also supports both of these features. Here's a quick example:
// Shim the "Symbol.metadata" symbol Symbol.metadata ??= Symbol('Symbol.metadata') const track = (_, context) => { (context.metadata.names ||= []).push(context.name) } class Foo { @​track foo = 1 @​track bar = 2 } // Prints ["foo", "bar"] console.log(Foo[Symbol.metadata].names)
⚠ ️ WARNING⚠ ️This proposal has been marked as "stage 3" which means "recommended for implementation". However, it's still a work in progress and isn't a part of JavaScript yet, so keep in mind that any code that uses JavaScript decorator metadata may need to be updated as the feature continues to evolve. If/when that happens, I will update esbuild's implementation to match the specification. I will not be supporting old versions of the specification.
-
Fix bundled decorators in derived classes (#3768)
In certain cases, bundling code that uses decorators in a derived class with a class body that references its own class name could previously generate code that crashes at run-time due to an incorrect variable name. This problem has been fixed. Here is an example of code that was compiled incorrectly before this fix:
class Foo extends Object { @​(x => x) foo() { return Foo } } console.log(new Foo().foo())
-
Fix
tsconfig.json
files inside symlinked directories (#3767)This release fixes an issue with a scenario involving a
tsconfig.json
file thatextends
another file from within a symlinked directory that uses thepaths
feature. In that case, the implicitbaseURL
value should be based on the real path (i.e. after expanding all symbolic links) instead of the original path. This was already done for other files that esbuild resolves but was not yet done fortsconfig.json
because it's special-cased (the regular path resolver can't be used because the information insidetsconfig.json
is involved in path resolution). Note that this fix no longer applies if the--preserve-symlinks
setting is enabled.
v0.21.2
-
Correct
this
in field and accessor decorators (#3761)This release changes the value of
this
in initializers for class field and accessor decorators from the module-levelthis
value to the appropriatethis
value for the decorated element (either the class or the instance). It was previously incorrect due to lack of test coverage. Here's an example of a decorator that doesn't work without this change:const dec = () => function() { this.bar = true } class Foo { @​dec static foo } console.log(Foo.bar) // Should be "true"
-
Allow
es2023
as a target environment (#3762)TypeScript recently added
es2023
as a compilation target, so esbuild now supports this too. There is no difference between a target ofes2022
andes2023
as far as esbuild is concerned since the 2023 edition of JavaScript doesn't introduce any new syntax features.
v0.21.1
-
Fix a regression with
--keep-names
(#3756)The previous release introduced a regression with the
--keep-names
setting and object literals withget
/set
accessor methods, in which case the generated code contained syntax errors. This release fixes the regression:// Original code x = { get y() {} } // Output from version 0.21.0 (with --keep-names) x = { get y: /* @​__PURE__ */ __name(function() { }, "y") }; // Output from this version (with --keep-names) x = { get y() { } };
v0.21.0
This release doesn't contain any deliberately-breaking changes. However, it contains a very complex new feature and while all of esbuild's tests pass, I would not be surprised if an important edge case turns out to be broken. So I'm releasing this as a breaking change release to avoid causing any trouble. As usual, make sure to test your code when you upgrade.
-
Implement the JavaScript decorators proposal (#104)
With this release, esbuild now contains an implementation of the upcoming JavaScript decorators proposal. This is the same feature that shipped in TypeScript 5.0 and has been highly-requested on esbuild's issue tracker. You can read more about them in that blog post and in this other (now slightly outdated) extensive blog post here: https://2ality.com/2022/10/javascript-decorators.html. Here's a quick example:
const log = (fn, context) => function() { console.log(`before ${context.name}`) const it = fn.apply(this, arguments) console.log(`after ${context.name}`) return it } class Foo { @​log static foo() { console.log('in foo') } } // Logs "before foo", "in foo", "after foo" Foo.foo()
Note that this feature is different than the existing "TypeScript experimental decorators" feature that esbuild already implements. It uses similar syntax but behaves very differently, and the two are not compatible (although it's sometimes possible to write decorators that work with both). TypeScript experimental decorators will still be supported by esbuild going forward as they have been around for a long time, are very widely used, and let you do certain things that are not possible with JavaScript decorators (such as decorating function parameters). By default esbuild will parse and transform JavaScript decorators, but you can tell esbuild to parse and transform TypeScript experimental decorators instead by setting
"experimentalDecorators": true
in yourtsconfig.json
file.Probably at least half of the work for this feature went into creating a test suite that exercises many of the proposal's edge cases: https://github.com/evanw/decorator-tests. It has given me a reasonable level of confidence that esbuild's initial implementation is acceptable. However, I don't have access to a significant sample of real code that uses JavaScript decorators. If you're currently using JavaScript decorators in a real code base, please try out esbuild's implementation and let me know if anything seems off.
⚠ ️ WARNING⚠ ️This proposal has been in the works for a very long time (work began around 10 years ago in 2014) and it is finally getting close to becoming part of the JavaScript language. However, it's still a work in progress and isn't a part of JavaScript yet, so keep in mind that any code that uses JavaScript decorators may need to be updated as the feature continues to evolve. The decorators proposal is pretty close to its final form but it can and likely will undergo some small behavioral adjustments before it ends up becoming a part of the standard. If/when that happens, I will update esbuild's implementation to match the specification. I will not be supporting old versions of the specification.
-
Optimize the generated code for private methods
Previously when lowering private methods for old browsers, esbuild would generate one
WeakSet
for each private method. This mirrors similar logic for generating oneWeakSet
for each private field. Using a separateWeakMap
for private fields is necessary as their assignment can be observable:let it class Bar { constructor() { it = this } } class Foo extends Bar { #x = 1 #y = null.foo static check() { console.log(#x in it, #y in it) } } try { new Foo } catch {} Foo.check()
This prints
true false
because this partially-initialized instance has#x
but not#y
. In other words, it's not true that all class instances will always have all of their private fields. However, the assignment of private methods to a class instance is not observable. In other words, it's true that all class instances will always have all of their private methods. This means esbuild can lower private methods into code where all methods share a singleWeakSet
, which is smaller, faster, and uses less memory. Other JavaScript processing tools such as the TypeScript compiler already make this optimization. Here's what this change looks like:// Original code class Foo { #x() { return this.#x() } #y() { return this.#y() } #z() { return this.#z() } } // Old output (--supported:class-private-method=false) var _x, x_fn, _y, y_fn, _z, z_fn; class Foo { constructor() { __privateAdd(this, _x); __privateAdd(this, _y); __privateAdd(this, _z); } } _x = new WeakSet(); x_fn = function() { return __privateMethod(this, _x, x_fn).call(this); }; _y = new WeakSet(); y_fn = function() { return __privateMethod(this, _y, y_fn).call(this); }; _z = new WeakSet(); z_fn = function() { return __privateMethod(this, _z, z_fn).call(this); }; // New output (--supported:class-private-method=false) var _Foo_instances, x_fn, y_fn, z_fn; class Foo { constructor() { __privateAdd(this, _Foo_instances); } } _Foo_instances = new WeakSet(); x_fn = function() { return __privateMethod(this, _Foo_instances, x_fn).call(this); }; y_fn = function() { return __privateMethod(this, _Foo_instances, y_fn).call(this); }; z_fn = function() { return __privateMethod(this, _Foo_instances, z_fn).call(this); };
-
Fix an obscure bug with lowering class members with computed property keys
When class members that use newer syntax features are transformed for older target environments, they sometimes need to be relocated. However, care must be taken to not reorder any side effects caused by computed property keys. For example, the following code must evaluate
a()
thenb()
thenc()
:class Foo { [a()]() {} [b()]; static { c() } }
Previously esbuild did this by shifting the computed property key forward to the next spot in the evaluation order. Classes evaluate all computed keys first and then all static class elements, so if the last computed key needs to be shifted, esbuild previously inserted a static block at start of the class body, ensuring it came before all other static class elements:
var _a; class Foo { constructor() { __publicField(this, _a); } static { _a = b(); } [a()]() { } static { c(); } }
However, this could cause esbuild to accidentally generate a syntax error if the computed property key contains code that isn't allowed in a static block, such as an
await
expression. With this release, esbuild fixes this problem by shifting the computed property key backward to the previous spot in the evaluation order instead, which may push it into theextends
clause or even before the class itself:// Original code class Foo { [a()]() {} [await b()]; static { c() } } // Old output (with --supported:class-field=false) var _a; class Foo { constructor() { __publicField(this, _a); } static { _a = await b(); } [a()]() { } static { c(); } } // New output (with --supported:class-field=false) var _a, _b; class Foo { constructor() { __publicField(this, _a); } [(_b = a(), _a = await b(), _b)]() { } static { c(); } }
-
Fix some
--keep-names
edge casesThe
NamedEvaluation
syntax-directed operation in the JavaScript specification gives certain anonymous expressions aname
property depending on where they are in the syntax tree. For example, the following initializers convey aname
value:var foo = function() {} var bar = class {} console.log(foo.name, bar.name)
When you enable esbuild's
--keep-names
setting, esbuild generates additional code to represent thisNamedEvaluation
operation so that the value of thename
property persists even when the identifiers are renamed (e.g. due to minification).However, I recently learned that esbuild's implementation of
NamedEvaluation
is missing a few cases. Specifically esbuild was missing property definitions, class initializers, logical-assignment operators. These cases should now all be handled:var obj = { foo: function() {} } class Foo0 { foo = function() {} } class Foo1 { static foo = function() {} } class Foo2 { accessor foo = function() {} } class Foo3 { static accessor foo = function() {} } foo ||= function() {} foo &&= function() {} foo ??= function() {}
v0.20.2
-
Support TypeScript experimental decorators on
abstract
class fields (#3684)With this release, you can now use TypeScript experimental decorators on
abstract
class fields. This was silently compiled incorrectly in esbuild 0.19.7 and below, and was an error from esbuild 0.19.8 to esbuild 0.20.1. Code such as the following should now work correctly:// Original code const log = (x: any, y: string) => console.log(y) abstract class Foo { @​log abstract foo: string } new class extends Foo { foo = '' } // Old output (with --loader=ts --tsconfig-raw={\"compilerOptions\":{\"experimentalDecorators\":true}}) const log = (x, y) => console.log(y); class Foo { } new class extends Foo { foo = ""; }(); // New output (with --loader=ts --tsconfig-raw={\"compilerOptions\":{\"experimentalDecorators\":true}}) const log = (x, y) => console.log(y); class Foo { } __decorateClass([ log ], Foo.prototype, "foo", 2); new class extends Foo { foo = ""; }();
-
JSON loader now preserves
__proto__
properties (#3700)Copying JSON source code into a JavaScript file will change its meaning if a JSON object contains the
__proto__
key. A literal__proto__
property in a JavaScript object literal sets the prototype of the object instead of adding a property named__proto__
, while a literal__proto__
property in a JSON object literal just adds a property named__proto__
. With this release, esbuild will now work around this problem by converting JSON to JavaScript with a computed property key in this case:// Original code import data from 'data:application/json,{"__proto__":{"fail":true}}' if (Object.getPrototypeOf(data)?.fail) throw 'fail' // Old output (with --bundle) (() => { // <data:application/json,{"__proto__":{"fail":true}}> var json_proto_fail_true_default = { __proto__: { fail: true } }; // entry.js if (Object.getPrototypeOf(json_proto_fail_true_default)?.fail) throw "fail"; })(); // New output (with --bundle) (() => { // <data:application/json,{"__proto__":{"fail":true}}> var json_proto_fail_true_default = { ["__proto__"]: { fail: true } }; // example.mjs if (Object.getPrototypeOf(json_proto_fail_true_default)?.fail) throw "fail"; })();
-
Improve dead code removal of
switch
statements (#3659)With this release, esbuild will now remove
switch
statements in branches when minifying if they are known to never be evaluated:// Original code if (true) foo(); else switch (bar) { case 1: baz(); break } // Old output (with --minify) if(1)foo();else switch(bar){case 1:} // New output (with --minify) foo();
-
Empty enums should behave like an object literal (#3657)
TypeScript allows you to create an empty enum and add properties to it at run time. While people usually use an empty object literal for this instead of a TypeScript enum, esbuild's enum transform didn't anticipate this use case and generated
undefined
instead of{}
for an empty enum. With this release, you can now use an empty enum to generate an empty object literal.// Original code enum Foo {} // Old output (with --loader=ts) var Foo = /* @​__PURE__ */ ((Foo2) => { })(Foo || {}); // New output (with --loader=ts) var Foo = /* @​__PURE__ */ ((Foo2) => { return Foo2; })(Foo || {});
-
Handle Yarn Plug'n'Play edge case with
tsconfig.json
(#3698)Previously a
tsconfig.json
file thatextends
another file in a package with anexports
map failed to work when Yarn's Plug'n'Play resolution was active. This edge case should work now starting with this release. -
Work around issues with Deno 1.31+ (#3682)
Version 0.20.0 of esbuild changed how the esbuild child process is run in esbuild's API for Deno. Previously it used
Deno.run
but that API is being removed in favor ofDeno.Command
. As part of this change, esbuild is now calling the newunref
function on esbuild's long-lived child process, which is supposed to allow Deno to exit when your code has finished running even though the child process is still around (previously you had to explicitly call esbuild'sstop()
function to terminate the child process for Deno to be able to exit).However, this introduced a problem for Deno's testing API which now fails some tests that use esbuild with
error: Promise resolution is still pending but the event loop has already resolved
. It's unclear to me why this is happening. The call tounref
was recommended by someone on the Deno core team, and calling Node's equivalentunref
API has been working fine for esbuild in Node for a long time. It could be that I'm using it incorrectly, or that there's some reference counting and/or garbage collection bug in Deno's internals, or that Deno'sunref
just works differently than Node'sunref
. In any case, it's not good for Deno tests that use esbuild to be failing.In this release, I am removing the call to
unref
to fix this issue. This means that you will now have to call esbuild'sstop()
function to allow Deno to exit, just like you did before esbuild version 0.20.0 when this regression was introduced.Note: This regression wasn't caught earlier because Deno doesn't seem to fail tests that have outstanding
setTimeout
calls, which esbuild's test harness was using to enforce a maximum test runtime. Adding asetTimeout
was allowing esbuild's Deno tests to succeed. So this regression doesn't necessarily apply to all people using tests in Deno.
v0.20.1
-
Fix a bug with the CSS nesting transform (#3648)
This release fixes a bug with the CSS nesting transform for older browsers where the generated CSS could be incorrect if a selector list contained a pseudo element followed by another selector. The bug was caused by incorrectly mutating the parent rule's selector list when filtering out pseudo elements for the child rules:
/* Original code */ .foo { &:after, & .bar { color: red; } } /* Old output (with --supported:nesting=false) */ .foo .bar, .foo .bar { color: red; } /* New output (with --supported:nesting=false) */ .foo:after, .foo .bar { color: red; }
-
Constant folding for JavaScript inequality operators (#3645)
This release introduces constant folding for the
< > <= >=
operators. The minifier will now replace these operators withtrue
orfalse
when both sides are compile-time numeric or string constants:// Original code console.log(1 < 2, '🍕' > '🧀') // Old output (with --minify) console.log(1<2,"🍕">"🧀"); // New output (with --minify) console.log(!0,!1);
-
Better handling of
__proto__
edge cases (#3651)JavaScript object literal syntax contains a special case where a non-computed property with a key of
__proto__
sets the prototype of the object. This does not apply to computed properties or to properties that use the shorthand property syntax introduced in ES6. Previously esbuild didn't correctly preserve the "sets the prototype" status of properties inside an object literal, meaning a property that sets the prototype could accidentally be transformed into one that doesn't and vice versa. This has now been fixed:// Original code function foo(__proto__) { return { __proto__: __proto__ } // Note: sets the prototype } function bar(__proto__, proto) { { let __proto__ = proto return { __proto__ } // Note: doesn't set the prototype } } // Old output function foo(__proto__) { return { __proto__ }; // Note: no longer sets the prototype (WRONG) } function bar(__proto__, proto) { { let __proto__2 = proto; return { __proto__: __proto__2 }; // Note: now sets the prototype (WRONG) } } // New output function foo(__proto__) { return { __proto__: __proto__ }; // Note: sets the prototype (correct) } function bar(__proto__, proto) { { let __proto__2 = proto; return { ["__proto__"]: __proto__2 }; // Note: doesn't set the prototype (correct) } }
-
Fix cross-platform non-determinism with CSS color space transformations (#3650)
The Go compiler takes advantage of "fused multiply and add" (FMA) instructions on certain processors which do the operation
x*y + z
without intermediate rounding. This causes esbuild's CSS color space math to differ on different processors (currentlyppc64le
ands390x
), which breaks esbuild's guarantee of deterministic output. To avoid this, esbuild's color space math now inserts afloat64()
cast around every single math operation. This tells the Go compiler not to use the FMA optimization. -
Fix a crash when resolving a path from a directory that doesn't exist (#3634)
This release fixes a regression where esbuild could crash when resolving an absolute path if the source directory for the path resolution operation doesn't exist. While this situation doesn't normally come up, it could come up when running esbuild concurrently with another operation that mutates the file system as esbuild is doing a build (such as using
git
to switch branches). The underlying problem was a regression that was introduced in version 0.18.0.
v0.20.0
This release deliberately contains backwards-incompatible changes. To avoid automatically picking up releases like this, you should either be pinning the exact version of esbuild
in your package.json
file (recommended) or be using a version range syntax that only accepts patch upgrades such as ^0.19.0
or ~0.19.0
. See npm's documentation about semver for more information.
This time there is only one breaking change, and it only matters for people using Deno. Deno tests that use esbuild will now fail unless you make the change described below.
-
Work around API deprecations in Deno 1.40.x (#3609, #3611)
Deno 1.40.0 was just released and introduced run-time warnings about certain APIs that esbuild uses. With this release, esbuild will work around these run-time warnings by using newer APIs if they are present and falling back to the original APIs otherwise. This should avoid the warnings without breaking compatibility with older versions of Deno.
Unfortunately, doing this introduces a breaking change. The newer child process APIs lack a way to synchronously terminate esbuild's child process, so calling
esbuild.stop()
from within a Deno test is no longer sufficient to prevent Deno from failing a test that uses esbuild's API (Deno fails tests that create a child process without killing it before the test ends). To work around this, esbuild'sstop()
function has been changed to return a promise, and you now have to changeesbuild.stop()
toawait esbuild.stop()
in all of your Deno tests. -
Reorder implicit file extensions within
node_modules
(#3341, #3608)In version 0.18.0, esbuild changed the behavior of implicit file extensions within
node_modules
directories (i.e. in published packages) to prefer.js
over.ts
even when the--resolve-extensions=
order prefers.ts
over.js
(which it does by default). However, doing that also accidentally made esbuild prefer.css
over.ts
, which caused problems for people that published packages containing both TypeScript and CSS in files with the same name.With this release, esbuild will reorder TypeScript file extensions immediately after the last JavaScript file extensions in the implicit file extension order instead of putting them at the end of the order. Specifically the default implicit file extension order is
.tsx,.ts,.jsx,.js,.css,.json
which used to become.jsx,.js,.css,.json,.tsx,.ts
innode_modules
directories. With this release it will now become.jsx,.js,.tsx,.ts,.css,.json
instead.Why even rewrite the implicit file extension order at all? One reason is because the
.js
file is more likely to behave correctly than the.ts
file. The behavior of the.ts
file may depend ontsconfig.json
and thetsconfig.json
file may not even be published, or may useextends
to refer to a basetsconfig.json
file that wasn't published. People can get into this situation when they forget to add all.ts
files to their.npmignore
file before publishing to npm. Picking.js
over.ts
helps make it more likely that resulting bundle will behave correctly.
v0.19.12
-
The "preserve" JSX mode now preserves JSX text verbatim (#3605)
The JSX specification deliberately doesn't specify how JSX text is supposed to be interpreted and there is no canonical way to interpret JSX text. Two most popular interpretations are Babel and TypeScript. Yes they are different (esbuild deliberately follows TypeScript by the way).
Previously esbuild normalized text to the TypeScript interpretation when the "preserve" JSX mode is active. However, "preserve" should arguably reproduce the original JSX text verbatim so that whatever JSX transform runs after esbuild is free to interpret it however it wants. So with this release, esbuild will now pass JSX text through unmodified:
// Original code let el = <a href={'/'} title=''"'> some text {foo} more text </a> // Old output (with --loader=jsx --jsx=preserve) let el = <a href="/" title={`'"`}> {" some text"} {foo} {"more text "} </a>; // New output (with --loader=jsx --jsx=preserve) let el = <a href={"/"} title=''"'> some text {foo} more text </a>;
-
Allow JSX elements as JSX attribute values
JSX has an obscure feature where you can use JSX elements in attribute position without surrounding them with
{...}
. It looks like this:let el = <div data-ab=<><a/><b/></>/>;
I think I originally didn't implement it even though it's part of the JSX specification because it previously didn't work in TypeScript (and potentially also in Babel?). However, support for it was silently added in TypeScript 4.8 without me noticing and Babel has also since fixed their bugs regarding this feature. So I'm adding it to esbuild too now that I know it's widely supported.
Keep in mind that there is some ongoing discussion about removing this feature from JSX. I agree that the syntax seems out of place (it does away with the elegance of "JSX is basically just XML with
{...}
escapes" for something arguably harder to read, which doesn't seem like a good trade-off), but it's in the specification and TypeScript and Babel both implement it so I'm going to have esbuild implement it too. However, I reserve the right to remove it from esbuild if it's ever removed from the specification in the future. So use it with caution. -
Fix a bug with TypeScript type parsing (#3574)
This release fixes a bug with esbuild's TypeScript parser where a conditional type containing a union type that ends with an infer type that ends with a constraint could fail to parse. This was caused by the "don't parse a conditional type" flag not getting passed through the union type parser. Here's an example of valid TypeScript code that previously failed to parse correctly:
type InferUnion<T> = T extends { a: infer U extends number } | infer U extends number ? U : never
v0.19.11
-
Fix TypeScript-specific class transform edge case (#3559)
The previous release introduced an optimization that avoided transforming
super()
in the class constructor for TypeScript code compiled withuseDefineForClassFields
set tofalse
if all class instance fields have no initializers. The rationale was that in this case, all class instance fields are omitted in the output so no changes to the constructor are needed. However, if all of this is the case and there are#private
instance fields with initializers, those private instance field initializers were still being moved into the constructor. This was problematic because they were being inserted before the call tosuper()
(sincesuper()
is now no longer transformed in that case). This release introduces an additional optimization that avoids moving the private instance field initializers into the constructor in this edge case, which generates smaller code, matches the TypeScript compiler's output more closely, and avoids this bug:// Original code class Foo extends Bar { #private = 1; public: any; constructor() { super(); } } // Old output (with esbuild v0.19.9) class Foo extends Bar { constructor() { super(); this.#private = 1; } #private; } // Old output (with esbuild v0.19.10) class Foo extends Bar { constructor() { this.#private = 1; super(); } #private; } // New output class Foo extends Bar { #private = 1; constructor() { super(); } }
-
Minifier: allow reording a primitive past a side-effect (#3568)
The minifier previously allowed reordering a side-effect past a primitive, but didn't handle the case of reordering a primitive past a side-effect. This additional case is now handled:
// Original code function f() { let x = false; let y = x; const boolean = y; let frag = $.template(`<p contenteditable="${boolean}">hello world</p>`); return frag; } // Old output (with --minify) function f(){const e=!1;return $.template(`<p contenteditable="${e}">hello world</p>`)} // New output (with --minify) function f(){return $.template('<p contenteditable="false">hello world</p>')}
-
Minifier: consider properties named using known
Symbol
instances to be side-effect free (#3561)Many things in JavaScript can have side effects including property accesses and ToString operations, so using a symbol such as
Symbol.iterator
as a computed property name is not obviously side-effect free. This release adds a special case for knownSymbol
instances so that they are considered side-effect free when used as property names. For example, this class declaration will now be considered side-effect free:class Foo { *[Symbol.iterator]() { } }
-
Provide the
stop()
API in node to exit esbuild's child process (#3558)You can now call
stop()
in esbuild's node API to exit esbuild's child process to reclaim the resources used. It only makes sense to do this for a long-lived node process when you know you will no longer be making any more esbuild API calls. It is not necessary to call this to allow node to exit, and it's advantageous to not call this in between calls to esbuild's API as sharing a single long-lived esbuild child process is more efficient than re-creating a new esbuild child process for every API call. This API call used to exist but was removed in version 0.9.0. This release adds it back due to a user request.
v0.19.10
-
Fix glob imports in TypeScript files (#3319)
This release fixes a problem where bundling a TypeScript file containing a glob import could emit a call to a helper function that doesn't exist. The problem happened because esbuild's TypeScript transformation removes unused imports (which is required for correctness, as they may be type-only imports) and esbuild's glob import transformation wasn't correctly marking the imported helper function as used. This wasn't caught earlier because most of esbuild's glob import tests were written in JavaScript, not in TypeScript.
-
Fix
require()
glob imports with bundling disabled (#3546)Previously
require()
calls containing glob imports were incorrectly transformed when bundling was disabled. All glob imports should only be transformed when bundling is enabled. This bug has been fixed. -
Fix a panic when transforming optional chaining with
define
(#3551, #3554)This release fixes a case where esbuild could crash with a panic, which was triggered by using
define
to replace an expression containing an optional chain. Here is an example:// Original code console.log(process?.env.SHELL) // Old output (with --define:process.env={}) /* panic: Internal error (while parsing "<stdin>") */ // New output (with --define:process.env={}) var define_process_env_default = {}; console.log(define_process_env_default.SHELL);
This fix was contributed by @hi-ogawa.
-
Work around a bug in node's CommonJS export name detector (#3544)
The export names of a CommonJS module are dynamically-determined at run time because CommonJS exports are properties on a mutable object. But the export names of an ES module are statically-determined at module instantiation time by using
import
andexport
syntax and cannot be changed at run time.When you import a CommonJS module into an ES module in node, node scans over the source code to attempt to detect the set of export names that the CommonJS module will end up using. That statically-determined set of names is used as the set of names that the ES module is allowed to import at module instantiation time. However, this scan appears to have bugs (or at least, can cause false positives) because it doesn't appear to do any scope analysis. Node will incorrectly consider the module to export something even if the assignment is done to a local variable instead of to the module-level
exports
object. For example:// confuseNode.js exports.confuseNode = function(exports) { // If this local is called "exports", node incorrectly // thinks this file has an export called "notAnExport". exports.notAnExport = function() { }; };
You can see that node incorrectly thinks the file
confuseNode.js
has an export callednotAnExport
when that file is loaded in an ES module context:$ node -e 'import("./confuseNode.js").then(console.log)' [Module: null prototype] { confuseNode: [Function (anonymous)], default: { confuseNode: [Function (anonymous)] }, notAnExport: undefined }
To avoid this, esbuild will now rename local variables that use the names
exports
andmodule
when generating CommonJS output for thenode
platform. -
Fix the return value of esbuild's
super()
shim (#3538)Some people write
constructor
methods that use the return value ofsuper()
instead of usingthis
. This isn't too common because TypeScript doesn't let you do that but it can come up when writing JavaScript. Previously esbuild's class lowering transform incorrectly transformed the return value ofsuper()
intoundefined
. With this release, the return value ofsuper()
will now bethis
instead:// Original code class Foo extends Object { field constructor() { console.log(typeof super()) } } new Foo // Old output (with --target=es6) class Foo extends Object { constructor() { var __super = (...args) => { super(...args); __publicField(this, "field"); }; console.log(typeof __super()); } } new Foo(); // New output (with --target=es6) class Foo extends Object { constructor() { var __super = (...args) => { super(...args); __publicField(this, "field"); return this; }; console.log(typeof __super()); } } new Foo();
-
Terminate the Go GC when esbuild's
stop()
API is called (#3552)If you use esbuild with WebAssembly and pass the
worker: false
flag toesbuild.initialize()
, then esbuild will run the WebAssembly module on the main thread. If you do this within a Deno test and that test callsesbuild.stop()
to clean up esbuild's resources, Deno may complain that asetTimeout()
call lasted past the end of the test. This happens when the Go is in the middle of a garbage collection pass and has scheduled additional ongoing garbage collection work. Normally callingesbuild.stop()
will terminate the web worker that the WebAssembly module runs in, which will terminate the Go GC, but that doesn't happen if you disable the web worker withworker: false
.With this release, esbuild will now attempt to terminate the Go GC in this edge case by calling
clearTimeout()
on these pending timeouts. -
Apply
/* @​__NO_SIDE_EFFECTS__ */
on tagged template literals (#3511)Tagged template literals that reference functions annotated with a
@__NO_SIDE_EFFECTS__
comment are now able to be removed via tree-shaking if the result is unused. This is a convention from Rollup. Here is an example:// Original code const html = /* @​__NO_SIDE_EFFECTS__ */ (a, ...b) => ({ a, b }) html`<a>remove</a>` x = html`<b>keep</b>` // Old output (with --tree-shaking=true) const html = /* @​__NO_SIDE_EFFECTS__ */ (a, ...b) => ({ a, b }); html`<a>remove</a>`; x = html`<b>keep</b>`; // New output (with --tree-shaking=true) const html = /* @​__NO_SIDE_EFFECTS__ */ (a, ...b) => ({ a, b }); x = html`<b>keep</b>`;
Note that this feature currently only works within a single file, so it's not especially useful. This feature does not yet work across separate files. I still recommend using
@__PURE__
annotations instead of this feature, as they have wider tooling support. The drawback of course is that@__PURE__
annotations need to be added at each call site, not at the declaration, and for non-call expressions such as template literals you need to wrap the expression in an IIFE (immediately-invoked function expression) to create a call expression to apply the@__PURE__
annotation to. -
Publish builds for IBM AIX PowerPC 64-bit (#3549)
This release publishes a binary executable to npm for IBM AIX PowerPC 64-bit, which means that in theory esbuild can now be installed in that environment with
npm install esbuild
. This hasn't actually been tested yet. If you have access to such a system, it would be helpful to confirm whether or not doing this actually works.
v0.19.9
-
Add support for transforming new CSS gradient syntax for older browsers
The specification called CSS Images Module Level 4 introduces new CSS gradient syntax for customizing how the browser interpolates colors in between color stops. You can now control the color space that the interpolation happens in as well as (for "polar" color spaces) control whether hue angle interpolation happens clockwise or counterclockwise. You can read more about this in Mozilla's blog post about new CSS gradient features.
With this release, esbuild will now automatically transform this syntax for older browsers in the
target
list. For example, here's a gradient that should appear as a rainbow in a browser that supports this new syntax:/* Original code */ .rainbow-gradient { width: 100px; height: 100px; background: linear-gradient(in hsl longer hue, #​7ff, #​77f); } /* New output (with --target=chrome99) */ .rainbow-gradient { width: 100px; height: 100px; background: linear-gradient( #​77ffff, #​77ffaa 12.5%, #​77ff80 18.75%, #​84ff77 21.88%, #​99ff77 25%, #eeff77 37.5%, #fffb77 40.62%, #ffe577 43.75%, #ffbb77 50%, #ff9077 56.25%, #ff7b77 59.38%, #ff7788 62.5%, #ff77dd 75%, #ff77f2 78.12%, #f777ff 81.25%, #cc77ff 87.5%, #​7777ff); }
You can now use this syntax in your CSS source code and esbuild will automatically convert it to an equivalent gradient for older browsers. In addition, esbuild will now also transform "double position" and "transition hint" syntax for older browsers as appropriate:
/* Original code */ .stripes { width: 100px; height: 100px; background: linear-gradient(#e65 33%, #ff2 33% 67%, #​99e 67%); } .glow { width: 100px; height: 100px; background: radial-gradient(white 10%, 20%, black); } /* New output (with --target=chrome33) */ .stripes { width: 100px; height: 100px; background: linear-gradient( #e65 33%, #ff2 33%, #ff2 67%, #​99e 67%); } .glow { width: 100px; height: 100px; background: radial-gradient( #ffffff 10%, #aaaaaa 12.81%, #​959595 15.62%, #​7b7b7b 21.25%, #​5a5a5a 32.5%, #​444444 43.75%, #​323232 55%, #​161616 77.5%, #​000000); }
You can see visual examples of these new syntax features by looking at esbuild's gradient transformation tests.
If necessary, esbuild will construct a new gradient that approximates the original gradient by recursively splitting the interval in between color stops until the approximation error is within a small threshold. That is why the above output CSS contains many more color stops than the input CSS.
Note that esbuild deliberately replaces the original gradient with the approximation instead of inserting the approximation before the original gradient as a fallback. The latest version of Firefox has multiple gradient rendering bugs (including incorrect interpolation of partially-transparent colors and interpolating non-sRGB colors using the incorrect color space). If esbuild didn't replace the original gradient, then Firefox would use the original gradient instead of the fallback the appearance would be incorrect in Firefox. In other words, the latest version of Firefox supports modern gradient syntax but interprets it incorrectly.
-
Add support for
color()
,lab()
,lch()
,oklab()
,oklch()
, andhwb()
in CSSCSS has recently added lots of new ways of specifying colors. You can read more about this in Chrome's blog post about CSS color spaces.
This release adds support for minifying colors that use the
color()
,lab()
,lch()
,oklab()
,oklch()
, orhwb()
syntax and/or transforming these colors for browsers that don't support it yet:/* Original code */ div { color: hwb(90deg 20% 40%); background: color(display-p3 1 0 0); } /* New output (with --target=chrome99) */ div { color: #​669933; background: #ff0f0e; background: color(display-p3 1 0 0); }
As you can see, colors outside of the sRGB color space such as
color(display-p3 1 0 0)
are mapped back into the sRGB gamut and inserted as a fallback for browsers that don't support the new color syntax. -
Allow empty type parameter lists in certain cases (#3512)
TypeScript allows interface declarations and type aliases to have empty type parameter lists. Previously esbuild didn't handle this edge case but with this release, esbuild will now parse this syntax:
interface Foo<> {} type Bar<> = {}
This fix was contributed by @magic-akari.
v0.19.8
-
Add a treemap chart to esbuild's bundle analyzer (#2848)
The bundler analyzer on esbuild's website (https://esbuild.github.io/analyze/) now has a treemap chart type in addition to the two existing chart types (sunburst and flame). This should be more familiar for people coming from other similar tools, as well as make better use of large screens.
-
Allow decorators after the
export
keyword (#104)Previously esbuild's decorator parser followed the original behavior of TypeScript's experimental decorators feature, which only allowed decorators to come before the
export
keyword. However, the upcoming JavaScript decorators feature also allows decorators to come after theexport
keyword. And with TypeScript 5.0, TypeScript now also allows experimental decorators to come after theexport
keyword too. So esbuild now allows this as well:// This old syntax has always been permitted: @​decorator export class Foo {} @​decorator export default class Foo {} // This new syntax is now permitted too: export @​decorator class Foo {} export default @​decorator class Foo {}
In addition, esbuild's decorator parser has been rewritten to fix several subtle and likely unimportant edge cases with esbuild's parsing of exports and decorators in TypeScript (e.g. TypeScript apparently does automatic semicolon insertion after
interface
andexport interface
but not afterexport default interface
). -
Pretty-print decorators using the same whitespace as the original
When printing code containing decorators, esbuild will now try to respect whether the original code contained newlines after the decorator or not. This can make generated code containing many decorators much more compact to read:
// Original code class Foo { @​a @​b @​c abc @​x @​y @​z xyz } // Old output class Foo { @​a @​b @​c abc; @​x @​y @​z xyz; } // New output class Foo { @​a @​b @​c abc; @​x @​y @​z xyz; }
v0.19.7
-
Add support for bundling code that uses import attributes (#3384)
JavaScript is gaining new syntax for associating a map of string key-value pairs with individual ESM imports. The proposal is still a work in progress and is still undergoing significant changes before being finalized. However, the first iteration has already been shipping in Chromium-based browsers for a while, and the second iteration has landed in V8 and is now shipping in node, so it makes sense for esbuild to support it. Here are the two major iterations of this proposal (so far):
-
Import assertions (deprecated, will not be standardized)
- Uses the
assert
keyword - Does not affect module resolution
- Causes an error if the assertion fails
- Shipping in Chrome 91+ (and in esbuild 0.11.22+)
- Uses the
-
Import attributes (currently set to become standardized)
- Uses the
with
keyword - Affects module resolution
- Unknown attributes cause an error
- Shipping in node 21+
- Uses the
You can already use esbuild to bundle code that uses import assertions (the first iteration). However, this feature is mostly useless for bundlers because import assertions are not allowed to affect module resolution. It's basically only useful as an annotation on external imports, which esbuild will then preserve in the output for use in a browser (which would otherwise refuse to load certain imports).
With this release, esbuild now supports bundling code that uses import attributes (the second iteration). This is much more useful for bundlers because they are allowed to affect module resolution, which means the key-value pairs can be provided to plugins. Here's an example, which uses esbuild's built-in support for the upcoming JSON module standard:
// On static imports import foo from './package.json' with { type: 'json' } console.log(foo) // On dynamic imports const bar = await import('./package.json', { with: { type: 'json' } }) console.log(bar)
One important consequence of the change in semantics between import assertions and import attributes is that two imports with identical paths but different import attributes are now considered to be different modules. This is because the import attributes are provided to the loader, which might then use those attributes during loading. For example, you could imagine an image loader that produces an image of a different size depending on the import attributes.
Import attributes are now reported in the metafile and are now provided to on-load plugins as a map in the
with
property. For example, here's an esbuild plugin that turns all imports with atype
import attribute equal to'cheese'
into a module that exports the cheese emoji:const cheesePlugin = { name: 'cheese', setup(build) { build.onLoad({ filter: /.*/ }, args => { if (args.with.type === 'cheese') return { contents: `export default "🧀"`, } }) } } require('esbuild').build({ bundle: true, write: false, stdin: { contents: ` import foo from 'data:text/javascript,' with { type: 'cheese' } console.log(foo) `, }, plugins: [cheesePlugin], }).then(result => { const code = new Function(result.outputFiles[0].text) code() })
Warning: It's possible that the second iteration of this feature may change significantly again even though it's already shipping in real JavaScript VMs (since it has already happened once before). In that case, esbuild may end up adjusting its implementation to match the eventual standard behavior. So keep in mind that by using this, you are using an unstable upcoming JavaScript feature that may undergo breaking changes in the future.
-
-
Adjust TypeScript experimental decorator behavior (#3230, #3326, #3394)
With this release, esbuild will now allow TypeScript experimental decorators to access both static class properties and
#private
class names. For example:const check = <T,>(a: T, b: T): PropertyDecorator => () => console.log(a === b) async function test() { class Foo { static #foo = 1 static bar = 1 + Foo.#foo @​check(Foo.#foo, 1) a: any @​check(Foo.bar, await Promise.resolve(2)) b: any } } test().then(() => console.log('pass'))
This will now print
true true pass
when compiled by esbuild. Previously esbuild evaluated TypeScript decorators outside of the class body, so it didn't allow decorators to accessFoo
or#foo
. Now esbuild does something different, although it's hard to concisely explain exactly what esbuild is doing now (see the background section below for more information).Note that TypeScript's experimental decorator support is currently buggy: TypeScript's compiler passes this test if only the first
@check
is present or if only the second@check
is present, but TypeScript's compiler fails this test if both checks are present together. I haven't changed esbuild to match TypeScript's behavior exactly here because I'm waiting for TypeScript to fix these bugs instead.Some background: TypeScript experimental decorators don't have consistent semantics regarding the context that the decorators are evaluated in. For example, TypeScript will let you use
await
within a decorator, which implies that the decorator runs outside the class body (sinceawait
isn't supported inside a class body), but TypeScript will also let you use#private
names, which implies that the decorator runs inside the class body (since#private
names are only supported inside a class body). The value ofthis
in a decorator is also buggy (the run-time value ofthis
changes if any decorator in the class uses a#private
name but the type ofthis
doesn't change, leading to the type checker no longer matching reality). These inconsistent semantics make it hard for esbuild to implement this feature as decorator evaluation happens in some superposition of both inside and outside the class body that is particular to the internal implementation details of the TypeScript compiler. -
Forbid
--keep-names
when targeting old browsers (#3477)The
--keep-names
setting needs to be able to assign to thename
property on functions and classes. However, before ES6 this property was non-configurable, and attempting to assign to it would throw an error. So with this release, esbuild will no longer allow you to enable this setting while also targeting a really old browser.
v0.19.6
-
Fix a constant folding bug with bigint equality
This release fixes a bug where esbuild incorrectly checked for bigint equality by checking the equality of the bigint literal text. This is correct if the bigint doesn't have a radix because bigint literals without a radix are always in canonical form (since leading zeros are not allowed). However, this is incorrect if the bigint has a radix (e.g.
0x123n
) because the canonical form is not enforced when a radix is present.// Original code console.log(!!0n, !!1n, 123n === 123n) console.log(!!0x0n, !!0x1n, 123n === 0x7Bn) // Old output console.log(false, true, true); console.log(true, true, false); // New output console.log(false, true, true); console.log(!!0x0n, !!0x1n, 123n === 0x7Bn);
-
Add some improvements to the JavaScript minifier
This release adds more cases to the JavaScript minifier, including support for inlining
String.fromCharCode
andString.prototype.charCodeAt
when possible:// Original code document.onkeydown = e => e.keyCode === 'A'.charCodeAt(0) && console.log(String.fromCharCode(55358, 56768)) // Old output (with --minify) document.onkeydown=o=>o.keyCode==="A".charCodeAt(0)&&console.log(String.fromCharCode(55358,56768)); // New output (with --minify) document.onkeydown=o=>o.keyCode===65&&console.log("🧀");
In addition, immediately-invoked function expressions (IIFEs) that return a single expression are now inlined when minifying. This makes it possible to use IIFEs in combination with
@__PURE__
annotations to annotate arbitrary expressions as side-effect free without the IIFE wrapper impacting code size. For example:// Original code const sideEffectFreeOffset = /* @​__PURE__ */ (() => computeSomething())() use(sideEffectFreeOffset) // Old output (with --minify) const e=(()=>computeSomething())();use(e); // New output (with --minify) const e=computeSomething();use(e);
-
Automatically prefix the
mask-composite
CSS property for WebKit (#3493)The
mask-composite
property will now be prefixed as-webkit-mask-composite
for older WebKit-based browsers. In addition to prefixing the property name, handling older browsers also requires rewriting the values since WebKit uses non-standard names for the mask composite modes:/* Original code */ div { mask-composite: add, subtract, intersect, exclude; } /* New output (with --target=chrome100) */ div { -webkit-mask-composite: source-over, source-out, source-in, xor; mask-composite: add, subtract, intersect, exclude; }
-
Avoid referencing
this
from JSX elements in derived class constructors (#3454)When you enable
--jsx=automatic
and--jsx-dev
, the JSX transform is supposed to insertthis
as the last argument to thejsxDEV
function. I'm not sure exactly why this is and I can't find any specification for it, but in any case this causes the generated code to crash when you use a JSX element in a derived class constructor before the call tosuper()
asthis
is not allowed to be accessed at that point. For example// Original code class ChildComponent extends ParentComponent { constructor() { super(<div />) } } // Problematic output (with --loader=jsx --jsx=automatic --jsx-dev) import { jsxDEV } from "react/jsx-dev-runtime"; class ChildComponent extends ParentComponent { constructor() { super(/* @​__PURE__ */ jsxDEV("div", {}, void 0, false, { fileName: "<stdin>", lineNumber: 3, columnNumber: 15 }, this)); // The reference to "this" crashes here } }
The TypeScript compiler doesn't handle this at all while the Babel compiler just omits
this
for the entire constructor (even after the call tosuper()
). There seems to be no specification so I can't be sure that this change doesn't break anything important. But given that Babel is pretty loose with this and TypeScript doesn't handle this at all, I'm guessing this value isn't too important. React's blog post seems to indicate that this value was intended to be used for a React-specific migration warning at some point, so it could even be that this value is irrelevant now. Anyway the crash in this case should now be fixed. -
Allow package subpath imports to map to node built-ins (#3485)
You are now able to use a subpath import in your package to resolve to a node built-in module. For example, with a
package.json
file like this:{ "type": "module", "imports": { "#stream": { "node": "stream", "default": "./stub.js" } } }
You can now import from node's
stream
module like this:import * as stream from '#stream'; console.log(Object.keys(stream));
This will import from node's
stream
module when the platform isnode
and from./stub.js
otherwise. -
No longer throw an error when a
Symbol
is missing (#3453)Certain JavaScript syntax features use special properties on the global
Symbol
object. For example, the asynchronous iteration syntax usesSymbol.asyncIterator
. Previously esbuild's generated code for older browsers required this symbol to be polyfilled. However, starting with this release esbuild will useSymbol.for()
to construct these symbols if they are missing instead of throwing an error about a missing polyfill. This means your code no longer needs to include a polyfill for missing symbols as long as your code also usesSymbol.for()
for missing symbols. -
Parse upcoming changes to TypeScript syntax (#3490, #3491)
With this release, you can now use
from
as the name of a default type-only import in TypeScript code, as well asof
as the name of anawait using
loop iteration variable:import type from from 'from' for (await using of of of) ;
This matches similar changes in the TypeScript compiler (#56376 and #55555) which will start allowing this syntax in an upcoming version of TypeScript. Please never actually write code like this.
The type-only import syntax change was contributed by @magic-akari.
v0.19.5
-
Fix a regression in 0.19.0 regarding
paths
intsconfig.json
(#3354)The fix in esbuild version 0.19.0 to process
tsconfig.json
aliases before the--packages=external
setting unintentionally broke an edge case in esbuild's handling of certaintsconfig.json
aliases where there are multiple files with the same name in different directories. This release adjusts esbuild's behavior for this edge case so that it passes while still processing aliases before--packages=external
. Please read the linked issue for more details. -
Fix a CSS
font
property minification bug (#3452)This release fixes a bug where esbuild's CSS minifier didn't insert a space between the font size and the font family in the
font
CSS shorthand property in the edge case where the original source code didn't already have a space and the leading string token was shortened to an identifier:/* Original code */ .foo { font: 16px"Menlo"; } /* Old output (with --minify) */ .foo{font:16pxMenlo} /* New output (with --minify) */ .foo{font:16px Menlo}
-
Fix bundling CSS with asset names containing spaces (#3410)
Assets referenced via CSS
url()
tokens may cause esbuild to generate invalid output when bundling if the file name contains spaces (e.g.url(image 2.png)
). With this release, esbuild will now quote all bundled asset references inurl()
tokens to avoid this problem. This only affects assets loaded using thefile
andcopy
loaders. -
Fix invalid CSS
url()
tokens in@import
rules (#3426)In the future, CSS
url()
tokens may contain additional stuff after the URL. This is irrelevant today as no CSS specification does this. But esbuild previously had a bug where using these tokens in an@import
rule resulted in malformed output. This bug has been fixed. -
Fix
browser
+false
+type: module
inpackage.json
(#3367)The
browser
field inpackage.json
allows you to map a file tofalse
to have it be treated as an empty file when bundling for the browser. However, ifpackage.json
contains"type": "module"
then all.js
files will be considered ESM, not CommonJS. Importing a named import from an empty CommonJS file gives you undefined, but importing a named export from an empty ESM file is a build error. This release changes esbuild's interpretation of these files mapped tofalse
in this situation from ESM to CommonJS to avoid generating build errors for named imports. -
Fix a bug in top-level await error reporting (#3400)
Using
require()
on a file that contains top-level await is not allowed becauserequire()
must return synchronously and top-level await makes that impossible. You will get a build error if you try to bundle code that does this with esbuild. This release fixes a bug in esbuild's error reporting code for complex cases of this situation involving multiple levels of imports to get to the module containing the top-level await. -
Update to Unicode 15.1.0
The character tables that determine which characters form valid JavaScript identifiers have been updated from Unicode version 15.0.0 to the newly-released Unicode version 15.1.0. I'm not putting an example in the release notes because all of the new characters will likely just show up as little squares since fonts haven't been updated yet. But you can read https://www.unicode.org/versions/Unicode15.1.0/#Summary for more information about the changes.
This upgrade was contributed by @JLHwung.
v0.19.4
-
Fix printing of JavaScript decorators in tricky cases (#3396)
This release fixes some bugs where esbuild's pretty-printing of JavaScript decorators could incorrectly produced code with a syntax error. The problem happened because esbuild sometimes substitutes identifiers for other expressions in the pretty-printer itself, but the decision about whether to wrap the expression or not didn't account for this. Here are some examples:
// Original code import { constant } from './constants.js' import { imported } from 'external' import { undef } from './empty.js' class Foo { @​constant() @​imported() @​undef() foo } // Old output (with --bundle --format=cjs --packages=external --minify-syntax) var import_external = require("external"); var Foo = class { @​123() @​(0, import_external.imported)() @​(void 0)() foo; }; // New output (with --bundle --format=cjs --packages=external --minify-syntax) var import_external = require("external"); var Foo = class { @​(123()) @​((0, import_external.imported)()) @​((void 0)()) foo; };
-
Allow pre-release versions to be passed to
target
(#3388)People want to be able to pass version numbers for unreleased versions of node (which have extra stuff after the version numbers) to esbuild's
target
setting and have esbuild do something reasonable with them. These version strings are of course not present in esbuild's internal feature compatibility table because an unreleased version has not been released yet (by definition). With this release, esbuild will now attempt to accept these version strings passed totarget
and do something reasonable with them.
Configuration
-
If you want to rebase/retry this MR, check this box
This MR has been generated by Renovate Bot.