@esbuild/linux-loong64
0.28.2 · 8 Aug 2026MIT12.3M / weekRepositoryHomepagenpmAtom feed
135 stable releases, newest first, by release line. Notes are quoted as the maintainers published them.
- 0.16.x
0.16.11
27 Dec 2022Avoid a syntax error in the presence of direct
evalThe behavior of nested
functiondeclarations in JavaScript depends on whether the code is run in strict mode or not. It would be problematic if esbuild preserved nestedfunctiondeclarations in its output because then the behavior would depend on whether the output was run in strict mode or not instead of respecting the strict mode behavior of the original source code. To avoid this, esbuild transforms nestedfunctiondeclarations to preserve the intended behavior of the original source code regardless of whether the output is run in strict mode or not:// Original code if (true) { function foo() {} console.log(!!foo) foo = null console.log(!!foo) } console.log(!!foo) // Transformed code if (true) { let foo2 = function() { }; var foo = foo2; console.log(!!foo2); foo2 = null; console.log(!!foo2); } console.log(!!foo);In the above example, the original code should print
true false truebecause it's not run in strict mode (it doesn't contain"use strict"and is not an ES module). The code that esbuild generates has been transformed such that it printstrue false trueregardless of whether it's run in strict mode or not.However, this transformation is impossible if the code contains direct
evalbecause directeval"poisons" all containing scopes by preventing anything in those scopes from being renamed. That prevents esbuild from splitting up accesses tofoointo two separate variables with different names. Previously esbuild still did this transformation but with two variables both namedfoo, which is a syntax error. With this release esbuild will now skip doing this transformation when directevalis present to avoid generating code with a syntax error. This means that the generated code may no longer behave as intended since the behavior depends on the run-time strict mode setting instead of the strict mode setting present in the original source code. To fix this problem, you will need to remove the use of directeval.Fix a bundling scenario involving multiple symlinks (#2773, #2774)
This release contains a fix for a bundling scenario involving an import path where multiple path segments are symlinks. Previously esbuild was unable to resolve certain import paths in this scenario, but these import paths should now work starting with this release. This fix was contributed
0.16.10
19 Dec 2022Change the default "legal comment" behavior again
The legal comments feature automatically gathers comments containing
@licenseor@preserveand puts the comments somewhere (either in the generated code or in a separate file). This behavior used to be on by default but was disabled by default in version 0.16.0 because automatically inserting comments is potentially confusing and misleading. These comments can appear to be assigning the copyright of your code to another entity. And this behavior can be especially problematic if it happens automatically by default since you may not even be aware of it happening. For example, if you bundle the TypeScript compiler the preserving legal comments means your source code would contain this comment, which appears to be assigning the copyright of all of your code to Microsoft:/*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */
However, people have asked for this feature to be re-enabled by default. To resolve the confusion about what these comments are applying to, esbuild's default behavior will now be to attempt to describe which package the comments are coming from. So while this feature has been re-enabled by default, the output will now look something like this instead:
/*! Bundled license information: typescript/lib/typescript.js: (*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** *) */
Note that you can still customize this behavior with the
--legal-comments=flag. For example, you can use--legal-comments=noneto turn this off, or you can use--legal-comments=linkedto put these comments in a separate.LEGAL.txtfile instead.Enable
externallegal comments with the transform APIPreviously esbuild's transform API only supported
none,inline, oreoflegal comments. With this release,externallegal comments are now also supported with the transform API. This only applies to the JS and Go APIs, not to the CLI, and looks like this:Fix duplicate function declaration edge cases
The change in the previous release to forbid duplicate function declarations in certain cases accidentally forbid some edge cases that should have been allowed. Specifically duplicate function declarations are forbidden in nested blocks in strict mode and at the top level of modules, but are allowed when they are declared at the top level of function bodies. This release fixes the regression by re-allowing the last case.
Change the default "legal comment" behavior again
The legal comments feature automatically gathers comments containing
@licenseor@preserveand puts the comments somewhere (either in the generated code or in a separate file). This behavior used to be on by default but was disabled by default in version 0.16.0 because automatically inserting comments is potentially confusing and misleading. These comments can appear to be assigning the copyright of your code to another entity. And this behavior can be especially problematic if it happens automatically by default since you may not even be aware of it happening. For example, if you bundle the TypeScript compiler the preserving legal comments means your source code would contain this comment, which appears to be assigning the copyright of all of your code to Microsoft:/*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */
However, people have asked for this feature to be re-enabled by default. To resolve the confusion about what these comments are applying to, esbuild's default behavior will now be to attempt to describe which package the comments are coming from. So while this feature has been re-enabled by default, the output will now look something like this instead:
/*! Bundled license information: typescript/lib/typescript.js: (*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** *) */
Note that you can still customize this behavior with the
--legal-comments=flag. For example, you can use--legal-comments=noneto turn this off, or you can use--legal-comments=linkedto put these comments in a separate.LEGAL.txtfile instead.Enable
externallegal comments with the transform APIPreviously esbuild's transform API only supported
none,inline, oreoflegal comments. With this release,externallegal comments are now also supported with the transform API. This only applies to the JS and Go APIs, not to the CLI, and looks like this:JS:
const { code, legalComments } = await esbuild.transform(input, { legalComments: 'external', })Go:
result := api.Transform(input, api.TransformOptions{ LegalComments: api.LegalCommentsEndOfFile, }) code := result.Code legalComments := result.LegalComments
Fix duplicate function declaration edge cases
The change in the previous release to forbid duplicate function declarations in certain cases accidentally forbid some edge cases that should have been allowed. Specifically duplicate function declarations are forbidden in nested blocks in strict mode and at the top level of modules, but are allowed when they are declared at the top level of function bodies. This release fixes the regression by re-allowing the last case.
Allow package subpaths with
aliasPreviously the names passed to the
aliasfeature had to be the name of a package (with or without a package scope). With this release, you can now also use thealiasfeature with package subpaths. So for example you can now create an alias that substitutes@org/pkg/libwith something else.
0.16.9
18 Dec 2022Update to Unicode 15.0.0
The character tables that determine which characters form valid JavaScript identifiers have been updated from Unicode version 14.0.0 to the newly-released Unicode version 15.0.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 unicode.org/versions/Unicode15.0.0/ for more information about the changes.
Disallow duplicate lexically-declared names in nested blocks and in strict mode
In strict mode or in a nested block, it's supposed to be a syntax error to declare two symbols with the same name unless all duplicate entries are either
functiondeclarations or allvardeclarations. However, esbuild was overly permissive and allowed this when duplicate entries were eitherfunctiondeclarations orvardeclarations (even if they were mixed). This check has now been made more restrictive to match the JavaScript specification:// JavaScript allows this var a function a() {} { var b var b function c() {} function c() {} } // JavaScript doesn't allow this { var d function d() {} }Add a type declaration for the new
emptyloaderI forgot to add this in the previous release. It has now been added.
This fix was contributed
Update to Unicode 15.0.0
The character tables that determine which characters form valid JavaScript identifiers have been updated from Unicode version 14.0.0 to the newly-released Unicode version 15.0.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 unicode.org/versions/Unicode15.0.0/ for more information about the changes.
Disallow duplicate lexically-declared names in nested blocks and in strict mode
In strict mode or in a nested block, it's supposed to be a syntax error to declare two symbols with the same name unless all duplicate entries are either
functiondeclarations or allvardeclarations. However, esbuild was overly permissive and allowed this when duplicate entries were eitherfunctiondeclarations orvardeclarations (even if they were mixed). This check has now been made more restrictive to match the JavaScript specification:// JavaScript allows this var a function a() {} { var b var b function c() {} function c() {} } // JavaScript doesn't allow this { var d function d() {} }Add a type declaration for the new
emptyloaderI forgot to add this in the previous release. It has now been added.
This fix was contributed
Add support for the
vflag in regular expression literalsPeople are currently working on adding a
vflag to JavaScript regular expresions. You can read more about this flag here: v8.dev/features/regexp-v-flag. This release adds support for parsing this flag, so esbuild will now no longer consider regular expression literals with this flag to be a syntax error. If the target is set to something other thanesnext, esbuild will transform regular expression literals containing this flag into anew RegExp()constructor call so the resulting code doesn't have a syntax error. This enables you to provide a polyfill forRegExpthat implements thevflag to get your code to work at run-time. While esbuild doesn't typically adopt proposals until they're already shipping in a real JavaScript run-time, I'm adding it now because a) esbuild's implementation doesn't need to change as the proposal evolves, b) this isn't really new syntax since regular expression literals already have flags, and c) esbuild's implementation is a trivial pass-through anyway.Avoid keeping the name of classes with static
namepropertiesThe
--keep-namesproperty attempts to preserve the original value of thenameproperty for functions and classes even when identifiers are renamed by the minifier or to avoid a name collision. This is currently done by generating code to assign a string to thenameproperty on the function or class object. However, this should not be done for classes with a staticnameproperty since in that case the explicitly-definednameproperty overwrites the automatically-generated class name. With this release, esbuild will now no longer attempt to preserve thenameproperty for classes with a staticnameproperty.
0.16.8
16 Dec 2022Allow plugins to resolve injected files
Previously paths passed to the
injectfeature were always interpreted as file system paths. This meant thatonResolveplugins would not be run for them and esbuild's default path resolver would always be used. This meant that theinjectfeature couldn't be used in the browser since the browser doesn't have access to a file system. This release runs paths passed toinjectthrough esbuild's full path resolution pipeline so plugins now have a chance to handle them usingonResolvecallbacks. This makes it possible to write a plugin that makes esbuild'sinjectwork in the browser.Add the
emptyloader (#1541, #2753)The new
emptyloader tells esbuild to pretend that a file is empty. So for example--loader:.css=emptyeffectively skips all imports of.cssfiles in JavaScript so that they aren't included in the bundle, sinceimport "./some-empty-file"in JavaScript doesn't bundle anything. You can also use theemptyloader to remove asset references in CSS files. For example--loader:.png=emptycauses esbuild to replace asset references such asurl(image.png)withurl()so that they are no longer included in the resulting style sheet.Fix
</script>and</style>escaping for non-default targetsThe change in version 0.16.0 to give control over
</script>escaping via--supported:inline-script=falseor--supported:inline-script=trueaccidentally broke automatic escaping of</script>when an explicittargetsetting is specified. This release restores the correct automatic escaping of</script>(which should not depend on whattargetis set to).
Allow plugins to resolve injected files
Previously paths passed to the
injectfeature were always interpreted as file system paths. This meant thatonResolveplugins would not be run for them and esbuild's default path resolver would always be used. This meant that theinjectfeature couldn't be used in the browser since the browser doesn't have access to a file system. This release runs paths passed toinjectthrough esbuild's full path resolution pipeline so plugins now have a chance to handle them usingonResolvecallbacks. This makes it possible to write a plugin that makes esbuild'sinjectwork in the browser.Add the
emptyloader (#1541, #2753)The new
emptyloader tells esbuild to pretend that a file is empty. So for example--loader:.css=emptyeffectively skips all imports of.cssfiles in JavaScript so that they aren't included in the bundle, sinceimport "./some-empty-file"in JavaScript doesn't bundle anything. You can also use theemptyloader to remove asset references in CSS files. For example--loader:.png=emptycauses esbuild to replace asset references such asurl(image.png)withurl()so that they are no longer included in the resulting style sheet.Fix
</script>and</style>escaping for non-default targetsThe change in version 0.16.0 to give control over
</script>escaping via--supported:inline-script=falseor--supported:inline-script=trueaccidentally broke automatic escaping of</script>when an explicittargetsetting is specified. This release restores the correct automatic escaping of</script>(which should not depend on whattargetis set to).Enable the
exportsfield withNODE_PATHSNode has a rarely-used feature where you can extend the set of directories that node searches for packages using the
NODE_PATHSenvironment variable. While esbuild supports this too, previously it only supported the oldmainfield path resolution but did not support the newexportsfield package resolution. This release makes the path resolution rules the same again for bothnode_modulesdirectories andNODE_PATHSdirectories.
0.16.7
14 Dec 2022Include
fileloader strings in metafile importsBundling a file with the
fileloader copies that file to the output directory and imports a module with the path to the copied file in thedefaultexport. Previously when bundling with thefileloader, there was no reference in the metafile from the JavaScript file containing the path string to the copied file. With this release, there will now be a reference in the metafile in theimportsarray with the kindfile-loader:{ ... "outputs": { "out/image-55CCFTCE.svg": { ... }, "out/entry.js": { "imports": [ + { + "path": "out/image-55CCFTCE.svg", + "kind": "file-loader" + } ], ... } } }Fix byte counts in metafile regarding references to other output files
Previously files that contained references to other output files had slightly incorrect metadata for the byte counts of input files which contributed to that output file. So for example if
app.jsimportsimage.pngusing the file loader and esbuild generatesout.jsandimage-LSAMBFUD.png, the metadata for how many bytes ofout.jsare fromapp.jswas slightly off (the metadata for the byte count ofout.jswas still correct). The reason is because esbuild substitutes the final paths for references between output files toward the end of the build to handle cyclic references, and the byte counts needed to be adjusted as well during the path substitution. This release fixes these byte counts (specifically thebytesInOutputvalues).The alias feature now strips a trailing slash
People sometimes add a trailing slash to the name of one of node's built-in modules to force node to import from the file system instead of importing the built-in module. For example, importing
utilimports node's built-in module calledutilbut importingutil/tries to find a package calledutilon the file system. Previously attempting to use esbuild's package alias feature to replace imports toutilwith a specific file would fail because the file path would also gain a trailing slash (e.g. mappingutilto./file.jsturnedutil/into./file.js/). With this release, esbuild will now omit the path suffix if it's a single trailing slash, which should now allow you to successfully apply aliases to these import paths.
0.16.6
14 Dec 2022Do not mark subpath imports as external with
--packages=externalNode has a feature called subpath imports where special import paths that start with
#are resolved using theimportsfield in thepackage.jsonfile of the enclosing package. The intent of the newly-added--packages=externalsetting is to exclude a package's dependencies from the bundle. Since a package's subpath imports are only accessible within that package, it's wrong for them to be affected by--packages=external. This release changes esbuild so that--packages=externalno longer affects subpath imports.Forbid invalid numbers in JSON files
Previously esbuild parsed numbers in JSON files using the same syntax as JavaScript. But starting from this release, esbuild will now parse them with JSON syntax instead. This means the following numbers are no longer allowed by esbuild in JSON files:
Add external imports to metafile (#905, #1768, #1933, #1939)
External imports now appear in
importsarrays in the metafile (which is present when bundling withmetafile: true) next to normal imports, but additionally haveexternal: trueto set them apart. This applies both to files in theinputssection and theoutputssection. Here's an example:{ "inputs": { "style.css": { "bytes": 83, "imports": [ + { + "path": "https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css", + "kind": "import-rule", + "external": true + } ] }, "app.js": { "bytes": 100, "imports": [ + { + "path": "https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js", + "kind": "import-statement", + "external": true + }, { "path": "style.css", "kind": "import-statement" } ] } }, "outputs": { "out/app.js": { "imports": [ + { + "path": "https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js", + "kind": "require-call", + "external": true + } ], "exports": [], "entryPoint": "app.js", "cssBundle": "out/app.css", "inputs": { "app.js": { "bytesInOutput": 113 }, "style.css": { "bytesInOutput": 0 } }, "bytes": 528 }, "out/app.css": { "imports": [ + { + "path": "https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css", + "kind": "import-rule", + "external": true + } ], "inputs": { "style.css": { "bytesInOutput": 0 } }, "bytes": 100 } } }One additional useful consequence of this is that the
importsarray is now populated when bundling is disabled. So you can now use esbuild with bundling disabled to inspect a file's imports.
0.16.5
13 Dec 2022Make it easy to exclude all packages from a bundle (#1958, #1975, #2164, #2246, #2542)
When bundling for node, it's often necessary to exclude npm packages from the bundle since they weren't designed with esbuild bundling in mind and don't work correctly after being bundled. For example, they may use
__dirnameand run-time file system calls to load files, which doesn't work after bundling with esbuild. Or they may compile a native.nodeextension that has similar expectations about the layout of the file system that are no longer true after bundling (even if the.nodeextension is copied next to the bundle).The way to get this to work with esbuild is to use the
--external:flag. For example, thefseventspackage contains a native.nodeextension and shouldn't be bundled. To bundle code that uses it, you can pass--external:fseventsto esbuild to exclude it from your bundle. You will then need to ensure that thefseventspackage is still present when you run your bundle (e.g. by publishing your bundle to npm as a package with a dependency onfsevents).It was possible to automatically do this for all of your dependencies, but it was inconvenient. You had to write some code that read your
package.jsonfile and passed the keys of thedependencies,devDependencies,peerDependencies, and/oroptionalDependenciesmaps to esbuild as external packages (either that or write a plugin to mark all package paths as external). Previously esbuild's recommendation for making this easier was to do--external:./node_modules/*(added in version 0.14.13). However, this was a bad idea because it caused compatibility problems with many node packages as it caused esbuild to mark the post-resolve path as external instead of the pre-resolve path. Doing that could break packages that are published as both CommonJS and ESM if esbuild's bundler is also used to do a module format conversion.With this release, you can now do the following to automatically exclude all packages from your bundle:
Doing
--external:./node_modules/*is still possible and still has the same behavior, but is no longer recommended. I recommend that you use the newpackagesfeature instead.Fix some subtle bugs with tagged template literals
This release fixes a bug where minification could incorrectly change the value of
thiswithin tagged template literal function calls:// Original code function f(x) { let z = y.z return z`` } // Old output (with --minify) function f(n){return y.z``} // New output (with --minify) function f(n){return(0,y.z)``}This release also fixes a bug where using optional chaining with
--target=es2019or earlier could incorrectly change the value ofthiswithin tagged template literal function calls:// Original code var obj = { foo: function() { console.log(this === obj); } }; (obj?.foo)``; // Old output (with --target=es6) var obj = { foo: function() { console.log(this === obj); } }; (obj == null ? void 0 : obj.foo)``; // New output (with --target=es6) var __freeze = Object.freeze; var __defProp = Object.defineProperty; var __template = (cooked, raw) => __freeze(__defProp(cooked, "raw", { value: __freeze(raw || cooked.slice()) })); var _a; var obj = { foo: function() { console.log(this === obj); } }; (obj == null ? void 0 : obj.foo).call(obj, _a || (_a = __template([""])));Some slight minification improvements
The following minification improvements were implemented:
0.16.4
10 Dec 2022Fix binary downloads from the
@esbuild/scope for DenoVersion 0.16.0 of esbuild moved esbuild's binary executables into npm packages under the
@esbuild/scope, which accidentally broke the binary downloader script for Deno. This release fixes this script so it should now be possible to use esbuild version 0.16.4+ with Deno.
0.16.3
8 Dec 2022Fix a hang with the JS API in certain cases
A change that was made in version 0.15.13 accidentally introduced a case when using esbuild's JS API could cause the node process to fail to exit. The change broke esbuild's watchdog timer, which detects if the parent process no longer exists and then automatically exits esbuild. This hang happened when you ran node as a child process with the
stderrstream set topipeinstead ofinherit, in the child process you call esbuild's JS API and passincremental: truebut do not calldispose()on the returnedrebuildobject, and then callprocess.exit(). In that case the parent node process was still waiting for the esbuild process that was created by the child node process to exit. The change made in version 0.15.13 was trying to avoid using Go'ssync.WaitGroupAPI incorrectly because the API is not thread-safe. Instead of doing this, I have now reverted that change and implemented a thread-safe version of thesync.WaitGroupAPI for esbuild to use instead.
0.16.2
8 Dec 2022Fix
process.env.NODE_ENVsubstitution when transformingVersion 0.16.0 introduced an unintentional regression that caused
process.env.NODE_ENVto be automatically substituted with either"development"or"production"when using esbuild'stransformAPI. This substitution is a necessary feature of esbuild'sbuildAPI because the React framework crashes when you bundle it without doing this. But thetransformAPI is typically used as part of a larger build pipeline so the benefit of esbuild doing this automatically is not as clear, and esbuild previously didn't do this.However, version 0.16.0 switched the default value of the
platformsetting for thetransformAPI fromneutraltobrowser, both to align it with esbuild's documentation (which saysbrowseris the default value) and because escaping the</script>character sequence is now tied to thebrowserplatform (see the release notes for version 0.16.0 for details). That accidentally enabled automatic substitution ofprocess.env.NODE_ENVbecause esbuild always did that for code meant for the browser. To fix this regression, esbuild will now only automatically substituteprocess.env.NODE_ENVwhen using thebuildAPI.Prevent
definefrom substituting constants into assignment positionThe
definefeature lets you replace certain expressions with constants. For example, you could use it to replace references to the global property referencewindow.DEBUGwithfalseat compile time, which can then potentially help esbuild remove unused code from your bundle. It's similar to DefinePlugin in Webpack.However, if you write code such as
window.DEBUG = trueand then definedwindow.DEBUGtofalse, esbuild previously generated the outputfalse = truewhich is a syntax error in JavaScript. This behavior is not typically a problem because it doesn't make sense to substitutewindow.DEBUGwith a constant if its value changes at run-time (Webpack'sDefinePluginalso generatesfalse = truein this case). But it can be alarming to have esbuild generate code with a syntax error.So with this release, esbuild will no longer substitute
defineconstants into assignment position to avoid generating code with a syntax error. Instead esbuild will generate a warning, which currently looks like this:▲ [WARNING] Suspicious assignment to defined constant "window.DEBUG" [assign-to-define] example.js:1:0: 1 │ window.DEBUG = true ╵ ~~~~~~~~~~~~ The expression "window.DEBUG" has been configured to be replaced with a constant using the "define" feature. If this expression is supposed to be a compile-time constant, then it doesn't make sense to assign to it here. Or if this expression is supposed to change at run-time, this "define" substitution should be removed.Fix a regression with
npm install --no-optionalNormally when you install esbuild with
npm install, npm itself is the tool that downloads the correct binary executable for the current platform. This happens because of how esbuild's primary package uses npm'soptionalDependenciesfeature. However, if you deliberately disable this withnpm install --no-optionalthen esbuild's install script will attempt to repair the installation by manually downloading and extracting the binary executable from the package that was supposed to be installed.The change in version 0.16.0 to move esbuild's nested packages into the
@esbuild/scope unintentionally broke this logic because of how npm's URL structure is different for scoped packages vs. normal packages. It was actually already broken for a few platforms earlier because esbuild already had packages for some platforms in the@esbuild/scope, but I didn't discover this then because esbuild's integration tests aren't run on all platforms. Anyway, this release contains some changes to the install script that should hopefully get this scenario working again.
0.16.1
7 Dec 2022Re-allow importing JSON with the
copyloader using an import assertionThe previous release made it so when
assert { type: 'json' }is present on an import statement, esbuild validated that thejsonloader was used. This is what an import assertion is supposed to do. However, I forgot about the relatively newcopyloader, which sort of behaves as if the import path was marked as external (and thus not loaded at all) except that the file is copied to the output directory and the import path is rewritten to point to the copy. In this case whatever JavaScript runtime ends up running the code is the one to evaluate the import assertion. So esbuild should really allow this case as well. With this release, esbuild now allows both thejsonandcopyloaders when anassert { type: 'json' }import assertion is present.
This is a hotfix for the previous release.
Re-allow importing JSON with the
copyloader using an import assertionThe previous release made it so when
assert { type: 'json' }is present on an import statement, esbuild validated that thejsonloader was used. This is what an import assertion is supposed to do. However, I forgot about the relatively newcopyloader, which sort of behaves as if the import path was marked as external (and thus not loaded at all) except that the file is copied to the output directory and the import path is rewritten to point to the copy. In this case whatever JavaScript runtime ends up running the code is the one to evaluate the import assertion. So esbuild should really allow this case as well. With this release, esbuild now allows both thejsonandcopyloaders when anassert { type: 'json' }import assertion is present.
0.16.0
7 Dec 2022Move all binary executable packages to the
@esbuild/scopeBinary package executables for esbuild are published as individual packages separate from the main
esbuildpackage so you only have to download the relevant one for the current platform when you install esbuild. This release moves all of these packages under the@esbuild/scope to avoid collisions with 3rd-party packages. It also changes them to a consistent naming scheme that uses theosandcpunames from node.The package name changes are as follows:
Normal usage of the
esbuildandesbuild-wasmpackages should not be affected. These name changes should only affect tools that hard-coded the individual binary executable package names into custom esbuild downloader scripts.This change was not made with performance in mind. But as a bonus, installing esbuild with npm may potentially happen faster now. This is because npm's package installation protocol is inefficient: it always downloads metadata for all past versions of each package even when it only needs metadata about a single version. This makes npm package downloads O(n) in the number of published versions, which penalizes packages like esbuild that are updated regularly. Since most of esbuild's package names have now changed, npm will now need to download much less data when installing esbuild (8.72mb of package manifests before this change → 0.06mb of package manifests after this change). However, this is only a temporary improvement. Installing esbuild will gradually get slower again as further versions of esbuild are published.
Fix some parameter names for the Go API
This release changes some parameter names for the Go API to be consistent with the JavaScript and CLI APIs:
Add additional validation of API parameters
The JavaScript API now does some additional validation of API parameters to catch incorrect uses of esbuild's API. The biggest impact of this is likely that esbuild now strictly only accepts strings with the
defineparameter. This would already have been a type error with esbuild's TypeScript type definitions, but it was previously not enforced for people using esbuild's API JavaScript without TypeScript.The
defineparameter appears at first glance to take a JSON object if you aren't paying close attention, but this actually isn't true. Values fordefineare instead strings of JavaScript code. This means you have to usedefine: { foo: '"bar"' }to replacefoowith the string"bar". Usingdefine: { foo: 'bar' }actually replacesfoowith the identifierbar. Previously esbuild allowed you to passdefine: { foo: false }andfalsewas automatically converted into a string, which made it more confusing to understand whatdefineactually represents. Starting with this release, passing non-string values such as withdefine: { foo: false }will no longer be allowed. You will now have to writedefine: { foo: 'false' }instead.
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.15.0or~0.15.0. See npm's documentation about semver for more information.Move all binary executable packages to the
@esbuild/scopeBinary package executables for esbuild are published as individual packages separate from the main
esbuildpackage so you only have to download the relevant one for the current platform when you install esbuild. This release moves all of these packages under the@esbuild/scope to avoid collisions with 3rd-party packages. It also changes them to a consistent naming scheme that uses theosandcpunames from node.The package name changes are as follows:
@esbuild/linux-loong64=>@esbuild/linux-loong64(no change)esbuild-android-64=>@esbuild/android-x64esbuild-android-arm64=>@esbuild/android-arm64esbuild-darwin-64=>@esbuild/darwin-x64esbuild-darwin-arm64=>@esbuild/darwin-arm64esbuild-freebsd-64=>@esbuild/freebsd-x64esbuild-freebsd-arm64=>@esbuild/freebsd-arm64esbuild-linux-32=>@esbuild/linux-ia32esbuild-linux-64=>@esbuild/linux-x64esbuild-linux-arm=>@esbuild/linux-armesbuild-linux-arm64=>@esbuild/linux-arm64esbuild-linux-mips64le=>@esbuild/linux-mips64elesbuild-linux-ppc64le=>@esbuild/linux-ppc64esbuild-linux-riscv64=>@esbuild/linux-riscv64esbuild-linux-s390x=>@esbuild/linux-s390xesbuild-netbsd-64=>@esbuild/netbsd-x64esbuild-openbsd-64=>@esbuild/openbsd-x64esbuild-sunos-64=>@esbuild/sunos-x64esbuild-wasm=>esbuild-wasm(no change)esbuild-windows-32=>@esbuild/win32-ia32esbuild-windows-64=>@esbuild/win32-x64esbuild-windows-arm64=>@esbuild/win32-arm64esbuild=>esbuild(no change)
Normal usage of the
esbuildandesbuild-wasmpackages should not be affected. These name changes should only affect tools that hard-coded the individual binary executable package names into custom esbuild downloader scripts.This change was not made with performance in mind. But as a bonus, installing esbuild with npm may potentially happen faster now. This is because npm's package installation protocol is inefficient: it always downloads metadata for all past versions of each package even when it only needs metadata about a single version. This makes npm package downloads O(n) in the number of published versions, which penalizes packages like esbuild that are updated regularly. Since most of esbuild's package names have now changed, npm will now need to download much less data when installing esbuild (8.72mb of package manifests before this change → 0.06mb of package manifests after this change). However, this is only a temporary improvement. Installing esbuild will gradually get slower again as further versions of esbuild are published.
Publish a shell script that downloads esbuild directly
In addition to all of the existing ways to install esbuild, you can now also download esbuild directly like this:
curl -fsSL https://esbuild.github.io/dl/latest | sh
This runs a small shell script that downloads the latest
esbuildbinary executable to the current directory. This can be convenient on systems that don't havenpminstalled or when you just want to get a copy of esbuild quickly without any extra steps. If you want a specific version of esbuild (starting with this version onward), you can provide that version in the URL instead oflatest:curl -fsSL https://esbuild.github.io/dl/v0.16.0 | sh
Note that the download script needs to be able to access registry.npmjs.org to be able to complete the download. This download script doesn't yet support all of the platforms that esbuild supports because I lack the necessary testing environments. If the download script doesn't work for you because you're on an unsupported platform, please file an issue on the esbuild repo so we can add support for it.
Fix some parameter names for the Go API
This release changes some parameter names for the Go API to be consistent with the JavaScript and CLI APIs:
OutExtensions=>OutExtensionJSXMode=>JSX
Add additional validation of API parameters
The JavaScript API now does some additional validation of API parameters to catch incorrect uses of esbuild's API. The biggest impact of this is likely that esbuild now strictly only accepts strings with the
defineparameter. This would already have been a type error with esbuild's TypeScript type definitions, but it was previously not enforced for people using esbuild's API JavaScript without TypeScript.The
defineparameter appears at first glance to take a JSON object if you aren't paying close attention, but this actually isn't true. Values fordefineare instead strings of JavaScript code. This means you have to usedefine: { foo: '"bar"' }to replacefoowith the string"bar". Usingdefine: { foo: 'bar' }actually replacesfoowith the identifierbar. Previously esbuild allowed you to passdefine: { foo: false }andfalsewas automatically converted into a string, which made it more confusing to understand whatdefineactually represents. Starting with this release, passing non-string values such as withdefine: { foo: false }will no longer be allowed. You will now have to writedefine: { foo: 'false' }instead.Generate shorter data URLs if possible
Loading a file with esbuild's
dataurlloader generates a JavaScript module with a data URL for that file in a string as a single default export. Previously the data URLs generated by esbuild all used base64 encoding. However, this is unnecessarily long for most textual data (e.g. SVG images). So with this release, esbuild'sdataurlloader will now use percent encoding instead of base64 encoding if the result will be shorter. This can result in ~25% smaller data URLs for large SVGs. If you want the old behavior, you can use thebase64loader instead and then construct the data URL yourself.Avoid marking entry points as external
Previously you couldn't specify
--external:*to mark all import paths as external because that also ended up making the entry point itself external, which caused the build to fail. With this release, esbuild'sexternalAPI parameter no longer applies to entry points so using--external:*is now possible.One additional consequence of this change is that the
kindparameter is now required when calling theresolve()function in esbuild's plugin API. Previously thekindparameter defaulted toentry-point, but that no longer interacts withexternalso it didn't seem wise for this to continue to be the default. You now have to specifykindso that the path resolution mode is explicit.Disallow non-
defaultimports whenassert { type: 'json' }is presentThere is now standard behavior for importing a JSON file into an ES module using an
importstatement. However, it requires you to place theassert { type: 'json' }import assertion after the import path. This import assertion tells the JavaScript runtime to throw an error if the import does not end up resolving to a JSON file. On the web, the type of a file is determined by theContent-TypeHTTP header instead of by the file extension. The import assertion prevents security problems on the web where a.jsonfile may actually resolve to a JavaScript file containing malicious code, which is likely not expected for an import that is supposed to only contain pure side-effect free data.By default, esbuild uses the file extension to determine the type of a file, so this import assertion is unnecessary with esbuild. However, esbuild's JSON import feature has a non-standard extension that allows you to import top-level properties of the JSON object as named imports. For example, esbuild lets you do this:
import { version } from './package.json'This is useful for tree-shaking when bundling because it means esbuild will only include the the
versionfield ofpackage.jsonin your bundle. This is non-standard behavior though and doesn't match the behavior of what happens when you import JSON in a real JavaScript runtime (after addingassert { type: 'json' }). In a real JavaScript runtime the only thing you can import is thedefaultimport. So with this release, esbuild will now prevent you from importing non-defaultimport names ifassert { type: 'json' }is present. This ensures that code containingassert { type: 'json' }isn't relying on non-standard behavior that won't work everywhere. So the following code is now an error with esbuild when bundling:import { version } from './package.json' assert { type: 'json' }In addition, adding
assert { type: 'json' }to an import statement now means esbuild will generate an error if the loader for the file is anything other thanjson, which is required by the import assertion specification.Provide a way to disable automatic escaping of
</script>If you inject esbuild's output into a script tag in an HTML file, code containing the literal characters
</script>will cause the tag to be ended early which will break the code:<script> console.log("</script>"); </script>To avoid this, esbuild automatically escapes these strings in generated JavaScript files (e.g.
"</script>"becomes"<\/script>"instead). This also applies to</style>in generated CSS files. Previously this always happened and there wasn't a way to turn this off.With this release, esbuild will now only do this if the
platformsetting is set tobrowser(the default value). Settingplatformtonodeorneutralwill disable this behavior. This behavior can also now be disabled with--supported:inline-script=false(for JS) and--supported:inline-style=false(for CSS).Throw an early error if decoded UTF-8 text isn't a
Uint8ArrayIf you run esbuild's JavaScript API in a broken JavaScript environment where
new TextEncoder().encode("") instanceof Uint8Arrayis false, then esbuild's API will fail with a confusing serialization error message that makes it seem like esbuild has a bug even though the real problem is that the JavaScript environment itself is broken. This can happen when using the test framework called Jest. With this release, esbuild's API will now throw earlier when it detects that the environment is unable to encode UTF-8 text correctly with an error message that makes it more clear that this is not a problem with esbuild.Change the default "legal comment" behavior
The legal comments feature automatically gathers comments containing
@licenseor@preserveand puts the comments somewhere (either in the generated code or in a separate file). People sometimes want this to happen so that the their dependencies' software licenses are retained in the generated output code. By default esbuild puts these comments at the end of the file when bundling. However, people sometimes find this confusing because these comments can be very generic and may not mention which library they come from. So with this release, esbuild will now discard legal comments by default. You now have to opt-in to preserving them if you want this behavior.Enable the
modulecondition by defaultPackage authors want to be able to use the new
exportsfield inpackage.jsonto provide tree-shakable ESM code for ESM-aware bundlers while simultaneously providing fallback CommonJS code for other cases.Node's proposed way to do this involves using the
importandrequireexport conditions so that you get the ESM code if you use an import statement and the CommonJS code if you use a require call. However, this has a major drawback: if some code in the bundle uses an import statement and other code in the bundle uses a require call, then you'll get two copies of the same package in the bundle. This is known as the dual package hazard and can lead to bloated bundles or even worse to subtle logic bugs.Webpack supports an alternate solution: an export condition called
modulethat takes effect regardless of whether the package was imported using an import statement or a require call. This works because bundlers such as Webpack support importing a ESM using a require call (something node doesn't support). You could already do this with esbuild using--conditions=modulebut you previously had to explicitly enable this. Package authors are concerned that esbuild users won't know to do this and will get suboptimal output with their package, so they have requested for esbuild to do this automatically.So with this release, esbuild will now automatically add the
modulecondition when there aren't any customconditionsalready configured. You can disable this with--conditions=orconditions:(i.e. explicitly clearing all custom conditions).Rename the
masterbranch tomainThe primary branch for this repository was previously called
masterbut is now calledmain. This change mirrors a similar change in many other projects.Remove esbuild's
_exit(0)hack for WebAssemblyNode had an unfortunate bug where the node process is unnecessarily kept open while a WebAssembly module is being optimized: #36616. This means cases where running
esbuildshould take a few milliseconds can end up taking many seconds instead.The workaround was to force node to exit by ending the process early. This was done by esbuild in one of two ways depending on the exit code. For non-zero exit codes (i.e. when there is a build error), the
esbuildcommand could just callprocess.kill(process.pid)to avoid the hang. But for zero exit codes, esbuild had to load a N-API native node extension that calls the operating system'sexit(0)function.However, this problem has essentially been fixed in node starting with version 18.3.0. So I have removed this hack from esbuild. If you are using an earlier version of node with
esbuild-wasmand you don't want theesbuildcommand to hang for a while when exiting, you can upgrade to node 18.3.0 or higher to remove the hang.The fix came from a V8 upgrade: this commit enabled dynamic tiering for WebAssembly by default for all projects that use V8's WebAssembly implementation. Previously all functions in the WebAssembly module were optimized in a single batch job but with dynamic tiering, V8 now optimizes individual WebAssembly functions as needed. This avoids unnecessary WebAssembly compilation which allows node to exit on time.
- 0.15.x
0.15.18
5 Dec 2022Performance improvements for both JS and CSS
This release brings noticeable performance improvements for JS parsing and for CSS parsing and printing. Here's an example benchmark for using esbuild to pretty-print a single large minified CSS file and JS file:
Test case Previous release This release 4.8mb CSS file 19ms 11ms (1.7x faster) 5.8mb JS file 36ms 32ms (1.1x faster) The performance improvements were very straightforward:
I definitely should have caught these performance issues earlier. Better late than never I suppose.
0.15.17
4 Dec 2022Search for missing source map code on the file system
Source maps are JSON files that map from compiled code back to the original code. They provide the original source code using two arrays:
sources(required) andsourcesContent(optional). When bundling is enabled, esbuild is able to bundle code with source maps that was compiled by other tools (e.g. with Webpack) and emit source maps that map all the way back to the original code (e.g. before Webpack compiled it).Previously if the input source maps omitted the optional
sourcesContentarray, esbuild would usenullfor the source content in the source map that it generates (since the source content isn't available). However, sometimes the original source code is actually still present on the file system. With this release, esbuild will now try to find the original source code using the path in thesourcesarray and will use that instead ofnullif it was found.Fix parsing bug with TypeScript
inferandextendsThis release fixes a bug where esbuild incorrectly failed to parse valid TypeScript code that nests
extendsinsideinferinsideextends, such as in the example below:type A<T> = {}; type B = {} extends infer T extends {} ? A<T> : never;TypeScript code that does this should now be parsed correctly.
Use
WebAssembly.instantiateStreamingif available (#1036, #1900)Currently the WebAssembly version of esbuild uses
fetchto downloadesbuild.wasmand thenWebAssembly.instantiateto compile it. There is a newer API calledWebAssembly.instantiateStreamingthat both downloads and compiles at the same time, which can be a performance improvement if both downloading and compiling are slow. With this release, esbuild now attempts to useWebAssembly.instantiateStreamingand falls back to the original approach if that fails.The implementation for this builds on a PR
Search for missing source map code on the file system
Source maps are JSON files that map from compiled code back to the original code. They provide the original source code using two arrays:
sources(required) andsourcesContent(optional). When bundling is enabled, esbuild is able to bundle code with source maps that was compiled by other tools (e.g. with Webpack) and emit source maps that map all the way back to the original code (e.g. before Webpack compiled it).Previously if the input source maps omitted the optional
sourcesContentarray, esbuild would usenullfor the source content in the source map that it generates (since the source content isn't available). However, sometimes the original source code is actually still present on the file system. With this release, esbuild will now try to find the original source code using the path in thesourcesarray and will use that instead ofnullif it was found.Fix parsing bug with TypeScript
inferandextendsThis release fixes a bug where esbuild incorrectly failed to parse valid TypeScript code that nests
extendsinsideinferinsideextends, such as in the example below:type A<T> = {}; type B = {} extends infer T extends {} ? A<T> : never;TypeScript code that does this should now be parsed correctly.
Use
WebAssembly.instantiateStreamingif available (#1036, #1900)Currently the WebAssembly version of esbuild uses
fetchto downloadesbuild.wasmand thenWebAssembly.instantiateto compile it. There is a newer API calledWebAssembly.instantiateStreamingthat both downloads and compiles at the same time, which can be a performance improvement if both downloading and compiling are slow. With this release, esbuild now attempts to useWebAssembly.instantiateStreamingand falls back to the original approach if that fails.The implementation for this builds on a PR
Preserve Webpack comments inside constructor calls
This improves the use of esbuild as a faster TypeScript-to-JavaScript frontend for Webpack, which has special magic comments inside
new Worker()expressions that affect Webpack's behavior.
0.15.16
27 Nov 2022Add a package alias feature
With this release, you can now easily substitute one package for another at build time with the new
aliasfeature. For example,--alias:oldpkg=newpkgreplaces all imports ofoldpkgwithnewpkg. One use case for this is easily replacing a node-only package with a browser-friendly package in 3rd-party code that you don't control. These new substitutions happen first before all of esbuild's existing path resolution logic.Note that when an import path is substituted using an alias, the resulting import path is resolved in the working directory instead of in the directory containing the source file with the import path. If needed, the working directory can be set with the
cdcommand when using the CLI or with theabsWorkingDirsetting when using the JS or Go APIs.Fix crash when pretty-printing minified JSX with object spread of object literal with computed property
JSX elements are translated to JavaScript function calls and JSX element attributes are translated to properties on a JavaScript object literal. These properties are always either strings (e.g. in
<x y />,yis a string) or an object spread (e.g. in<x {...y} />,yis an object spread) because JSX doesn't provide syntax for directly passing a computed property as a JSX attribute. However, esbuild's minifier has a rule that tries to inline object spread with an inline object literal in JavaScript. For example,x = { ...{ y } }is minified tox={y}when minification is enabled. This means that there is a way to generate a non-string non-spread JSX attribute in esbuild's internal representation. One example is with<x {...{ [y]: z }} />. When minification is enabled, esbuild's internal representation of this is something like<x [y]={z} />due to object spread inlining, which is not valid JSX syntax. If this internal representation is then pretty-printed as JSX using--minify --jsx=preserve, esbuild previously crashed when trying to print this invalid syntax. With this release, esbuild will now print<x {...{[y]:z}}/>in this scenario instead of crashing.
0.15.15
21 Nov 2022Remove duplicate CSS rules across files
When two or more CSS rules are exactly the same (even if they are not adjacent), all but the last one can safely be removed:
/* Before */ a { color: red; } span { font-weight: bold; } a { color: red; } /* After */ span { font-weight: bold; } a { color: red; }Previously esbuild only did this transformation within a single source file. But with this release, esbuild will now do this transformation across source files, which may lead to smaller CSS output if the same rules are repeated across multiple CSS source files in the same bundle. This transformation is only enabled when minifying (specifically when syntax minification is enabled).
Add
denoas a valid value fortargetThe
targetsetting in esbuild allows you to enable or disable JavaScript syntax features for a given version of a set of target JavaScript VMs. Previously Deno was not one of the JavaScript VMs that esbuild supported withtarget, but it will now be supported starting from this release. For example, versions of Deno older than v1.2 don't support the new||=operator, so adding e.g.--target=deno1.0to esbuild now lets you tell esbuild to transpile||=to older JavaScript.Fix the
esbuild-wasmpackage in Node v19A recent change to Node v19 added a non-writable
cryptoproperty to the global object: #44897. This conflicts with Go's WebAssembly shim code, which overwrites the globalcryptoproperty. As a result, all Go-based WebAssembly code that uses the built-in shim (including esbuild) is now broken on Node v19. This release of esbuild fixes the issue by reconfiguring the globalcryptoproperty to be writable before invoking Go's WebAssembly shim code.
Remove duplicate CSS rules across files
When two or more CSS rules are exactly the same (even if they are not adjacent), all but the last one can safely be removed:
/* Before */ a { color: red; } span { font-weight: bold; } a { color: red; } /* After */ span { font-weight: bold; } a { color: red; }Previously esbuild only did this transformation within a single source file. But with this release, esbuild will now do this transformation across source files, which may lead to smaller CSS output if the same rules are repeated across multiple CSS source files in the same bundle. This transformation is only enabled when minifying (specifically when syntax minification is enabled).
Add
denoas a valid value fortargetThe
targetsetting in esbuild allows you to enable or disable JavaScript syntax features for a given version of a set of target JavaScript VMs. Previously Deno was not one of the JavaScript VMs that esbuild supported withtarget, but it will now be supported starting from this release. For example, versions of Deno older than v1.2 don't support the new||=operator, so adding e.g.--target=deno1.0to esbuild now lets you tell esbuild to transpile||=to older JavaScript.Fix the
esbuild-wasmpackage in Node v19A recent change to Node v19 added a non-writable
cryptoproperty to the global object: #44897. This conflicts with Go's WebAssembly shim code, which overwrites the globalcryptoproperty. As a result, all Go-based WebAssembly code that uses the built-in shim (including esbuild) is now broken on Node v19. This release of esbuild fixes the issue by reconfiguring the globalcryptoproperty to be writable before invoking Go's WebAssembly shim code.Fix CSS dimension printing exponent confusion edge case
In CSS, a dimension token has a numeric "value" part and an identifier "unit" part. For example, the dimension token
32pxhas a value of32and a unit ofpx. The unit can be any valid CSS identifier. The value can be any number in floating-point format including an optional exponent (e.g.-3.14e-0has an exponent ofe-0). The full details of this syntax are here: w3.org/TR/css-syntax-3/.To maintain the integrity of the dimension token through the printing process, esbuild must handle the edge case where the unit looks like an exponent. One such case is the dimension
1e\32which has the value1and the unite2. It would be bad if this dimension token was printed such that a CSS parser would parse it as a number token with the value1e2instead of a dimension token. The way esbuild currently does this is to escape the leadingein the dimension unit, so esbuild would parse1e\32but print1\65 2(both1e\32and1\65 2represent a dimension token with a value of1and a unit ofe2).However, there is an even narrower edge case regarding this edge case. If the value part of the dimension token itself has an
e, then it's not necessary to escape theein the dimension unit because a CSS parser won't confuse the unit with the exponent even though it looks like one (since a number can only have at most one exponent). This came up because the grammar for the CSSunicode-rangeproperty uses a hack that lets you specify a hexadecimal range without quotes even though CSS has no token for a hexadecimal range. The hack is to allow the hexadecimal range to be parsed as a dimension token and optionally also a number token. Here is the grammar forunicode-range:unicode-range = <urange># <urange> = u '+' <ident-token> '?'* | u <dimension-token> '?'* | u <number-token> '?'* | u <number-token> <dimension-token> | u <number-token> <number-token> | u '+' '?'+
and here is an example
unicode-rangedeclaration that was problematic for esbuild:@font-face { unicode-range: U+0e2e-0e2f; }This is parsed as a dimension with a value of
+0e2and a unit ofe-0e2f. This was problematic for esbuild because the unit starts withe-0which could be confused with an exponent when appended after a number, so esbuild was escaping theecharacter in the unit. However, this escaping is unnecessary because in this case the dimension value already has an exponent in it. With this release, esbuild will no longer unnecessarily escape theein the dimension unit in these cases, which should fix the printing ofunicode-rangedeclarations.An aside: You may be wondering why esbuild is trying to escape the
eat all and why it doesn't just pass through the original source code unmodified. The reason why esbuild does this is that, for robustness, esbuild's AST generally tries to omit semantically-unrelated information and esbuild's code printers always try to preserve the semantics of the underlying AST. That way the rest of esbuild's internals can just deal with semantics instead of presentation. They don't have to think about how the AST will be printed when changing the AST. This is the same reason that esbuild's JavaScript AST doesn't have a "parentheses" node (e.g.a * (b + c)is represented by the ASTmultiply(a, add(b, c))instead ofmultiply(a, parentheses(add(b, c)))). Instead, the printer automatically inserts parentheses as necessary to maintain the semantics of the AST, which means all of the optimizations that run over the AST don't have to worry about keeping the parentheses up to date. Similarly, the CSS AST for the dimension token stores the actual unit and the printer makes sure the unit is properly escaped depending on what value it's placed after. All of the other code operating on CSS ASTs doesn't have to worry about parsing escapes to compare units or about keeping escapes up to date when the AST is modified. Hopefully that makes sense.Attempt to avoid creating the
node_modules/.cachedirectory for people that use Yarn 2+ in Plug'n'Play modeWhen Yarn's PnP mode is enabled, packages installed by Yarn may or may not be put inside
.zipfiles. The specific heuristics for when this happens change over time in between Yarn versions. This is problematic for esbuild because esbuild's JavaScript package needs to execute a binary file inside the package. Yarn makes extensive modifications to Node's file system APIs at run time to pretend that.zipfiles are normal directories and to make it hard to tell whether a file is real or not (since in theory it doesn't matter). But they haven't modified Node'schild_process.execFileSyncAPI so attempting to execute a file inside a zip file fails. To get around this, esbuild previously used Node's file system APIs to copy the binary executable to another location before invokingexecFileSync. Under the hood this caused Yarn to extract the file from the zip file into a real file that can then be run.However, esbuild copied its executable into
node_modules/.cache/esbuild. This is the official recommendation from the Yarn team for where packages are supposed to put these types of files when Yarn PnP is being used. However, users of Yarn PnP with esbuild find this really annoying because they don't like looking at thenode_modulesdirectory. With this release, esbuild now sets"preferUnplugged": truein itspackage.jsonfiles, which tells newer versions of Yarn to not put esbuild's packages in a zip file. There may exist older versions of Yarn that don't supportpreferUnplugged. In that case esbuild should still copy the executable to a cache directory, so it should still run (hopefully, since I haven't tested this myself). Note that esbuild setting"preferUnplugged": truemay have the side effect of esbuild taking up more space on the file system in the event that multiple platforms are installed simultaneously, or that you're using an older version of Yarn that always installs packages for all platforms. In that case you may want to update to a newer version of Yarn since Yarn has recently changed to only install packages for the current platform.
0.15.14
15 Nov 2022Fix parsing of TypeScript
inferinside a conditionalextendsUnlike JavaScript, parsing TypeScript sometimes requires backtracking. The
infer Atype operator can take an optional constraint of the forminfer A extends B. However, this syntax conflicts with the similar conditional type operatorA extends B ? C : Din cases where the syntax is combined, such asinfer A extends B ? C : D. This is supposed to be parsed as(infer A) extends B ? C : D. Previously esbuild incorrectly parsed this as(infer A extends B) ? C : Dinstead, which is a parse error since the?:conditional operator requires theextendskeyword as part of the conditional type. TypeScript disambiguates by speculatively parsing theextendsafter theinfer, but backtracking if a?token is encountered afterward. With this release, esbuild should now do the same thing, so esbuild should now correctly parse these types. Here's a real-world example of such a type:type Normalized<T> = T extends Array<infer A extends object ? infer A : never> ? Dictionary<Normalized<A>> : { [P in keyof T]: T[P] extends Array<infer A extends object ? infer A : never> ? Dictionary<Normalized<A>> : Normalized<T[P]> }Avoid unnecessary watch mode rebuilds when debug logging is enabled
When debug-level logs are enabled (such as with
--log-level=debug), esbuild's path resolution subsystem generates debug log messages that say something like "Read 20 entries for directory /home/user" to help you debug what esbuild's path resolution is doing. This caused esbuild's watch mode subsystem to add a dependency on the full list of entries in that directory since if that changes, the generated log message would also have to be updated. However, meant that on systems where a parent directory undergoes constant directory entry churn, esbuild's watch mode would continue to rebuild if--log-level=debugwas passed.With this release, these debug log messages are now generated by "peeking" at the file system state while bypassing esbuild's watch mode dependency tracking. So now watch mode doesn't consider the count of directory entries in these debug log messages to be a part of the build that needs to be kept up to date when the file system state changes.
0.15.13
3 Nov 2022Add support for the TypeScript 4.9
satisfiesoperatorTypeScript 4.9 introduces a new operator called
satisfiesthat lets you check that a given value satisfies a less specific type without casting it to that less specific type and without generating any additional code at run-time. It looks like this:const value = { foo: 1, bar: false } satisfies Record<string, number | boolean> console.log(value.foo.toFixed(1)) // TypeScript knows that "foo" is a number hereBefore this existed, you could use a cast with
asto check that a value satisfies a less specific type, but that removes any additional knowledge that TypeScript has about that specific value:const value = { foo: 1, bar: false } as Record<string, number | boolean> console.log(value.foo.toFixed(1)) // TypeScript no longer knows that "foo" is a numberYou can read more about this feature in TypeScript's blog post for 4.9 as well as the associated TypeScript issue for this feature.
This feature was implemented in esbuild
Fix watch mode constantly rebuilding if the parent directory is inaccessible
Android is unusual in that it has an inaccessible directory in the path to the root, which esbuild was not originally built to handle. To handle cases like this, the path resolution layer in esbuild has a hack where it treats inaccessible directories as empty. However, esbuild's watch implementation currently triggers a rebuild if a directory previously encountered an error but the directory now exists. The assumption is that the previous error was caused by the directory not existing. Although that's usually the case, it's not the case for this particular parent directory on Android. Instead the error is that the directory previously existed but was inaccessible.
This discrepancy between esbuild's path resolution layer and its watch mode was causing watch mode to rebuild continuously on Android. With this release, esbuild's watch mode instead checks for an error status change in the
readdirfile system call, so watch mode should no longer rebuild continuously on Android.Apply a fix for a rare deadlock with the JavaScript API (#1842, #2485)
There have been reports of esbuild sometimes exiting with an "all goroutines are asleep" deadlock message from the Go language runtime. This issue hasn't made much progress until recently, where a possible cause was discovered (thanks to @jfirebaugh for the investigation). This release contains a possible fix for that possible cause, so this deadlock may have been fixed. The fix cannot be easily verified because the deadlock is non-deterministic and rare. If this was indeed the cause, then this issue only affected the JavaScript API in situations where esbuild was already in the process of exiting.
In detail: The underlying cause is that Go's
sync.WaitGroupAPI for waiting for a set of goroutines to finish is not fully thread-safe. Specifically it's not safe to callAdd()concurrently withWait()when the wait group counter is zero due to a data race. This situation could come up with esbuild's JavaScript API when the host JavaScript process closes the child process's stdin and the child process (with no active tasks) callsWait()to check that there are no active tasks, at the same time as esbuild's watchdog timer callsAdd()to add an active task (that pings the host to see if it's still there). The fix in this release is to avoid callingAdd()once we learn that stdin has been closed but before we callWait().
0.15.12
19 Oct 2022Fix minifier correctness bug with single-use substitutions
When minification is enabled, esbuild will attempt to eliminate variables that are only used once in certain cases. For example, esbuild minifies this code:
function getEmailForUser(name) { let users = db.table('users'); let user = users.find({ name }); let email = user?.get('email'); return email; }into this code:
function getEmailForUser(e){return db.table("users").find({name:e})?.get("email")}However, this transformation had a bug where esbuild did not correctly consider the "read" part of binary read-modify-write assignment operators. For example, it's incorrect to minify the following code into
bar += fn()because the call tofn()might modifybar:const foo = fn(); bar += foo;
In addition to fixing this correctness bug, this release also improves esbuild's output in the case where all values being skipped over are primitives:
function toneMapLuminance(r, g, b) { let hdr = luminance(r, g, b) let decay = 1 / (1 + hdr) return 1 - decay }Previous releases of esbuild didn't substitute these single-use variables here, but esbuild will now minify this to the following code starting with this release:
function toneMapLuminance(e,n,a){return 1-1/(1+luminance(e,n,a))}
0.15.11
14 Oct 2022Fix various edge cases regarding template tags and
thisThis release fixes some bugs where the value of
thiswasn't correctly preserved when evaluating template tags in a few edge cases. These edge cases are listed below:async function test() { class Foo { foo() { return this } } class Bar extends Foo { a = async () => super.foo`` b = async () => super['foo']`` c = async (foo) => super[foo]`` } function foo() { return this } const obj = { foo } const bar = new Bar console.log( (await bar.a()) === bar, (await bar.b()) === bar, (await bar.c('foo')) === bar, { foo }.foo``.foo === foo, (true && obj.foo)`` !== obj, (false || obj.foo)`` !== obj, (null ?? obj.foo)`` !== obj, ) } test()Each edge case in the code above previously incorrectly printed
falsewhen run through esbuild with--minify --target=es6but now correctly printstrue. These edge cases are unlikely to have affected real-world code.
0.15.10
29 Sep 2022Add support for node's "pattern trailers" syntax
After esbuild implemented node's
exportsfeature inpackage.json, node changed the feature to also allow text after*wildcards in patterns. Previously the*was required to be at the end of the pattern. It lets you do something like this:{ "exports": { "./features/*": "./features/*.js", "./features/*.js": "./features/*.js" } }With this release, esbuild now supports these types of patterns too.
Fix subpath imports with Yarn PnP
Node has a little-used feature called subpath imports which are package-internal imports that start with
#and that go through theimportsmap inpackage.json. Previously esbuild had a bug that caused esbuild to not handle these correctly in packages installed via Yarn's "Plug'n'Play" installation strategy. The problem was that subpath imports were being checked after Yarn PnP instead of before. This release reorders these checks, which should allow subpath imports to work in this case.Link from JS to CSS in the metafile (#1861, #2565)
When you import CSS into a bundled JS file, esbuild creates a parallel CSS bundle next to your JS bundle. So if
app.tsimports some CSS files and you bundle it, esbuild will give youapp.jsandapp.css. You would then add both<script src="app.js"></script>and<link href="app.css" rel="stylesheet">to your HTML to include everything in the page. This approach is more efficient than having esbuild insert additional JavaScript intoapp.jsthat downloads and includesapp.cssbecause it means the browser can download and parse both the CSS and the JS in parallel (and potentially apply the CSS before the JS has even finished downloading).However, sometimes it's difficult to generate the
<link>tag. One case is when you've added[hash]to the entry names setting to include a content hash in the file name. Then the file name will look something likeapp-GX7G2SBE.cssand may change across subsequent builds. You can tell esbuild to generate build metadata using themetafileAPI option but the metadata only tells you which generated JS bundle corresponds to a JS entry point (via theentryPointproperty), not which file corresponds to the associated CSS bundle. Working around this was hacky and involved string manipulation.This release adds the
cssBundleproperty to the metafile to make this easier. It's present on the metadata for the generated JS bundle and points to the associated CSS bundle. So to generate the HTML tags for a given JS entry point, you first find the output file with theentryPointyou are looking for (and put that in a<script>tag), then check for thecssBundleproperty to find the associated CSS bundle (and put that in a<link>tag).One thing to note is that there is deliberately no
jsBundleproperty mapping the other way because it's not a 1:1 relationship. Two JS bundles can share the same CSS bundle in the case where the associated CSS bundles have the same name and content. In that case there would be no one value for a hypotheticaljsBundleproperty to have.
0.15.9
22 Sep 2022Fix an obscure npm package installation issue with
--omit=optionalThe previous release introduced a regression with
npm install esbuild --omit=optionalwhere the filenode_modules/.bin/esbuildwould no longer be present after installation. That could cause any package scripts which used theesbuildcommand to no longer work. This release fixes the regression sonode_modules/.bin/esbuildshould now be present again after installation. This regression only affected people installing esbuild usingnpmwith either the--omit=optionalor--no-optionalflag, which is a somewhat unusual situation.More details:
The reason for this regression is due to some obscure npm implementation details. Since the Go compiler doesn't support trivial cross-compiling on certain Android platforms, esbuild's installer installs a WebAssembly shim on those platforms instead. In the previous release I attempted to simplify esbuild's WebAssembly shims to depend on the
esbuild-wasmpackage instead of including another whole copy of the WebAssembly binary (to make publishing faster and to save on file system space after installation). However, both theesbuildpackage and theesbuild-wasmpackage provide a binary calledesbuildand it turns out that addingesbuild-wasmas a nested dependency of theesbuildpackage (specificallyesbuildoptionally depends on@esbuild/android-armwhich depends onesbuild-wasm) caused npm to be confused about whatnode_modules/.bin/esbuildis supposed to be.It's pretty strange and unexpected that disabling the installation of optional dependencies altogether would suddenly cause an optional dependency's dependency to conflict with the top-level package. What happens under the hood is that if
--omit=optionalis present, npm attempts to uninstall theesbuild-wasmnested dependency at the end ofnpm install(even though theesbuild-wasmpackage was never installed due to--omit=optional). This uninstallation causesnode_modules/.bin/esbuildto be deleted.After doing a full investigation, I discovered that npm's handling of the
.bindirectory is deliberately very brittle. When multiple packages in the dependency tree put something in.binwith the same name, the end result is non-deterministic/random. What you get in.binmight be from one package, from the other package, or might be missing entirely. The workaround suggested by npm is to just avoid having two packages that put something in.binwith the same name. So this was fixed by making the@esbuild/android-armandesbuild-android-64packages each include another whole copy of the WebAssembly binary, which works because these packages don't put anything in.bin.
0.15.8
18 Sep 2022Fix JSX name collision edge case
Code generated by esbuild could have a name collision in the following edge case:
In this case, esbuild previously generated two variables with the same name
import_react, like this:var import_react = require("react"); var import_react2 = require("@remix-run/react");That bug is fixed in this release. The code generated by esbuild no longer contains a name collision.
Fall back to WebAssembly on Android ARM (#1556, #1578, #2335, #2526)
Go's compiler supports trivial cross-compiling to almost all platforms without installing any additional software other than the Go compiler itself. This has made it very easy for esbuild to publish native binary executables for many platforms. However, it strangely doesn't support cross-compiling to Android ARM without installing the Android build tools.
So instead of publishing a native esbuild binary executable to npm, this release publishes a WebAssembly fallback build. This is essentially the same as the
esbuild-wasmpackage but it's installed automatically when you install theesbuildpackage on Android ARM. So packages that depend on theesbuildpackage should now work on Android ARM. This change has not yet been tested end-to-end because I don't have a 32-bit Android ARM device myself, but in theory it should work.This inherits the drawbacks of WebAssembly including significantly slower performance than native as well as potentially also more severe memory usage limitations and lack of certain features (e.g.
--serve). If you want to use a native binary executable of esbuild on Android ARM, you may be able to build it yourself from source after installing the Android build tools.Attempt to better support Yarn's
ignorePatternDatafeaturePart of resolving paths in a project using Yarn's Plug'n'Play feature involves evaluating a regular expression in the
ignorePatternDataproperty of.pnp.data.json. However, it turns out that the particular regular expressions generated by Yarn use some syntax that works with JavaScript regular expressions but that does not work with Go regular expressions.In this release, esbuild will now strip some of the the problematic syntax from the regular expression before compiling it, which should hopefully allow it to be compiled by Go's regular expression engine. The specific character sequences that esbuild currently strips are as follows:
These seem to be used by Yarn to avoid the
.and..path segments in the middle of relative paths. The removal of these character sequences seems relatively harmless in this case since esbuild shouldn't ever generate such path segments. This change should add support to esbuild for Yarn'spnpIgnorePatternsfeature.
Fix JSX name collision edge case
Code generated by esbuild could have a name collision in the following edge case:
The JSX transformation mode is set to
automatic, which causesimportstatements to be insertedAn element uses a
{...spread}followed by akey={...}, which uses the legacycreateElementfallback imported fromreactAnother import uses a name that ends with
reactsuch as@remix-run/reactThe output format has been set to CommonJS so that
importstatements are converted into require calls
In this case, esbuild previously generated two variables with the same name
import_react, like this:var import_react = require("react"); var import_react2 = require("@remix-run/react");That bug is fixed in this release. The code generated by esbuild no longer contains a name collision.
Fall back to WebAssembly on Android ARM (#1556, #1578, #2335, #2526)
Go's compiler supports trivial cross-compiling to almost all platforms without installing any additional software other than the Go compiler itself. This has made it very easy for esbuild to publish native binary executables for many platforms. However, it strangely doesn't support cross-compiling to Android ARM without installing the Android build tools.
So instead of publishing a native esbuild binary executable to npm, this release publishes a WebAssembly fallback build. This is essentially the same as the
esbuild-wasmpackage but it's installed automatically when you install theesbuildpackage on Android ARM. So packages that depend on theesbuildpackage should now work on Android ARM. This change has not yet been tested end-to-end because I don't have a 32-bit Android ARM device myself, but in theory it should work.This inherits the drawbacks of WebAssembly including significantly slower performance than native as well as potentially also more severe memory usage limitations and lack of certain features (e.g.
--serve). If you want to use a native binary executable of esbuild on Android ARM, you may be able to build it yourself from source after installing the Android build tools.Attempt to better support Yarn's
ignorePatternDatafeaturePart of resolving paths in a project using Yarn's Plug'n'Play feature involves evaluating a regular expression in the
ignorePatternDataproperty of.pnp.data.json. However, it turns out that the particular regular expressions generated by Yarn use some syntax that works with JavaScript regular expressions but that does not work with Go regular expressions.In this release, esbuild will now strip some of the the problematic syntax from the regular expression before compiling it, which should hopefully allow it to be compiled by Go's regular expression engine. The specific character sequences that esbuild currently strips are as follows:
(?!\.)(?!(?:^|\/)\.)(?!\.{1,2}(?:\/|$))(?!(?:^|\/)\.{1,2}(?:\/|$))
These seem to be used by Yarn to avoid the
.and..path segments in the middle of relative paths. The removal of these character sequences seems relatively harmless in this case since esbuild shouldn't ever generate such path segments. This change should add support to esbuild for Yarn'spnpIgnorePatternsfeature.Fix non-determinism issue with legacy block-level function declarations and strict mode
When function declaration statements are nested inside a block in strict mode, they are supposed to only be available within that block's scope. But in "sloppy mode" (which is what non-strict mode is commonly called), they are supposed to be available within the whole function's scope:
// This returns 1 due to strict mode function test1() { 'use strict' function fn() { return 1 } if (true) { function fn() { return 2 } } return fn() } // This returns 2 due to sloppy mode function test2() { function fn() { return 1 } if (true) { function fn() { return 2 } } return fn() }To implement this, esbuild compiles these two functions differently to reflect their different semantics:
function test1() { "use strict"; function fn() { return 1; } if (true) { let fn2 = function() { return 2; }; } return fn(); } function test2() { function fn() { return 1; } if (true) { let fn2 = function() { return 2; }; var fn = fn2; } return fn(); }However, the compilation had a subtle bug where the automatically-generated function-level symbols for multible hoisted block-level function declarations in the same block a sloppy-mode context were generated in a random order if the output was in strict mode, which could be the case if TypeScript's
alwaysStrictsetting was set to true. This lead to non-determinism in the output as the minifier would randomly exchange the generated names for these symbols on different runs. This bug has been fixed by sorting the keys of the unordered map before iterating over them.Fix parsing of
@keyframeswith string identifiersFirefox supports
@keyframeswith string identifier names. Previously this was treated as a syntax error by esbuild as it doesn't work in any other browser. The specification allows for this however, so it's technically not a syntax error (even though it would be unwise to use this feature at the moment). There was also a bug where esbuild would remove the identifier name in this case as the syntax wasn't recognized.This release changes esbuild's parsing of
@keyframesto now consider this case to be an unrecognized CSS rule. That means it will be passed through unmodified (so you can now use esbuild to bundle this Firefox-specific CSS) but the CSS will not be pretty-printed or minified. I don't think it makes sense for esbuild to have special code to handle this Firefox-specific syntax at this time. This decision can be revisited in the future if other browsers add support for this feature.Add the
--jsx-side-effectsAPI option (#2539, #2546)By default esbuild assumes that JSX expressions are side-effect free, which means they are annoated with
/* @__PURE__ */comments and are removed during bundling when they are unused. This follows the common use of JSX for virtual DOM and applies to the vast majority of JSX libraries. However, some people have written JSX libraries that don't have this property. JSX expressions can have arbitrary side effects and can't be removed. If you are using such a library, you can now pass--jsx-side-effectsto tell esbuild that JSX expressions have side effects so it won't remove them when they are unused.This feature was contributed
0.15.7
4 Sep 2022Add
--watch=foreverto allow esbuild to never terminate (#1511, #1885)Currently using esbuild's watch mode via
--watchfrom the CLI will stop watching if stdin is closed. The rationale is that stdin is automatically closed by the OS when the parent process exits, so stopping watch mode when stdin is closed ensures that esbuild's watch mode doesn't keep running forever after the parent process has been closed. For example, it would be bad if you wrote a shell script that didesbuild --watch &to run esbuild's watch mode in the background, and every time you run the script it creates a newesbuildprocess that runs forever.However, there are cases when it makes sense for esbuild's watch mode to never exit. One such case is within a short-lived VM where the lifetime of all processes inside the VM is expected to be the lifetime of the VM. Previously you could easily do this by piping the output of a long-lived command into esbuild's stdin such as
sleep 999999999 | esbuild --watch &. However, this possibility often doesn't occur to people, and it also doesn't work on Windows. People also sometimes attempt to keep esbuild open by piping an infinite stream of data to esbuild such as withesbuild --watch </dev/zero &which causes esbuild to spin at 100% CPU. So with this release, esbuild now has a--watch=foreverflag that will not stop watch mode when stdin is closed.Work around
PATHwithoutnodein install scriptSome people install esbuild's npm package in an environment without the
nodecommand in theirPATH. This fails on Windows because esbuild's install script runs theesbuildcommand before exiting as a sanity check, and on Windows theesbuildcommand has to be a JavaScript file because of some internal details about how npm handles thebinfolder (specifically theesbuildcommand lacks the.exeextension, which is required on Windows). This release attempts to work around this problem by usingprocess.execPathinstead of"node"as the command for running node. In theory this means the installer can now still function on Windows if something is wrong withPATH.
0.15.6
30 Aug 2022Lower
for awaitloopsThis release lowers
for awaitloops to the equivalentforloop containingawaitwhen esbuild is configured such thatfor awaitloops are unsupported. This transform still requires at least generator functions to be supported since esbuild's lowering ofawaitcurrently relies on generators. This new transformation is mostly modeled after what the TypeScript compiler does. Here's an example:async function f() { for await (let x of y) x() }The code above will now become the following code with
--target=es2017(omitting the code for the__forAwaithelper function):async function f() { try { for (var iter = __forAwait(y), more, temp, error; more = !(temp = await iter.next()).done; more = false) { let x = temp.value; x(); } } catch (temp) { error = [temp]; } finally { try { more && (temp = iter.return) && await temp.call(iter); } finally { if (error) throw error[0]; } } }Automatically fix invalid
supportedconfigurationsThe
--target=setting lets you tell esbuild to target a specific version of one or more JavaScript runtimes such aschrome80,node14and esbuild will restrict its output to only those features supported by all targeted JavaScript runtimes. More recently, esbuild introduced the--supported:setting that lets you override which features are supported on a per-feature basis. However, this now lets you configure nonsensical things such as--supported:async-await=false --supported:async-generator=true. Previously doing this could result in esbuild building successfully but producing invalid output.Starting with this release, esbuild will now attempt to automatically fix nonsensical feature override configurations by introducing more overrides until the configuration makes sense. So now the configuration from previous example will be changed such that
async-await=falseimpliesasync-generator=false. The full list of implications that were introduced is below:Implement a small minification improvement
Some people write code that contains a label with an immediate break such as
x: break x. Previously this code was not removed during minification but it will now be removed during minification starting with this release.
Lower
for awaitloopsThis release lowers
for awaitloops to the equivalentforloop containingawaitwhen esbuild is configured such thatfor awaitloops are unsupported. This transform still requires at least generator functions to be supported since esbuild's lowering ofawaitcurrently relies on generators. This new transformation is mostly modeled after what the TypeScript compiler does. Here's an example:async function f() { for await (let x of y) x() }The code above will now become the following code with
--target=es2017(omitting the code for the__forAwaithelper function):async function f() { try { for (var iter = __forAwait(y), more, temp, error; more = !(temp = await iter.next()).done; more = false) { let x = temp.value; x(); } } catch (temp) { error = [temp]; } finally { try { more && (temp = iter.return) && await temp.call(iter); } finally { if (error) throw error[0]; } } }Automatically fix invalid
supportedconfigurationsThe
--target=setting lets you tell esbuild to target a specific version of one or more JavaScript runtimes such aschrome80,node14and esbuild will restrict its output to only those features supported by all targeted JavaScript runtimes. More recently, esbuild introduced the--supported:setting that lets you override which features are supported on a per-feature basis. However, this now lets you configure nonsensical things such as--supported:async-await=false --supported:async-generator=true. Previously doing this could result in esbuild building successfully but producing invalid output.Starting with this release, esbuild will now attempt to automatically fix nonsensical feature override configurations by introducing more overrides until the configuration makes sense. So now the configuration from previous example will be changed such that
async-await=falseimpliesasync-generator=false. The full list of implications that were introduced is below:async-await=falseimplies:async-generator=falsefor-await=falsetop-level-await=false
generator=falseimplies:async-generator=false
object-accessors=falseimplies:class-private-accessor=falseclass-private-static-accessor=false
class-field=falseimplies:class-private-field=false
class-static-field=falseimplies:class-private-static-field=false
class=falseimplies:class-field=falseclass-private-accessor=falseclass-private-brand-check=falseclass-private-field=falseclass-private-method=falseclass-private-static-accessor=falseclass-private-static-field=falseclass-private-static-method=falseclass-static-blocks=falseclass-static-field=false
Implement a small minification improvement
Some people write code that contains a label with an immediate break such as
x: break x. Previously this code was not removed during minification but it will now be removed during minification starting with this release.Fix installing esbuild via Yarn with
enableScripts: falseconfiguredIf esbuild is installed with Yarn with the
enableScripts: falsesetting configured, then Yarn will not "unplug" theesbuildpackage (i.e. it will keep the entire package inside a.zipfile). This messes with esbuild's library code that extracts the platform-specific binary executable because that code copies the binary executable into the esbuild package directory, and Yarn's.zipfile system shim doesn't let you write to a directory inside of a.zipfile. This release fixes this problem by writing to thenode_modules/.cache/esbuilddirectory instead in this case. So you should now be able to use esbuild with Yarn whenenableScripts: falseis configured.This fix was contributed
0.15.5
17 Aug 2022Fix issues with Yarn PnP and Yarn's workspaces feature
This release makes sure esbuild works with a Yarn feature called workspaces. Previously esbuild wasn't tested in this scenario, but this scenario now has test coverage. Getting this to work involved further tweaks to esbuild's custom code for what happens after Yarn PnP's path resolution algorithm runs, which is not currently covered by Yarn's PnP specification. These tweaks also fix
exportsmap resolution with Yarn PnP for non-empty subpaths, which wasn't previously working.
0.15.4
16 Aug 2022Consider TypeScript import assignments to be side-effect free
TypeScript has a legacy import syntax for working with TypeScript namespaces that looks like this:
import { someNamespace } from './some-file' import bar = someNamespace.foo; // some-file.ts export namespace someNamespace { export let foo = 123 }Since esbuild converts TypeScript into JavaScript one file at a time, it doesn't know if
baris supposed to be a value or a type (or both, which TypeScript actually allows in this case). This is problematic because values are supposed to be kept during the conversion but types are supposed to be removed during the conversion. Currently esbuild keepsbarin the output, which is done becausesomeNamespace.foois a property access and property accesses run code that could potentially have a side effect (although there is no side effect in this case).With this release, esbuild will now consider
someNamespace.footo have no side effects. This meansbarwill now be removed when bundling and when tree shaking is enabled. Note that it will still not be removed when tree shaking is disabled. This is because in this mode, esbuild supports adding additional code to the end of the generated output that's in the same scope as the module. That code could potentially make use ofbar, so it would be incorrect to remove it. If you wantbarto be removed, you'll have to enable tree shaking (which tells esbuild that nothing else depends on the unexported top-level symbols in the generated output).Change the order of the banner and the
"use strict"directivePreviously the top of the file contained the following things in order:
This was problematic for people that used the
bannerAPI option to insert the hashbang comment instead of using esbuild's hashbang comment preservation feature. So with this release, the order has now been changed to:I'm considering this change to be a bug fix instead of a breaking change because esbuild's documentation states that the
bannerAPI option can be used to "insert an arbitrary string at the beginning of generated JavaScript files". While this isn't technically true because esbuild may still insert the original hashbang comment before the banner, it's at least more correct now because the banner will now come before the"use strict"directive.For context: JavaScript files recently allowed using a hashbang comment, which starts with
#!and which must start at the very first character of the file. It allows Unix systems to execute the file directly as a script without needing to prefix it by thenodecommand. This comment typically has the value#!/usr/bin/env node. Hashbang comments will be a part of ES2023 when it's released next year.Fix
exportsmaps with Yarn PnP path resolutionThe Yarn PnP specification says that to resolve a package path, you first resolve it to the absolute path of a directory, and then you run node's module resolution algorithm on it. Previously esbuild followed this part of the specification. However, doing this means that
exportsinpackage.jsonis not respected because node's module resolution algorithm doesn't interpretexportsfor absolute paths. So with this release, esbuild will now use a modified algorithm that deviates from both specifications but that should hopefully behave more similar to what Yarn actually does: node's module resolution algorithm is run with the original import path but starting from the directory returned by Yarn PnP.
0.15.3
14 Aug 2022Change the Yarn PnP manifest to a singleton
Previously esbuild searched for the Yarn PnP manifest in the parent directories of each file. But with Yarn's
enableGlobalCachesetting it's possible to configure Yarn PnP's implementation to reach outside of the directory subtree containing the Yarn PnP manifest. This was causing esbuild to fail to bundle projects with theenableGlobalCachesetting enabled.To handle this case, esbuild will now only search for the Yarn PnP manifest in the current working directory of the esbuild process. If you're using esbuild's CLI, this means you will now have to
cdinto the appropriate directory first. If you're using esbuild's API, you can override esbuild's value for the current working directory with theabsWorkingDirAPI option.Fix Yarn PnP resolution failures due to backslashes in paths on Windows
Previously dependencies of a Yarn PnP virtual dependency failed to resolve on Windows. This was because Windows uses
\instead of/as a path separator, and the path manipulation algorithms used for Yarn PnP expected/. This release converts\into/in Windows paths, which fixes this issue.Fix
sideEffectspatterns containing slashes on WindowsThe
sideEffectsfield inpackage.jsonlets you specify an array of patterns to mark which files have side effects (which causes all other files to be considered to not have side effects by exclusion). That looks like this:"sideEffects": [ "**/index.js", "**/index.prod.js" ]
However, the presence of the
/character in the pattern meant that the pattern failed to match Windows-style paths, which brokesideEffectson Windows in this case. This release fixes this problem by adding additional code to handle Windows-style paths.
0.15.2
12 Aug 2022Fix Yarn PnP issue with packages containing
index.js(#2455, #2461)Yarn PnP's tests require the resolved paths to end in
/. That's not how the rest of esbuild's internals work, however, and doing this messed up esbuild's node module path resolution regarding automatically-detectedindex.jsfiles. Previously packages that relied on implicitindex.jsresolution rules didn't work with esbuild under Yarn PnP. Removing this slash has fixed esbuild's path resolution behavior regardingindex.js, which should now the same both with and without Yarn PnP.Fix Yarn PnP support for
extendsintsconfig.jsonPreviously using
extendsintsconfig.jsonwith a path in a Yarn PnP package didn't work. This is because the process of setting up package path resolution rules requires parsingtsconfig.jsonfiles (due to thebaseUrlandpathsfeatures) and resolvingextendsto a package path requires package path resolution rules to already be set up, which is a circular dependency. This cycle is broken by using special rules forextendsintsconfig.jsonthat bypasses esbuild's normal package path resolution process. This is why usingextendswith a Yarn PnP package didn't automatically work. With this release, these special rules have been modified to check for a Yarn PnP manifest so this case should work now.Fix Yarn PnP support in
esbuild-wasmWhen running esbuild via WebAssembly, Yarn PnP support previously failed because Go's file system internals return
EINVALwhen trying to read a.zipfile as a directory when run with WebAssembly. This was unexpected because Go's file system internals returnENOTDIRfor this case on native. This release updates esbuild to treatEINVALlikeENOTDIRin this case, which fixes usingesbuild-wasmto bundle a Yarn PnP project.Note that to be able to use
esbuild-wasmfor Yarn PnP successfully, you currently have to run it usingnodeinstead ofyarn node. This is because the file system shim that Yarn overwrites node's native file system API with currently generates invalid file descriptors with negative values when inside a.zipfile. This prevents esbuild from working correctly because Go's file system internals don't expect syscalls that succeed without an error to return an invalid file descriptor. Yarn is working on fixing their use of invalid file descriptors.
0.15.1
10 Aug 2022Update esbuild's Yarn Plug'n'Play implementation to match the latest specification changes (#2452, #2453)
This release updates esbuild's implementation of Yarn Plug'n'Play to match some changes to Yarn's specification that just landed. The changes are as follows:
These fixes mean that esbuild's implementation of Plug'n'Play now matches Yarn's implementation more closely, and esbuild can now correctly build more projects that use Plug'n'Play.
0.15.0
10 Aug 2022Implement the Yarn Plug'n'Play module resolution algorithm (#154, #237, #1263, #2451)
Node comes with a package manager called npm, which installs packages into a
node_modulesfolder. Node and esbuild both come with built-in rules for resolving import paths to packages withinnode_modules, so packages installed via npm work automatically without any configuration. However, many people use an alternative package manager called Yarn. While Yarn can install packages usingnode_modules, it also offers a different package installation strategy called Plug'n'Play, which is often shortened to "PnP" (not to be confused with pnpm, which is an entirely different unrelated package manager).Plug'n'Play installs packages as
.zipfiles on your file system. The packages are never actually unzipped. Since Node doesn't know anything about Yarn's package installation strategy, this means you can no longer run your code with Node as it won't be able to find your packages. Instead, you need to run your code with Yarn, which applies patches to Node's file system APIs before running your code. These patches attempt to make zip files seem like normal directories. When running under Yarn, using Node's file system API to read./some.zip/lib/file.jsactually automatically extractslib/file.jsfrom./some.zipat run-time as if it was a normal file. Other file system APIs behave similarly. However, these patches don't work with esbuild because esbuild is not written in JavaScript; it's a native binary executable that interacts with the file system directly through the operating system.Previously the workaround for using esbuild with Plug'n'Play was to use the
@yarnpkg/esbuild-plugin-pnpplugin with esbuild's JavaScript API. However, this wasn't great because the plugin needed to potentially intercept every single import path and file load to check whether it was a Plug'n'Play package, which has an unusually high performance cost. It also meant that certain subtleties of path resolution rules within a.zipfile could differ slightly from the way esbuild normally works since path resolution inside.zipfiles was implemented by Yarn, not by esbuild (which is due to a limitation of esbuild's plugin API).With this release, esbuild now contains an independent implementation of Yarn's Plug'n'Play algorithm (which is used when esbuild finds a
.pnp.js,.pnp.cjs, or.pnp.data.jsonfile in the directory tree). Creating additional implementations of this algorithm recently became possible because Yarn's package manifest format was recently documented: yarnpkg.com/advanced/pnp-spec/. This should mean that you can now use esbuild to bundle Plug'n'Play projects without any additional configuration (so you shouldn't need@yarnpkg/esbuild-plugin-pnpanymore). Bundling these projects should now happen much faster as Yarn no longer even needs to be run at all. Bundling the Yarn codebase itself with esbuild before and after this change seems to demonstrate over a 10x speedup (3.4s to 0.24s). And path resolution rules within Yarn packages should now be consistent with how esbuild handles regular Node packages. For example, fields such asmoduleandbrowserinpackage.jsonfiles within.zipfiles should now be respected.Keep in mind that this is brand new code and there may be some initial issues to work through before esbuild's implementation is solid. Yarn's Plug'n'Play specification is also brand new and may need some follow-up edits to guide new implementations to match Yarn's exact behavior. If you try this out, make sure to test it before committing to using it, and let me know if anything isn't working as expected. Should you need to debug esbuild's path resolution, you may find
--log-level=verbosehelpful.
This release contains backwards-incompatible changes. Since esbuild is before version 1.0.0, these changes have been released as a new minor version to reflect this (as recommended by npm). You should either be pinning the exact version of
esbuildin yourpackage.jsonfile or be using a version range syntax that only accepts patch upgrades such as~0.14.0. See the documentation about semver for more information.Implement the Yarn Plug'n'Play module resolution algorithm (#154, #237, #1263, #2451)
Node comes with a package manager called npm, which installs packages into a
node_modulesfolder. Node and esbuild both come with built-in rules for resolving import paths to packages withinnode_modules, so packages installed via npm work automatically without any configuration. However, many people use an alternative package manager called Yarn. While Yarn can install packages usingnode_modules, it also offers a different package installation strategy called Plug'n'Play, which is often shortened to "PnP" (not to be confused with pnpm, which is an entirely different unrelated package manager).Plug'n'Play installs packages as
.zipfiles on your file system. The packages are never actually unzipped. Since Node doesn't know anything about Yarn's package installation strategy, this means you can no longer run your code with Node as it won't be able to find your packages. Instead, you need to run your code with Yarn, which applies patches to Node's file system APIs before running your code. These patches attempt to make zip files seem like normal directories. When running under Yarn, using Node's file system API to read./some.zip/lib/file.jsactually automatically extractslib/file.jsfrom./some.zipat run-time as if it was a normal file. Other file system APIs behave similarly. However, these patches don't work with esbuild because esbuild is not written in JavaScript; it's a native binary executable that interacts with the file system directly through the operating system.Previously the workaround for using esbuild with Plug'n'Play was to use the
@yarnpkg/esbuild-plugin-pnpplugin with esbuild's JavaScript API. However, this wasn't great because the plugin needed to potentially intercept every single import path and file load to check whether it was a Plug'n'Play package, which has an unusually high performance cost. It also meant that certain subtleties of path resolution rules within a.zipfile could differ slightly from the way esbuild normally works since path resolution inside.zipfiles was implemented by Yarn, not by esbuild (which is due to a limitation of esbuild's plugin API).With this release, esbuild now contains an independent implementation of Yarn's Plug'n'Play algorithm (which is used when esbuild finds a
.pnp.js,.pnp.cjs, or.pnp.data.jsonfile in the directory tree). Creating additional implementations of this algorithm recently became possible because Yarn's package manifest format was recently documented: yarnpkg.com/advanced/pnp-spec/. This should mean that you can now use esbuild to bundle Plug'n'Play projects without any additional configuration (so you shouldn't need@yarnpkg/esbuild-plugin-pnpanymore). Bundling these projects should now happen much faster as Yarn no longer even needs to be run at all. Bundling the Yarn codebase itself with esbuild before and after this change seems to demonstrate over a 10x speedup (3.4s to 0.24s). And path resolution rules within Yarn packages should now be consistent with how esbuild handles regular Node packages. For example, fields such asmoduleandbrowserinpackage.jsonfiles within.zipfiles should now be respected.Keep in mind that this is brand new code and there may be some initial issues to work through before esbuild's implementation is solid. Yarn's Plug'n'Play specification is also brand new and may need some follow-up edits to guide new implementations to match Yarn's exact behavior. If you try this out, make sure to test it before committing to using it, and let me know if anything isn't working as expected. Should you need to debug esbuild's path resolution, you may find
--log-level=verbosehelpful.
- 0.14.x
0.14.54
8 Aug 2022Fix optimizations for calls containing spread arguments
This release fixes the handling of spread arguments in the optimization of
/* @__PURE__ */comments, empty functions, and identity functions:// Original code function empty() {} function identity(x) { return x } /* @__PURE__ */ a(...x) /* @__PURE__ */ new b(...x) empty(...x) identity(...x) // Old output (with --minify --tree-shaking=true) ...x;...x;...x;...x; // New output (with --minify --tree-shaking=true) function identity(n){return n}[...x];[...x];[...x];identity(...x);Previously esbuild assumed arguments with side effects could be directly inlined. This is almost always true except for spread arguments, which are not syntactically valid on their own and which have the side effect of causing iteration, which might have further side effects. Now esbuild will wrap these elements in an unused array so that they are syntactically valid and so that the iteration side effects are preserved.
0.14.53
2 Aug 2022This release fixes a minor issue with the previous release: I had to rename the package
esbuild-linux-loong64to@esbuild/linux-loong64in the contributed PR because someone registered the package name before I could claim it, and I missed a spot. Hopefully everything is working after this release. I plan to change all platform-specific package names to use the@esbuild/scope at some point to avoid this problem in the future.0.14.52
2 Aug 2022Allow binary data as input to the JS
transformandbuildAPIsPreviously esbuild's
transformandbuildAPIs could only take a string. However, some people want to use esbuild to convert binary data to base64 text. This is problematic because JavaScript strings represent UTF-16 text and esbuild internally operates on arrays of bytes, so all strings coming from JavaScript undergo UTF-16 to UTF-8 conversion before use. This meant that using esbuild in this way was doing base64 encoding of the UTF-8 encoding of the text, which was undesired.With this release, esbuild now accepts
Uint8Arrayin addition to string as an input format for thetransformandbuildAPIs. Now you can use esbuild to convert binary data to base64 text:// Original code import esbuild from 'esbuild' console.log([ (await esbuild.transform('\xFF', { loader: 'base64' })).code, (await esbuild.build({ stdin: { contents: '\xFF', loader: 'base64' }, write: false })).outputFiles[0].text, ]) console.log([ (await esbuild.transform(new Uint8Array([0xFF]), { loader: 'base64' })).code, (await esbuild.build({ stdin: { contents: new Uint8Array([0xFF]), loader: 'base64' }, write: false })).outputFiles[0].text, ]) // Old output [ 'module.exports = "w78=";\n', 'module.exports = "w78=";\n' ] /* ERROR: The input to "transform" must be a string */ // New output [ 'module.exports = "w78=";\n', 'module.exports = "w78=";\n' ] [ 'module.exports = "/w==";\n', 'module.exports = "/w==";\n' ]Update the getter for
textin build resultsOutput files in build results returned from esbuild's JavaScript API have both a
contentsand atextproperty to return the contents of the output file. Thecontentsproperty is a binary UTF-8 Uint8Array and thetextproperty is a JavaScript UTF-16 string. Thetextproperty is a getter that does the UTF-8 to UTF-16 conversion only if it's needed for better performance.Previously if you mutate the build results object, you had to overwrite both
contentsandtextsince the value returned from thetextgetter is the original text returned by esbuild. Some people find this confusing so with this release, the getter fortexthas been updated to do the UTF-8 to UTF-16 conversion on the current value of thecontentsproperty instead of the original value.
- 0.0.x
0.0.1
2 Aug 2022
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.