Update dependency esbuild to v0.12.15 #610
No reviewers
Labels
No Label
area/internal-code
changes requested
confirmed
dependencies
duplicate
good first issue
help wanted
hosting
invalid
kind/bug
kind/feature
question
wontfix
No Milestone
No project
No Assignees
1 Participants
Due Date
No due date set.
Dependencies
No dependencies set.
Reference: vikunja/frontend#610
Loading…
Reference in New Issue
No description provided.
Delete Branch "renovate/esbuild-0.x"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
This PR contains the following updates:
0.8.51
->0.12.15
Release Notes
evanw/esbuild
v0.12.15
Compare Source
Fix a bug with
var()
in CSS color lowering (#1421)This release fixes a bug with esbuild's handling of the
rgb
andhsl
color functions when they containvar()
. Eachvar()
token sequence can be substituted for any number of tokens including zero or more than one, but previously esbuild's output was only correct if eachvar()
inside ofrgb
orhsl
contained exactly one token. With this release, esbuild will now not attempt to transform newer CSS color syntax to older CSS color syntax if it containsvar()
:The bug with the old output above happened because esbuild considered the arguments to
hsl
as matching the patternhsl(h s l)
which is the new space-separated form allowed by CSS Color Module Level 4. Then esbuild tried to convert this to the formhsl(h, s, l)
which is more widely supported by older browsers. But this substitution doesn't work in the presence ofvar()
, so it has now been disabled in that case.v0.12.14
Compare Source
Fix the
file
loader with custom namespaces (#1404)This fixes a regression from version 0.12.12 where using a plugin to load an input file with the
file
loader in a custom namespace caused esbuild to write the contents of that input file to the path associated with that namespace instead of to a path inside of the output directory. With this release, thefile
loader should now always copy the file somewhere inside of the output directory.v0.12.13
Compare Source
Fix using JS synchronous API from from non-main threads (#1406)
This release fixes an issue with the new implementation of the synchronous JS API calls (
transformSync
andbuildSync
) when they are used from a thread other than the main thread. The problem happened because esbuild's new implementation uses node'sworker_threads
library internally and non-main threads were incorrectly assumed to be esbuild's internal thread instead of potentially another unrelated thread. Now esbuild's synchronous JS APIs should work correctly when called from non-main threads.v0.12.12
Compare Source
Fix
file
loader import paths when subdirectories are present (#1044)Using the
file
loader for a file type causes importing affected files to copy the file into the output directory and to embed the path to the copied file into the code that imported it. However, esbuild previously always embedded the path relative to the output directory itself. This is problematic when the importing code is generated within a subdirectory inside the output directory, since then the relative path is wrong. For example:This is output from the previous version of esbuild. The above asset reference in
out/example/entry.css
is wrong. The path should start with../
because the two files are in different directories.With this release, the asset references present in output files will now be the full relative path from the output file to the asset, so imports should now work correctly when the entry point is in a subdirectory within the output directory. This change affects asset reference paths in both CSS and JS output files.
Note that if you want asset reference paths to be independent of the subdirectory in which they reside, you can use the
--public-path
setting to provide the common path that all asset reference paths should be constructed relative to. Specifically--public-path=.
should bring back the old problematic behavior in case you need it.Add support for
[dir]
in--asset-names
(#1196)You can now use path templates such as
--asset-names=[dir]/[name]-[hash]
to copy the input directory structure of your asset files (i.e. input files loaded with thefile
loader) to the output directory. Here's an example:v0.12.11
Compare Source
Enable faster synchronous transforms with the JS API by default (#1000)
Currently the synchronous JavaScript API calls
transformSync
andbuildSync
spawn a new child process on every call. This is due to limitations with node'schild_process
API. Doing this meanstransformSync
andbuildSync
are much slower thantransform
andbuild
, which share the same child process across calls.This release improves the performance of
transformSync
andbuildSync
by up to 20x. It enables a hack where node'sworker_threads
API and atomics are used to block the main thread while asynchronous communication with a single long-lived child process happens in a worker. Previously this was only enabled when theESBUILD_WORKER_THREADS
environment variable was set to1
. But this experiment has been available for a while (since version 0.9.6) without any reported issues. Now this hack will be enabled by default. It can be disabled by settingESBUILD_WORKER_THREADS
to0
before running node.Fix nested output directories with WebAssembly on Windows (#1399)
Many functions in Go's standard library have a bug where they do not work on Windows when using Go with WebAssembly. This is a long-standing bug and is a fault with the design of the standard library, so it's unlikely to be fixed. Basically Go's standard library is designed to bake "Windows or not" decision into the compiled executable, but WebAssembly is platform-independent which makes "Windows or not" is a run-time decision instead of a compile-time decision. Oops.
I have been working around this by trying to avoid using path-related functions in the Go standard library and doing all path manipulation by myself instead. This involved completely replacing Go's
path/filepath
library. However, I missed theos.MkdirAll
function which is also does path manipulation but is outside of thepath/filepath
package. This meant that nested output directories failed to be created on Windows, which caused a build error. This problem only affected theesbuild-wasm
package.This release manually reimplements nested output directory creation to work around this bug in the Go standard library. So nested output directories should now work on Windows with the
esbuild-wasm
package.v0.12.10
Compare Source
Add a target for ES2021
It's now possible to use
--target=es2021
to target the newly-released JavaScript version ES2021. The only difference between that and--target=es2020
is that logical assignment operators such asa ||= b
are not converted to regular assignment operators such asa || (a = b)
.Minify the syntax
Infinity
to1 / 0
(#1385)The
--minify-syntax
flag (automatically enabled by--minify
) will now minify the expressionInfinity
to1 / 0
, which uses fewer bytes:This change was contributed by @Gusted.
Minify syntax in the CSS
transform
property (#1390)This release includes various size reductions for CSS transform matrix syntax when minification is enabled:
The
translate3d
totranslateZ
conversion was contributed by @steambap.Support for the case-sensitive flag in CSS attribute selectors (#1397)
You can now use the case-sensitive CSS attribute selector flag
s
such as in[type="a" s] { list-style: lower-alpha; }
. Previously doing this caused a warning about unrecognized syntax.v0.12.9
Compare Source
Allow
this
with--define
(#1361)You can now override the default value of top-level
this
with the--define
feature. Top-levelthis
defaults to beingundefined
in ECMAScript modules andexports
in CommonJS modules. For example:Note that overriding what top-level
this
is will likely break code that uses it correctly. So this new feature is only useful in certain cases.Fix CSS minification issue with
!important
and duplicate declarations (#1372)Previously CSS with duplicate declarations for the same property where the first one was marked with
!important
was sometimes minified incorrectly. For example:This was incorrectly minified as
.selector{padding:0}
. The bug affected three properties:padding
,margin
, andborder-radius
. With this release, this code will now be minified as.selector{padding:10px!important;padding:0}
instead which means there is no longer a difference between minified and non-minified code in this case.v0.12.8
Compare Source
Plugins can now specify
sideEffects: false
(#1009)The default path resolution behavior in esbuild determines if a given file can be considered side-effect free (in the Webpack-specific sense) by reading the contents of the nearest enclosing
package.json
file and looking for"sideEffects": false
. However, up until now this was impossible to achieve in an esbuild plugin because there was no way of returning this metadata back to esbuild.With this release, esbuild plugins can now return
sideEffects: false
to mark a file as having no side effects. Here's an example:This plugin creates a virtual module that can be generated by importing the string
env
. However, since the plugin returnssideEffects: false
, the generated virtual module will not be included in the bundle if all of the imported values from the moduleenv
end up being unused.This feature was contributed by @chriscasola.
Remove a warning about unsupported source map comments (#1358)
This removes a warning that indicated when a source map comment couldn't be supported. Specifically, this happens when you enable source map generation and esbuild encounters a file with a source map comment pointing to an external file but doesn't have enough information to know where to look for that external file (basically when the source file doesn't have an associated directory to use for path resolution). In this case esbuild can't respect the input source map because it cannot be located. The warning was annoying so it has been removed. Source maps still won't work, however.
v0.12.7
Compare Source
Quote object properties that are modern Unicode identifiers (#1349)
In ES6 and above, an identifier is a character sequence starting with a character in the
ID_Start
Unicode category and followed by zero or more characters in theID_Continue
Unicode category, and these categories must be drawn from Unicode version 5.1 or above.But in ES5, an identifier is a character sequence starting with a character in one of the
Lu, Ll, Lt, Lm, Lo, Nl
Unicode categories and followed by zero or more characters in theLu, Ll, Lt, Lm, Lo, Nl, Mn, Mc, Nd, Pc
Unicode categories, and these categories must be drawn from Unicode version 3.0 or above.Previously esbuild always used the ES6+ identifier validation test when deciding whether to use an identifier or a quoted string to encode an object property but with this release, it will use the ES5 validation test instead:
This approach should ensure maximum compatibility with all JavaScript environments that support ES5 and above. Note that this means minified files containing Unicode properties may be slightly larger than before.
Ignore
tsconfig.json
files insidenode_modules
(#1355)Package authors often publish their
tsconfig.json
files to npm because of npm's default-include publishing model and because these authors probably don't know about.npmignore
files. People trying to use these packages with esbuild have historically complained that esbuild is respectingtsconfig.json
in these cases. The assumption is that the package author published these files by accident.With this release, esbuild will no longer respect
tsconfig.json
files when the source file is inside anode_modules
folder. Note thattsconfig.json
files insidenode_modules
are still parsed, and extendingtsconfig.json
files from inside a package is still supported.Fix missing
--metafile
when using--watch
(#1357)Due to an oversight, the
--metafile
setting didn't work when--watch
was also specified. This only affected the command-line interface. With this release, the--metafile
setting should now work in this case.Add a hidden
__esModule
property to modules in ESM format (#1338)Module namespace objects from ESM files will now have a hidden
__esModule
property. This improves compatibility with code that has been converted from ESM syntax to CommonJS by Babel or TypeScript. For example:If the object returned by
require("y")
doesn't have an__esModule
property, theny_1
will be the object{ "default": require("y") }
. If the file"y"
is in ESM format and has a default export of, say, the valuenull
, that meansy_1
will now be{ "default": { "default": null } }
and you will need to usey_1.default.default
to access the default value. Adding an automatically-generated__esModule
property when converting files in ESM format to CommonJS is required to make this code work correctly (i.e. for the value to be accessible via justy_1.default
instead).With this release, code in ESM format will now have an automatically-generated
__esModule
property to satisfy this convention. The property is non-enumerable so it shouldn't show up when iterating over the properties of the object. As a result, the export name__esModule
is now reserved for use with esbuild. It's now an error to create an export with the name__esModule
.This fix was contributed by @lbwa.
v0.12.6
Compare Source
Improve template literal lowering transformation conformance (#1327)
This release contains the following improvements to template literal lowering for environments that don't support tagged template literals natively (such as
--target=es5
):For tagged template literals, the arrays of strings that are passed to the tag function are now frozen and immutable. They are also now cached so they should now compare identical between multiple template evaluations:
For tagged template literals, the generated code size is now smaller in the common case where there are no escape sequences, since in that case there is no distinction between "raw" and "cooked" values:
For non-tagged template literals, the generated code now uses chains of
.concat()
calls instead of string addition:The old output was incorrect for several reasons including that
toString
must be called instead ofvalueOf
for objects and that passing aSymbol
instance should throw instead of converting the symbol to a string. Using.concat()
instead of string addition fixes both of those correctness issues. And you can't use a single.concat()
call because side effects must happen inline instead of at the end.Only respect
target
intsconfig.json
when esbuild's target is not configured (#1332)In version 0.12.4, esbuild began respecting the
target
setting intsconfig.json
. However, sometimestsconfig.json
contains target values that should not be used. With this release, esbuild will now only use thetarget
value intsconfig.json
as the language level when esbuild'starget
setting is not configured. If esbuild'starget
setting is configured then thetarget
value intsconfig.json
is now ignored.Fix the order of CSS imported from JS (#1342)
Importing CSS from JS when bundling causes esbuild to generate a sibling CSS output file next to the resulting JS output file containing the bundled CSS. The order of the imported CSS files in the output was accidentally the inverse order of the order in which the JS files were evaluated. Instead the order of the imported CSS files should match the order in which the JS files were evaluated. This fix was contributed by @dmitrage.
Fix an edge case with transforming
export default class
(#1346)Statements of the form
export default class x {}
were incorrectly transformed toclass x {} var y = x; export {y as default}
instead ofclass x {} export {x as default}
. Transforming these statements like this is incorrect in the rare case that the class is later reassigned by name within the same file such asexport default class x {} x = null
. Here the imported value should benull
but was incorrectly the class object instead. This is unlikely to matter in real-world code but it has still been fixed to improve correctness.v0.12.5
Compare Source
Add support for lowering tagged template literals to ES5 (#297)
This release adds support for lowering tagged template literals such as
String.raw`\unicode`
to target environments that don't support them such as--target=es5
(non-tagged template literals were already supported). Each literal turns into a function call to a helper function:Change class field behavior to match TypeScript 4.3
TypeScript 4.3 includes a subtle breaking change that wasn't mentioned in the TypeScript 4.3 blog post: class fields will now be compiled with different semantics if
"target": "ESNext"
is present intsconfig.json
. Specifically in this caseuseDefineForClassFields
will default totrue
when not specified instead offalse
. This means class field behavior in TypeScript code will now match JavaScript instead of doing something else:In TypeScript 4.2 and below, the TypeScript compiler would generate code that prints
set 123
whentsconfig.json
contains"target": "ESNext"
but in TypeScript 4.3, the TypeScript compiler will now generate code that doesn't print anything. This is the difference between "assign" semantics and "define" semantics. With this release, esbuild has been changed to follow the TypeScript 4.3 behavior.Avoid generating the character sequence
</script>
(#1322)If the output of esbuild is inlined into a
<script>...</script>
tag inside an HTML file, the character sequence</script>
inside the JavaScript code will accidentally cause the script tag to be terminated early. There are at least four such cases where this can happen:With this release, esbuild will now handle all of these cases and avoid generating the problematic character sequence:
Change the triple-slash reference comment for Deno (#1325)
The comment in esbuild's JavaScript API implementation for Deno that references the TypeScript type declarations has been changed from
/// <reference path="./mod.d.ts" />
to/// <reference types="./mod.d.ts" />
. This comment was copied from Deno's documentation but apparently Deno's documentation was incorrect. The comment in esbuild's Deno bundle has been changed to reflect Deno's latest documentation.v0.12.4
Compare Source
Reorder name preservation before TypeScript decorator evaluation (#1316)
The
--keep-names
option ensures the.name
property on functions and classes remains the same after bundling. However, this was being enforced after TypeScript decorator evaluation which meant that the decorator could observe the incorrect name. This has been fixed and now.name
preservation happens before decorator evaluation instead.Potential fix for a determinism issue (#1304)
This release contains a potential fix for an unverified issue with non-determinism in esbuild. The regression was apparently introduced in 0.11.13 and may be related to parallelism that was introduced around the point where dynamic
import()
expressions are added to the list of entry points. Hopefully this fix should resolve the regression.Respect
target
intsconfig.json
(#277)Each JavaScript file that esbuild bundles will now be transformed according to the
target
language level from the nearest enclosingtsconfig.json
file. This is in addition to esbuild's own--target
setting; the two settings are merged by transforming any JavaScript language feature that is unsupported in either esbuild's configured--target
value or thetarget
property in thetsconfig.json
file.v0.12.3
Compare Source
Ensure JSX element names start with a capital letter (#1309)
The JSX specification only describes the syntax and says nothing about how to interpret it. But React (and therefore esbuild) treats JSX tags that start with a lower-case ASCII character as strings instead of identifiers. That way the tag
<i/>
always refers to the italic HTML elementi
and never to a local variable namedi
.However, esbuild may rename identifiers for any number of reasons such as when minification is enabled. Previously esbuild could sometimes rename identifiers used as tag names such that they start with a lower-case ASCII character. This is problematic when JSX syntax preservation is enabled since subsequent JSX processing would then turn these identifier references into strings.
With this release, esbuild will now make sure identifiers used in tag names start with an upper-case ASCII character instead when JSX syntax preservation is enabled. This should avoid problems when using esbuild with JSX transformation tools.
Fix a single hyphen being treated as a CSS name (#1310)
CSS identifiers are allowed to start with a
-
character if (approximately) the following character is a letter, an escape sequence, a non-ASCII character, the character_
, or another-
character. This check is used in certain places when printing CSS to determine whether a token is a valid identifier and can be printed as such or whether it's an invalid identifier and needs to be quoted as a string. One such place is in attribute selectors such as[a*=b]
.However, esbuild had a bug where a single
-
character was incorrectly treated as a valid identifier in this case. This is because the end of string became U+FFFD (the Unicode replacement character) which is a non-ASCII character and a valid name-start code point. With this release a single-
character is no longer treated as a valid identifier. This fix was contributed by @lbwa.v0.12.2
Compare Source
Fix various code generation and minification issues (#1305)
This release fixes the following issues, which were all identified by running esbuild against the latest UglifyJS test suite:
The
in
operator is now surrounded parentheses inside arrow function expression bodies insidefor
loop initializers:Without this, the
in
operator would cause the for loop to be considered a for-in loop instead.The statement
return undefined;
is no longer minified toreturn;
inside async generator functions:Using
return undefined;
inside an async generator function has the same effect asreturn await undefined;
which schedules a task in the event loop and runs code in a different order than justreturn;
, which doesn't hide an implicitawait
expression.Property access expressions are no longer inlined in template tag position:
The expression
a.b`c`
is different than the expression(0, a.b)`c`
. The first calls the functiona.b
witha
as the value forthis
but the second calls the functiona.b
with the default value forthis
(the global object in non-strict mode orundefined
in strict mode).Verbatim
__proto__
properties inside object spread are no longer inlined when minifying:A verbatim (i.e. non-computed non-method) property called
__proto__
inside an object literal actually sets the prototype of the surrounding object literal. It does not add an "own property" called__proto__
to that object literal, so inlining it into the parent object literal would be incorrect. The presence of a__proto__
property now stops esbuild from applying the object spread inlining optimization when minifying.The value of
this
has now been fixed for lowered private class members that are used as template tags:The value of
this
here should be an instance of the class because the template tag is a property access expression. However, it was previously the default value (the global object in non-strict mode orundefined
in strict mode) instead due to the private member transformation, which is incorrect.Invalid escape sequences are now allowed in tagged template literals
This implements the template literal revision feature: https://github.com/tc39/proposal-template-literal-revision. It allows you to process tagged template literals using custom semantics that don't follow JavaScript escape sequence rules without causing a syntax error:
v0.12.1
Compare Source
Fix a bug with
var()
in CSS color lowering (#1421)This release fixes a bug with esbuild's handling of the
rgb
andhsl
color functions when they containvar()
. Eachvar()
token sequence can be substituted for any number of tokens including zero or more than one, but previously esbuild's output was only correct if eachvar()
inside ofrgb
orhsl
contained exactly one token. With this release, esbuild will now not attempt to transform newer CSS color syntax to older CSS color syntax if it containsvar()
:The bug with the old output above happened because esbuild considered the arguments to
hsl
as matching the patternhsl(h s l)
which is the new space-separated form allowed by CSS Color Module Level 4. Then esbuild tried to convert this to the formhsl(h, s, l)
which is more widely supported by older browsers. But this substitution doesn't work in the presence ofvar()
, so it has now been disabled in that case.v0.12.0
Compare Source
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
esbuild
in yourpackage.json
file or be using a version range syntax that only accepts patch upgrades such as~0.11.0
. See the documentation about semver for more information.The breaking changes in this release relate to CSS import order and also build scenarios where both the
inject
anddefine
API options are used (see below for details). These breaking changes are as follows:Fix bundled CSS import order (#465)
JS and CSS use different import ordering algorithms. In JS, importing a file that has already been imported is a no-op but in CSS, importing a file that has already been imported re-imports the file. A simple way to imagine this is to view each
@import
rule in CSS as being replaced by the contents of that file similar to#include
in C/C++. However, this is incorrect in the case of@import
cycles because it would cause infinite expansion. A more accurate way to imagine this is that in CSS, a file is evaluated at the last@import
location while in JS, a file is evaluated at the firstimport
location.Previously esbuild followed JS import order rules for CSS but now esbuild will follow CSS import order rules. This is a breaking change because it means your CSS may behave differently when bundled. Note that CSS import order rules are somewhat unintuitive because evaluation order matters. In CSS, using
@import
multiple times can end up unintentionally erasing overriding styles. For example, consider the following files:Because of how CSS import order works,
entry.css
will now be bundled like this:This means the body will unintuitively be all black! The file
reset.css
is evaluated at the location of the last@import
instead of the first@import
. The fix for this case is to remove the nested imports ofreset.css
and to importreset.css
exactly once at the top ofentry.css
.Note that while the evaluation order of external CSS imports is preserved with respect to other external CSS imports, the evaluation order of external CSS imports is not preserved with respect to other internal CSS imports. All external CSS imports are "hoisted" to the top of the bundle. The alternative would be to generate many smaller chunks which is usually undesirable. So in this case esbuild's CSS bundling behavior will not match the browser.
Fix bundled CSS when using JS code splitting (#608)
Previously esbuild generated incorrect CSS output when JS code splitting was enabled and the JS code being bundled imported CSS files. CSS code that was reachable via multiple JS entry points was split off into a shared CSS chunk, but that chunk was not actually imported anywhere so the shared CSS was missing. This happened because both CSS and JS code splitting were experimental features that are still in progress and weren't tested together.
Now esbuild's CSS output should contain all reachable CSS code when JS code splitting is enabled. Note that this does not mean code splitting works for CSS files. Each CSS output file simply contains the transitive set of all CSS reachable from the JS entry point including through dynamic
import()
andrequire()
expressions. Specifically, the bundler constructs a virtual CSS file for each JS entry point consisting only of@import
rules for each CSS file imported into a JS file. These@import
rules are constructed in JS source order, but then the bundler uses CSS import order from that point forward to bundle this virtual CSS file into the final CSS output file.This model makes the most sense when CSS files are imported into JS files via JS
import
statements. Importing CSS viaimport()
andrequire()
(either directly or transitively through multiple intermediate JS files) should still "work" in the sense that all reachable CSS should be included in the output, but in this case esbuild will pick an arbitrary (but consistent) import order. The import order may not match the order that the JS files are evaluated in because JS evaluation order of dynamic imports is only determined at run-time while CSS bundling happens at compile-time.It's possible to implement code splitting for CSS such that CSS code used between multiple entry points is shared. However, CSS lacks a mechanism for "lazily" importing code (i.e. disconnecting the import location with the evaluation location) so CSS code splitting could potentially need to generate a huge number of very small chunks to preserve import order. It's unclear if this would end up being a net win or not as far as browser download time. So sharing-based code splitting is currently not supported for CSS.
It's theoretically possible to implement code splitting for CSS such that CSS from a dynamically-imported JS file (e.g. via
import()
) is placed into a separate chunk. However, due to how@import
order works this would in theory end up re-evaluating all shared dependencies which could overwrite overloaded styles and unintentionally change the way the page is rendered. For example, constructing a single-page app architecture such that each page is JS-driven and can transition to other JS-driven pages viaimport()
could end up with pages that look different depending on what order you visit them in. This is clearly undesirable. The simple way to address this is to just not support dynamic-import code splitting for CSS either.Change "define" to have higher priority than "inject" (#660)
The "define" and "inject" features are both ways of replacing certain expressions in your source code with other things expressions. Previously esbuild's behavior ran "inject" before "define", which could lead to some undesirable behavior. For example (from the
react
npm package):If you use "define" to replace
process.env.NODE_ENV
with"production"
and "inject" to replaceprocess
with a shim that emulates node's process API, thenprocess
was previously replaced first and thenprocess.env.NODE_ENV
wasn't matched becauseprocess
referred to the injected shim. This wasn't ideal because it means esbuild didn't detect the branch condition as a constant (since it doesn't know how the shim behaves at run-time) and bundled both the development and production versions of the package.With this release, esbuild will now run "define" before "inject". In the above example this means that
process.env.NODE_ENV
will now be replaced with"production"
, the injected shim will not be included, and only the production version of the package will be bundled. This feature was contributed by @rtsao.In addition to the breaking changes above, the following features are also included in this release:
Add support for the
NO_COLOR
environment variableThe CLI will now omit color if the
NO_COLOR
environment variable is present, which is an existing convention that is followed by some other software. See https://no-color.org/ for more information.v0.11.23
Compare Source
Add a shim function for unbundled uses of
require
(#1202)Modules in CommonJS format automatically get three variables injected into their scope:
module
,exports
, andrequire
. These allow the code to import other modules and to export things from itself. The bundler automatically rewrites uses ofmodule
andexports
to refer to the module's exports and certain uses ofrequire
to a helper function that loads the imported module.Not all uses of
require
can be converted though, and un-converted uses ofrequire
will end up in the output. This is problematic becauserequire
is only present at run-time if the output is run as a CommonJS module. Otherwiserequire
is undefined, which means esbuild's behavior is inconsistent between compile-time and run-time. Themodule
andexports
variables are objects at compile-time and run-time butrequire
is a function at compile-time and undefined at run-time. This causes code that checks fortypeof require
to have inconsistent behavior:In the above example, ideally
CommonJS detected
would always be printed since the code is being bundled with a CommonJS-aware bundler. To fix this, esbuild will now substitute references torequire
with a stub__require
function when bundling if the output format is something other than CommonJS. This should ensure thatrequire
is now consistent between compile-time and run-time. When bundled, code that uses unbundled references torequire
will now look something like this:Fix incorrect caching of internal helper function library (#1292)
This release fixes a bug where running esbuild multiple times with different configurations sometimes resulted in code that would crash at run-time. The bug was introduced in version 0.11.19 and happened because esbuild's internal helper function library is parsed once and cached per configuration, but the new profiler name option was accidentally not included in the cache key. This option is now included in the cache key so this bug should now be fixed.
Minor performance improvements
This release contains some small performance improvements to offset an earlier minor performance regression due to the addition of certain features such as hashing for entry point files. The benchmark times on the esbuild website should now be accurate again (versions of esbuild after the regression but before this release were slightly slower than the benchmark).
v0.11.22
Compare Source
Add support for the "import assertions" proposal
This is new JavaScript syntax that was shipped in Chrome 91. It looks like this:
On the web, the content type for a given URL is determined by the
Content-Type
HTTP header instead of the file extension. So adding support for importing non-JS content types such as JSON to the web could cause security issues since importing JSON from an untrusted source is safe while importing JS from an untrusted source is not.Import assertions are a new feature to address this security concern and unblock non-JS content types on the web. They cause the import to fail if the
Content-Type
header doesn't match the expected value. This prevents security issues for data-oriented content types such as JSON since it guarantees that data-oriented content will never accidentally be evaluated as code instead of data. More information about the proposal is available here: https://github.com/tc39/proposal-import-assertions.This release includes support for parsing and printing import assertions. They will be printed if the configured target environment supports them (currently only in
esnext
andchrome91
), otherwise they will be omitted. If they aren't supported in the configured target environment and it's not possible to omit them, which is the case for certain dynamicimport()
expressions, then using them is a syntax error. Import assertions are otherwise unused by the bundler.Forbid the token sequence
for ( async of
when not followed by=>
This follows a recently-fixed ambiguity in the JavaScript specification, which you can read about here: https://github.com/tc39/ecma262/pull/2256. Prior to this change in the specification, it was ambiguous whether this token sequence should be parsed as
for ( async of =>
orfor ( async of ;
. V8 and esbuild expected=>
afterfor ( async of
while SpiderMonkey and JavaScriptCore did something else.The ambiguity has been removed and the token sequence
for ( async of
is now forbidden by the specification when not followed by=>
, so esbuild now forbids this as well. Note that the token sequencefor await (async of
is still allowed even when not followed by=>
. Code such asfor ((async) of []) ;
is still allowed and will now be printed with parentheses to avoid the grammar ambiguity.Restrict
super
property access to inside of methodsYou can now only use
super.x
andsuper[x]
expressions inside of methods. Previously these expressions were incorrectly allowed everywhere. This means esbuild now follows the JavaScript language specification more closely.v0.11.21
Compare Source
TypeScript
override
for parameter properties (#1262)You can now use the
override
keyword instead of or in addition to thepublic
,private
,protected
, andreadonly
keywords for declaring a TypeScript parameter property:This feature was recently added to the TypeScript compiler and will presumably be in an upcoming version of the TypeScript language. Support for this feature in esbuild was contributed by @g-plane.
Fix duplicate export errors due to TypeScript import-equals statements (#1283)
TypeScript has a special import-equals statement that is not part of JavaScript. It looks like this:
Each import can be a type or a value and type-only imports need to be eliminated when converting this code to JavaScript, since types do not exist at run-time. The TypeScript compiler generates the following JavaScript code for this example:
The
x
,y
, andz
import statements are eliminated in esbuild by iterating over imports and exports multiple times and continuing to remove unused TypeScript import-equals statements until none are left. The first pass removesz
and marksy
as unused, the second pass removesy
and marksx
as unused, and the third pass removesx
.However, this had the side effect of making esbuild incorrectly think that a single export is exported twice (because it's processed more than once). This release fixes that bug by only iterating multiple times over imports, not exports. There should no longer be duplicate export errors for this case.
Add support for type-only TypeScript import-equals statements (#1285)
This adds support for the following new TypeScript syntax that was added in version 4.2:
Unlike
import React = require('react')
, this statement is a type declaration instead of a value declaration and should be omitted from the generated code. See microsoft/TypeScript#41573 for details. This feature was contributed by @g-plane.v0.11.20
Compare Source
Omit warning about duplicate JSON keys from inside
node_modules
(#1254)This release no longer warns about duplicate keys inside
package.json
files insidenode_modules
. There are packages like this that are published to npm, and this warning is unactionable. Now esbuild will only issue this warning outside ofnode_modules
directories.Add CSS minification for
box-shadow
valuesThe CSS
box-shadow
property is now minified when--mangle-syntax
is enabled. This includes trimming length values and minifying color representations.Fix object spread transform for non-spread getters (#1259)
When transforming an object literal containing object spread (the
...
syntax), properties inside the spread should be evaluated but properties outside the spread should not be evaluated. Previously esbuild's object spread transform incorrectly evaluated properties in both cases. Consider this example:This should print out
1 2 3
because the non-spread getter should not be evaluated. Instead, esbuild was incorrectly transforming this into code that printed1 3 2
. This issue should now be fixed with this release.Prevent private class members from being added more than once
This fixes a corner case with the private class member implementation. Constructors in JavaScript can return an object other than
this
, so private class members can actually be added to objects other thanthis
. This can be abused to attach completely private metadata to other objects:This already worked in code transformed by esbuild for older browsers. However, calling
new Derived(foo)
multiple times in the above code was incorrectly allowed. This should not be allowed because it would mean that the private field#y
would be re-declared. This is no longer allowed starting from this release.v0.11.19
Compare Source
Allow esbuild to be restarted in Deno (#1238)
The esbuild API for Deno has an extra function called
stop()
that doesn't exist in esbuild's API for node. This is because Deno doesn't provide a way to stop esbuild automatically, so callingstop()
is required to allow Deno to exit. However, once stopped the esbuild API could not be restarted.With this release, you can now continue to use esbuild after calling
stop()
. This will restart esbuild's API and means that you will need to callstop()
again for Deno to be able to exit. This feature was contributed by @lucacasonato.Fix code splitting edge case (#1252)
This release fixes an edge case where bundling with code splitting enabled generated incorrect code if multiple ESM entry points re-exported the same re-exported symbol from a CommonJS file. In this case the cross-chunk symbol dependency should be the variable that holds the return value from the
require()
call instead of the original ESM namedimport
clause item. When this bug occurred, the generated ESM code contained an export and import for a symbol that didn't exist, which caused a module initialization error. This case should now work correctly.Fix code generation with
declare
class fields (#1242)This fixes a bug with TypeScript code that uses
declare
on a class field and yourtsconfig.json
file has"useDefineForClassFields": true
. Fields marked asdeclare
should not be defined in the generated code, but they were incorrectly being declared asundefined
. These fields are now correctly omitted from the generated code.Annotate module wrapper functions in debug builds (#1236)
Sometimes esbuild needs to wrap certain modules in a function when bundling. This is done both for lazy evaluation and for CommonJS modules that use a top-level
return
statement. Previously these functions were all anonymous, so stack traces for errors thrown during initialization looked like this:This release adds names to these anonymous functions when minification is disabled. The above stack trace now looks like this:
This is similar to Webpack's development-mode behavior:
These descriptive function names will additionally be available when using a profiler such as the one included in the "Performance" tab in Chrome Developer Tools. Previously all functions were named
(anonymous)
which made it difficult to investigate performance issues during bundle initialization.Add CSS minification for more cases
The following CSS minification cases are now supported:
The CSS
margin
property family is now minified including combining themargin-top
,margin-right
,margin-bottom
, andmargin-left
properties into a singlemargin
property.The CSS
padding
property family is now minified including combining thepadding-top
,padding-right
,padding-bottom
, andpadding-left
properties into a singlepadding
property.The CSS
border-radius
property family is now minified including combining theborder-top-left-radius
,border-top-right-radius
,border-bottom-right-radius
, andborder-bottom-left-radius
properties into a singleborder-radius
property.The four special pseudo-elements
::before
,::after
,::first-line
, and::first-letter
are allowed to be parsed with one:
for legacy reasons, so the::
is now converted to:
for these pseudo-elements.Duplicate CSS rules are now deduplicated. Only the last rule is kept, since that's the only one that has any effect. This applies for both top-level rules and nested rules.
Preserve quotes around properties when minification is disabled (#1251)
Previously the parser did not distinguish between unquoted and quoted properties, since there is no semantic difference. However, some tools such as Google Closure Compiler with "advanced mode" enabled attach their own semantic meaning to quoted properties, and processing code intended for Google Closure Compiler's advanced mode with esbuild was changing those semantics. The distinction between unquoted and quoted properties is now made in the following cases:
The parser will now preserve the quoted properties in these cases as long as
--minify-syntax
is not enabled. This does not mean that esbuild is officially supporting Google Closure Compiler's advanced mode, just that quoted properties are now preserved when the AST is pretty-printed. Google Closure Compiler's advanced mode accepts a language that shares syntax with JavaScript but that deviates from JavaScript semantics and there could potentially be other situations where preprocessing code intended for Google Closure Compiler's advanced mode with esbuild first causes it to break. If that happens, that is not a bug with esbuild.v0.11.18
Compare Source
Add support for OpenBSD on x86-64 (#1235)
Someone has asked for OpenBSD to be supported on x86-64. It should now be supported starting with this release.
Fix an incorrect warning about top-level
this
This was introduced in the previous release, and happens when using a top-level
async
arrow function with a compilation target that doesn't support it. The reason is that doing this generates a shim that preserves the value ofthis
. However, this warning message is confusing because there is not necessarily anythis
present in the source code. The warning message has been removed in this case. Now it should only show up ifthis
is actually present in the source code.v0.11.17
Compare Source
Fix building with a large
stdin
string with Deno (#1219)When I did the initial port of esbuild's node-based API to Deno, I didn't realize that Deno's
write(bytes)
function doesn't actually write the provided bytes. Instead it may only write some of those bytes and needs to be repeatedly called again until it writes everything. This meant that calling esbuild's Deno-based API could hang if the API request was large enough, which can happen in practice when using thestdin
string feature. Thewrite
API is now called in a loop so these hangs in Deno should now be fixed.Add a warning about replacing
this
withundefined
in ESM code (#1225)There is existing JavaScript code that sometimes references top-level
this
as a way to access the global scope. However, top-levelthis
is actually specified to beundefined
inside of ECMAScript module code, which makes referencing top-levelthis
inside ESM code useless. This issue can come up when the existing JavaScript code is adapted for ESM by addingimport
and/orexport
. All top-level references tothis
are replaced withundefined
when bundling to make sure ECMAScript module behavior is emulated correctly regardless of the environment in which the resulting code is run.With this release, esbuild will now warn about this when bundling:
This warning is not unique to esbuild. Rollup also already has a similar warning:
Allow a string literal as a JSX fragment (#1217)
TypeScript's JSX implementation allows you to configure a custom JSX factory and a custom JSX fragment, but requires that they are both valid JavaScript identifier member expression chains. Since esbuild's JSX implementation is based on TypeScript, esbuild has the same requirement. So
React.createElement
is a valid JSX factory value but['React', 'createElement']
is not.However, the Mithril framework has decided to use
"["
as a JSX fragment, which is not a valid JavaScript identifier member expression chain. This meant that using Mithril with esbuild required a workaround. In this release, esbuild now lets you use a string literal as a custom JSX fragment. It should now be easier to use esbuild's JSX implementation with libraries such as Mithril.Fix
metafile
inonEnd
withwatch
mode enabled (#1186)This release fixes a bug where the
metafile
property was incorrectly undefined inside pluginonEnd
callbacks ifwatch
mode is enabled for all builds after the first build. Themetafile
property was accidentally being set after callingonEnd
instead of before.v0.11.16
Compare Source
Fix TypeScript
enum
edge case (#1198)In TypeScript, you can reference the inner closure variable in an
enum
within the inner closure by name:The TypeScript compiler generates the following code for this case:
However, TypeScript also lets you declare an
enum
value with the same name as the inner closure variable. In that case, the value "shadows" the declaration of the inner closure variable:The TypeScript compiler generates the following code for this case:
Previously esbuild reported a duplicate variable declaration error in the second case due to the collision between the
enum
value and the inner closure variable with the same name. With this release, the shadowing is now handled correctly.Parse the
@-moz-document
CSS rule (#1203)This feature has been removed from the web because it's actively harmful, at least according to this discussion. However, there is one exception where
@-moz-document url-prefix() {
is accepted by Firefox to basically be an "if Firefox" conditional rule. Because of this, esbuild now parses the@-moz-document
CSS rule. This should result in better pretty-printing and minification and no more warning when this rule is used.Fix syntax error in TypeScript-specific speculative arrow function parsing (#1211)
Because of grammar ambiguities, expressions that start with a parenthesis are parsed using what's called a "cover grammar" that is a super-position of both a parenthesized expression and an arrow function parameter list. In JavaScript, the cover grammar is unambiguously an arrow function if and only if the following token is a
=>
token.But in TypeScript, the expression is still ambiguously a parenthesized expression or an arrow function if the following token is a
:
since it may be the second half of the?:
operator or a return type annotation. This requires speculatively attempting to reduce the cover grammar to an arrow function parameter list.However, when doing this esbuild eagerly reported an error if a default argument was encountered and the target is
es5
(esbuild doesn't support lowering default arguments to ES5). This is problematic in the following TypeScript code since the parenthesized code turns out to not be an arrow function parameter list:Previously this code incorrectly generated an error since
hover = 2
was incorrectly eagerly validated as a default argument. With this release, the reporting of the default argument error when targetinges5
is now done lazily and only when it's determined that the parenthesized code should actually be interpreted as an arrow function parameter list.Further changes to the behavior of the
browser
field (#1209)This release includes some changes to how the
browser
field inpackage.json
is interpreted to better match how Browserify, Webpack, Parcel, and Rollup behave. The interpretation of this map in esbuild is intended to be applied if and only if it's applied by any one of these bundlers. However, there were some cases where esbuild applied the mapping and none of the other bundlers did, which could lead to build failures. These cases have been added to my growing list ofbrowser
field test cases and esbuild's behavior should now be consistent with other bundlers again.Avoid placing a
super()
call inside areturn
statement (#1208)When minification is enabled, an expression followed by a return statement (e.g.
a(); return b
) is merged into a single statement (e.g.return a(), b
). This is done because it sometimes results in smaller code. If the return statement is the only statement in a block and the block is in a single-statement context, the block can be removed which saves a few characters.Previously esbuild applied this rule to calls to
super()
inside of constructors. Doing that broke esbuild's class lowering transform that tries to insert class field initializers after thesuper()
call. This transform isn't robust and only scans the top-level statement list inside the constructor, so inserting thesuper()
call inside of thereturn
statement means class field initializers were inserted before thesuper()
call instead of after. This could lead to run-time crashes due to initialization failure.With this release, top-level calls to
super()
will no longer be placed insidereturn
statements (in addition to various other kinds of statements such asthrow
, which are now also handled). This should avoid class field initializers being inserted before thesuper()
call.Fix a bug with
onEnd
and watch mode (#1186)This release fixes a bug where
onEnd
plugin callbacks only worked with watch mode when anonRebuild
watch mode callback was present. NowonEnd
callbacks should fire even if there is noonRebuild
callback.Fix an edge case with minified export names and code splitting (#1201)
The names of symbols imported from other chunks were previously not considered for renaming during minified name assignment. This could cause a syntax error due to a name collision when two symbols have the same original name. This was just an oversight and has been fixed, so symbols imported from other chunks should now be renamed when minification is enabled.
Provide a friendly error message when you forget
async
(#1216)If the parser hits a parse error inside a non-asynchronous function or arrow expression and the previous token is
await
, esbuild will now report a friendly error about a missingasync
keyword instead of reporting the parse error. This behavior matches other JavaScript parsers including TypeScript, Babel, and V8.The previous error looked like this:
The error now looks like this:
v0.11.15
Compare Source
Provide options for how to handle legal comments (#919)
A "legal comment" is considered to be any comment that contains
@license
or@preserve
or that starts with//!
or/*!
. These comments are preserved in output files by esbuild since that follows the intent of the original authors of the code.However, some people want to remove the automatically-generated license information before they distribute their code. To facilitate this, esbuild now provides several options for how to handle legal comments (via
--legal-comments=
in the CLI andlegalComments
in the JS API):none
: Do not preserve any legal commentsinline
: Preserve all statement-level legal commentseof
: Move all statement-level legal comments to the end of the filelinked
: Move all statement-level legal comments to a.LEGAL.txt
file and link to them with a commentexternal
: Move all statement-level legal comments to a.LEGAL.txt
file but to not link to themThe default behavior is
eof
when bundling andinline
otherwise.Add
onStart
andonEnd
callbacks to the plugin APIPlugins can now register callbacks to run when a build is started and ended:
One benefit of
onStart
andonEnd
is that they are run for all builds including rebuilds (relevant for incremental mode, watch mode, or serve mode), so they should be a good place to do work related to the build lifecycle.More details:
build.onStart()
You should not use an
onStart
callback for initialization since it can be run multiple times. If you want to initialize something, just put your plugin initialization code directly inside thesetup
function instead.The
onStart
callback can beasync
and can return a promise. However, the build does not wait for the promise to be resolved before starting, so a slowonStart
callback will not necessarily slow down the build. AllonStart
callbacks are also run concurrently, not consecutively. The returned promise is purely for error reporting, and matters when theonStart
callback needs to do an asynchronous operation that may fail. If your plugin needs to wait for an asynchronous task inonStart
to complete before anyonResolve
oronLoad
callbacks are run, you will need to have youronResolve
oronLoad
callbacks block on that task fromonStart
.Note that
onStart
callbacks do not have the ability to mutatebuild.initialOptions
. The initial options can only be modified within thesetup
function and are consumed once thesetup
function returns. All rebuilds use the same initial options so the initial options are never re-consumed, and modifications tobuild.initialOptions
that are done withinonStart
are ignored.build.onEnd()
All
onEnd
callbacks are run in serial and each callback is given access to the final build result. It can modify the build result before returning and can delay the end of the build by returning a promise. If you want to be able to inspect the build graph, you should setbuild.initialOptions.metafile = true
and the build graph will be returned as themetafile
property on the build result object.v0.11.14
Compare Source
Implement arbitrary module namespace identifiers
This introduces new JavaScript syntax:
The proposal for this feature appears to not be going through the regular TC39 process. It is being done as a subtle direct pull request instead. It seems appropriate for esbuild to support this feature since it has been implemented in V8 and has now shipped in Chrome 90 and node 16.
According to the proposal, this feature is intended to improve interop with non-JavaScript languages which use exports that aren't valid JavaScript identifiers such as
Foo::~Foo
. In particular, WebAssembly allows any valid UTF-8 string as to be used as an export alias.This feature was actually already partially possible in previous versions of JavaScript via the computed property syntax:
However, doing this is very un-ergonomic and exporting something as an arbitrary name is impossible outside of
export * from
. So this proposal is designed to fully fill out the possibility matrix and make arbitrary alias names a proper first-class feature.Implement more accurate
sideEffects
behavior from Webpack (#1184)This release adds support for the implicit
**/
prefix that must be added to paths in thesideEffects
array inpackage.json
if the path does not contain/
. Another way of saying this is ifpackage.json
contains asideEffects
array with a string that doesn't contain a/
then it should be treated as a file name instead of a path. Previously esbuild treated all strings in this array as paths, which does not match how Webpack behaves. The result of this meant that esbuild could consider files to have no side effects while Webpack would consider the same files to have side effects. This bug should now be fixed.v0.11.13
Compare Source
Implement ergonomic brand checks for private fields
This introduces new JavaScript syntax:
The TC39 proposal for this feature is currently at stage 3 but has already been shipped in Chrome 91 and has also landed in Firefox. It seems reasonably inevitable given that it's already shipping and that it's a very simple feature, so it seems appropriate to add this feature to esbuild.
Add the
--allow-overwrite
flag (#1152)This is a new flag that allows output files to overwrite input files. It's not enabled by default because doing so means overwriting your source code, which can lead to data loss if your code is not checked in. But supporting this makes certain workflows easier by avoiding the need for a temporary directory so doing this is now supported.
Minify property accesses on object literals (#1166)
The code
{a: {b: 1}}.a.b
will now be minified to1
. This optimization is relatively complex and hard to do safely. Here are some tricky cases that are correctly handled:Improve arrow function parsing edge cases
There are now more situations where arrow expressions are not allowed. This improves esbuild's alignment with the JavaScript specification. Some examples of cases that were previously allowed but that are now no longer allowed:
v0.11.12
Compare Source
Fix a bug where
-0
and0
were collapsed to the same value (#1159)Previously esbuild would collapse
Object.is(x ? 0 : -0, -0)
intoObject.is((x, 0), -0)
during minification, which is incorrect. The IEEE floating-point value-0
is a different bit pattern than0
and while they both compare equal, the difference is detectable in a few scenarios such as when usingObject.is()
. The minification transformation now checks for-0
vs.0
and no longer has this bug. This fix was contributed by @rtsao.Match the TypeScript compiler's output in a strange edge case (#1158)
With this release, esbuild's TypeScript-to-JavaScript transform will no longer omit the namespace in this case:
This was previously omitted because TypeScript omits empty namespaces, and the namespace was considered empty because the
export declare function
statement isn't "real":The TypeScript compiler compiles the above code into the following:
Notice how
Something.Print
is never called, and what appears to be a reference to thePrint
symbol on the namespaceSomething
is actually a reference to the global variablePrint
. I can only assume this is a bug in TypeScript, but it's important to replicate this behavior inside esbuild for TypeScript compatibility.The TypeScript-to-JavaScript transform in esbuild has been updated to match the TypeScript compiler's output in both of these cases.
Separate the
debug
log level intodebug
andverbose
You can now use
--log-level=debug
to get some additional information that might indicate some problems with your build, but that has a high-enough false-positive rate that it isn't appropriate for warnings, which are on by default. Enabling thedebug
log level no longer generates a torrent of debug information like it did in the past; that behavior is now reserved for theverbose
log level instead.v0.11.11
Compare Source
Initial support for Deno (#936)
You can now use esbuild in the Deno JavaScript environment via esbuild's official Deno package. Using it looks something like this:
It has basically the same API as esbuild's npm package with one addition: you need to call
stop()
when you're done because unlike node, Deno doesn't provide the necessary APIs to allow Deno to exit while esbuild's internal child process is still running.Remove warnings about non-bundled use of
require
andimport
(#1153, #1142, #1132, #1045, #812, #661, #574, #512, #495, #480, #453, #410, #80)Previously esbuild had warnings when bundling about uses of
require
andimport
that are not of the formrequire(<string literal>)
orimport(<string literal>)
. These warnings existed because the bundling process must be able to statically-analyze all dynamic imports to determine which files must be included. Here are some real-world examples of cases that esbuild doesn't statically analyze:From
mongoose
:From
moment
:From
logform
:All of these dynamic imports will not be bundled (i.e. they will be left as-is) and will crash at run-time if they are evaluated. Some of these crashes are ok since the code paths may have error handling or the code paths may never be used. Other crashes are not ok because the crash will actually be hit.
The warning from esbuild existed to let you know that esbuild is aware that it's generating a potentially broken bundle. If you discover that your bundle is broken, it's nice to have a warning from esbuild to point out where the problem is. And it was just a warning so the build process still finishes and successfully generates output files. If you didn't want to see the warning, it was easy to turn it off via
--log-level=error
.However, there have been quite a few complaints about this warning. Some people seem to not understand the difference between a warning and an error, and think the build has failed even though output files were generated. Other people do not want to see the warning but also do not want to enable
--log-level=error
.This release removes this warning for both
require
andimport
. Now when you try to bundle code with esbuild that contains dynamic imports not of the formrequire(<string literal>)
orimport(<string literal>)
, esbuild will just silently generate a potentially broken bundle. This may affect people coming from other bundlers that support certain forms of dynamic imports that are not compatible with esbuild such as the Webpack-specific dynamicimport()
with pattern matching.v0.11.10
Compare Source
Provide more information about
exports
map import failures if possible (#1143)Node has a new feature where you can add an
exports
map to yourpackage.json
file to control how external import paths map to the files in your package. You can change which paths map to which files as well as make it impossible to import certain files (i.e. the files are private).If path resolution fails due to an
exports
map and the failure is not related to import conditions, esbuild's current error message for this just says that the import isn't possible:This error message matches the error that node itself throws. However, the message could be improved in the case where someone is trying to import a file using its file system path and that path is actually exported by the package, just under a different export path. This case comes up a lot when using TypeScript because the TypeScript compiler (and therefore the Visual Studio Code IDE) still doesn't support package
exports
.With this release, esbuild will now do a reverse lookup of the file system path using the
exports
map to determine what the correct import path should be:Hopefully this should enable people encountering this issue to fix the problem themselves.
v0.11.9
Compare Source
Fix escaping of non-BMP characters in property names (#977)
Property names in object literals do not have to be quoted if the property is a valid JavaScript identifier. This is defined as starting with a character in the
ID_Start
Unicode category and ending with zero or more characters in theID_Continue
Unicode category. However, esbuild had a bug where non-BMP characters (i.e. characters encoded using two UTF-16 code units instead of one) were always checked againstID_Continue
instead ofID_Start
because they included a code unit that wasn't at the start. This could result in invalid JavaScript being generated when using--charset=utf8
becauseID_Continue
is a superset ofID_Start
and contains some characters that are not valid at the start of an identifier. This bug has been fixed.Be maximally liberal in the interpretation of the
browser
field (#740)The
browser
field inpackage.json
is an informal convention followed by browser-specific bundlers that allows package authors to substitute certain node-specific import paths with alternative browser-specific import paths. It doesn't have a rigorous specification and the canonical description of the feature doesn't include any tests. As a result, each bundler implements this feature differently. I have tried to create a survey of how different bundlers interpret thebrowser
field and the results are very inconsistent.This release attempts to change esbuild to support the union of the behavior of all other bundlers. That way if people have the
browser
field working with some other bundler and they switch to esbuild, thebrowser
field shouldn't ever suddenly stop working. This seemed like the most principled approach to take in this situation.The drawback of this approach is that it means the
browser
field may start working when switching to esbuild when it was previously not working. This could cause bugs, but I consider this to be a problem with the package (i.e. not using a more well-supported form of thebrowser
field), not a problem with esbuild itself.v0.11.8
Compare Source
Fix hash calculation for code splitting and dynamic imports (#1076)
The hash included in the file name of each output file is intended to change if and only if anything relevant to the content of that output file changes. It includes:
import
statementsHowever, this didn't include dynamic
import()
expressions due to an oversight. With this release, dynamicimport()
expressions are now also counted as transitive dependencies. This fixes an issue where the content of an output file could change without its hash also changing. As a side effect of this change, dynamic imports inside output files of other output files are now listed in the metadata file if themetafile
setting is enabled.Refactor the internal module graph representation
This release changes a large amount of code relating to esbuild's internal module graph. The changes are mostly organizational and help consolidate most of the logic around maintaining various module graph invariants into a separate file where it's easier to audit. The Go language doesn't have great abstraction capabilities (e.g. no zero-cost iterators) so the enforcement of this new abstraction is unfortunately done by convention instead of by the compiler, and there is currently still some code that bypasses the abstraction. But it's better than it was before.
Another relevant change was moving a number of special cases that happened during the tree shaking traversal into the graph itself instead. Previously there were quite a few implicit dependency rules that were checked in specific places, which was hard to follow. Encoding these special case constraints into the graph itself makes the problem easier to reason about and should hopefully make the code more regular and robust.
Finally, this set of changes brings back full support for the
sideEffects
annotation inpackage.json
. It was previously disabled when code splitting was active as a temporary measure due to the discovery of some bugs in that scenario. But I believe these bugs have been resolved now that tree shaking and code splitting are done in separate passes (see the previous release for more information).v0.11.7
Compare Source
Fix incorrect chunk reference with code splitting, css, and dynamic imports (#1125)
This release fixes a bug where when you use code splitting, CSS imports in JS, and dynamic imports all combined, the dynamic import incorrectly references the sibling CSS chunk for the dynamic import instead of the primary JS chunk. In this scenario the entry point file corresponds to two different output chunks (one for CSS and one for JS) and the wrong chunk was being picked. This bug has been fixed.
Split apart tree shaking and code splitting (#1123)
The original code splitting algorithm allowed for files to be split apart and for different parts of the same file to end up in different chunks based on which entry points needed which parts. This was done at the same time as tree shaking by essentially performing tree shaking multiple times, once per entry point, and tracking which entry points each file part is live in. Each file part that is live in at least one entry point was then assigned to a code splitting chunk with all of the other code that is live in the same set of entry points. This ensures that entry points only import code that they will use (i.e. no code will be downloaded by an entry point that is guaranteed to not be used).
This file-splitting feature has been removed because it doesn't work well with the recently-added top-level await JavaScript syntax, which has complex evaluation order rules that operate at file boundaries. File parts now have a single boolean flag for whether they are live or not instead of a set of flags that track which entry points that part is reachable from (reachability is still tracked at the file level).
However, this change appears to have introduced some subtly incorrect behavior with code splitting because there is now an implicit dependency in the import graph between adjacent parts within the same file even if the two parts are unrelated and don't reference each other. This is due to the fact each entry point that references one part pulls in the file (but not the whole file, only the parts that are live in at least one entry point). So liveness must be fully computed first before code splitting is computed.
This release splits apart tree shaking and code splitting into two separate passes, which fixes certain cases where two generated code splitting chunks ended up each importing symbols from the other and causing a cycle. There should hopefully no longer be cycles in generated code splitting chunks.
Make
this
work in static class fields in TypeScript filesCurrently
this
is mis-compiled in static fields in TypeScript files if theuseDefineForClassFields
setting intsconfig.json
isfalse
(the default value):This is currently compiled into the code below, which is incorrect because it changes the value of
this
(it's supposed to refer toFoo
):This was an intentionally unhandled case because the TypeScript compiler doesn't handle this either (esbuild's currently incorrect output matches the output from the TypeScript compiler, which is also currently incorrect). However, the TypeScript compiler might fix their output at some point in which case esbuild's behavior would become problematic.
So this release now generates the correct output:
Presumably the TypeScript compiler will be fixed to also generate something like this in the future. If you're wondering why esbuild generates the extra
_Foo
variable, it's defensive code to handle the possibility of the class being reassigned, since class declarations are not constants:We can't just move the initializer containing
Foo.foo
outside of the class body because in JavaScript, the class name is shadowed inside the class body by a special hidden constant that is equal to the class object. Even if the class is reassigned later, references to that shadowing symbol within the class body should still refer to the original class object.Various fixes for private class members (#1131)
This release fixes multiple issues with esbuild's handling of the
#private
syntax. Previously there could be scenarios where references tothis.#private
could be moved outside of the class body, which would cause them to become invalid (since the#private
name is only available within the class body). One such case is when TypeScript'suseDefineForClassFields
setting has the valuefalse
(which is the default value), which causes class field initializers to be replaced with assignment expressions to avoid using "define" semantics:Previously this was turned into the following code, which is incorrect because
Foo.#foo
was moved outside of the class body:This is now handled by converting the private field syntax into normal JavaScript that emulates it with a
WeakMap
instead.This conversion is fairly conservative to make sure certain edge cases are covered, so this release may unfortunately convert more private fields than previous releases, even when the target is
esnext
. It should be possible to improve this transformation in future releases so that this happens less often while still preserving correctness.v0.11.6
Compare Source
Fix an incorrect minification transformation (#1121)
This release removes an incorrect substitution rule in esbuild's peephole optimizer, which is run when minification is enabled. The incorrect rule transformed
if(a && falsy)
intoif(a, falsy)
which is equivalent iffalsy
has no side effects (such as the literalfalse
). However, the rule didn't check that the expression is side-effect free first which could result in miscompiled code. I have removed the rule instead of modifying it to check for the lack of side effects first because while the code is slightly smaller, it may also be more expensive at run-time which is undesirable. The size savings are also very insignificant.Change how
NODE_PATH
works to match node (#1117)Node searches for packages in nearby
node_modules
directories, but it also allows you to inject extra directories to search for packages in using theNODE_PATH
environment variable. This is supported when using esbuild's CLI as well as via thenodePaths
option when using esbuild's API.Node's module resolution algorithm is well-documented, and esbuild's path resolution is designed to follow it. The full algorithm is here: https://nodejs.org/api/modules.html#modules_all_together. However, it appears that the documented algorithm is incorrect with regard to
NODE_PATH
. The documentation saysNODE_PATH
directories should take precedence overnode_modules
directories, and so that's how esbuild worked. However, in practice node actually does it the other way around.Starting with this release, esbuild will now allow
node_modules
directories to take precedence overNODE_PATH
directories. This is a deviation from the published algorithm.Provide a better error message for incorrectly-quoted JSX attributes (#959, #1115)
People sometimes try to use the output of
JSON.stringify()
as a JSX attribute when automatically-generating JSX code. Doing so is incorrect because JSX strings work like XML instead of like JS (since JSX is XML-in-JS). Specifically, using a backslash before a quote does not cause it to be escaped:It's not just esbuild; Babel and TypeScript also treat this as a syntax error. All of these JSX parsers are just following the JSX specification. This has come up twice now so it could be worth having a dedicated error message. Previously esbuild had a generic syntax error like this:
Now esbuild will provide more information if it detects this case:
v0.11.5
Compare Source
Add support for the
override
keyword in TypeScript 4.3 (#1105)The latest version of TypeScript (now in beta) adds a new keyword called
override
that can be used on class members. You can read more about this feature in Microsoft's blog post about TypeScript 4.3. It looks like this:With this release, esbuild will now ignore the
override
keyword when parsing TypeScript code instead of treating this keyword as a syntax error, which means esbuild can now support TypeScript 4.3 syntax. This change was contributed by @g-plane.Allow
async
pluginsetup
functionsWith this release, you can now return a promise from your plugin's
setup
function to delay the start of the build:This is useful if your plugin needs to do something asynchronous before the build starts. For example, you may need some asynchronous information before modifying the
initialOptions
object, which must be done before the build starts for the modifications to take effect.Add some optimizations around hashing
This release contains two optimizations to the hashes used in output file names:
Hash generation now happens in parallel with other work, and other work only blocks on the hash computation if the hash ends up being needed (which is only if
[hash]
is included in--entry-names=
, and potentially--chunk-names=
if it's relevant). This is a performance improvement because--entry-names=
does not include[hash]
in the default case, so bundling time no longer always includes hashing time.The hashing algorithm has been changed from SHA1 to xxHash (specifically this Go implementation) which means the hashing step is around 6x faster than before. Thanks to @Jarred-Sumner for the suggestion.
Disable tree shaking annotations when code splitting is active (#1070, #1081)
Support for Webpack's
"sideEffects": false
annotation inpackage.json
is now disabled when code splitting is enabled and there is more than one entry point. This avoids a bug that could cause generated chunks to reference each other in some cases. Now all chunks generated by code splitting should be acyclic.v0.11.4
Compare Source
Avoid name collisions with TypeScript helper functions (#1102)
Helper functions are sometimes used when transforming newer JavaScript syntax for older browsers. For example,
let {x, ...y} = {z}
is transformed intolet _a = {z}, {x} = _a, y = __rest(_a, ["x"])
which uses the__rest
helper function. Many of esbuild's transforms were modeled after the transforms in the TypeScript compiler, so many of the helper functions use the same names as TypeScript's helper functions.However, the TypeScript compiler doesn't avoid name collisions with existing identifiers in the transformed code. This means that post-processing esbuild's output with the TypeScript compiler (e.g. for lowering ES6 to ES5) will cause issues since TypeScript will fail to call its own helper functions: microsoft/TypeScript#43296. There is also a problem where TypeScript's
tslib
library overwrites globals with these names, which can overwrite esbuild's helper functions if code bundled with esbuild is run in the global scope.To avoid these problems, esbuild will now use different names for its helper functions.
Fix a chunk hashing issue (#1099)
Previously the chunk hashing algorithm skipped hashing entry point chunks when the
--entry-names=
setting doesn't contain[hash]
, since the hash wasn't used in the file name. However, this is no longer correct with the change in version 0.11.0 that made dynamic entry point chunks use--chunk-names=
instead of--entry-names=
since--chunk-names=
can still contain[hash]
.With this release, chunk contents will now always be hashed regardless of the chunk type. This makes esbuild somewhat slower than before in the common case, but it fixes this correctness issue.
v0.11.3
Compare Source
Auto-define
process.env.NODE_ENV
when platform is set tobrowser
All code in the React world has the requirement that the specific expression
process.env.NODE_ENV
must be replaced with a string at compile-time or your code will immediately crash at run-time. This is a common stumbling point for people when they start using esbuild with React. Previously bundling code with esbuild containingprocess.env.NODE_ENV
without defining a string replacement first was a warning that warned you about the lack of a define.With this release esbuild will now attempt to define
process.env.NODE_ENV
automatically instead of warning about it. This will be implicitly defined to"production"
if minification is enabled and"development"
otherwise. This automatic behavior only happens when the platform isbrowser
, sinceprocess
is not a valid browser API and will never exist in the browser. This is also only done if there are no existing defines forprocess
,process.env
, orprocess.env.NODE_ENV
so you can override the automatic value if necessary. If you need to disable this behavior, you can use theneutral
platform instead of thebrowser
platform.Retain side-effect free intermediate re-exporting files (#1088)
This fixes a subtle bug with esbuild's support for Webpack's
"sideEffects": false
annotation inpackage.json
when combined with re-export statements. A re-export is when you import something from one file and then export it again. You can re-export something withexport * from
orexport {foo} from
orimport {foo} from
followed byexport {foo}
.The bug was that files which only contain re-exports and that are marked as being side-effect free were not being included in the bundle if you import one of the re-exported symbols. This is because esbuild's implementation of re-export linking caused the original importing file to "short circuit" the re-export and just import straight from the file containing the final symbol, skipping the file containing the re-export entirely.
This was normally not observable since the intermediate file consisted entirely of re-exports, which have no side effects. However, a recent change to allow ESM files to be lazily-initialized relies on all intermediate files being included in the bundle to trigger the initialization of the lazy evaluation wrappers. So the behavior of skipping over re-export files is now causing the imported symbols to not be initialized if the re-exported file is marked as lazily-evaluated.
The fix is to track all re-exports in the import chain from the original file to the file containing the final symbol and then retain all of those statements if the import ends up being used.
Add a very verbose
debug
log levelThis log level is an experiment. Enabling it logs a lot of information (currently only about path resolution). The idea is that if you are having an obscure issue, the debug log level might contain some useful information. Unlike normal logs which are meant to mainly provide actionable information, these debug logs are intentionally mostly noise and are designed to be searched through instead.
Here is an example of debug-level log output:
v0.11.2
Compare Source
Add a shim function for unbundled uses of
require
(#1202)Modules in CommonJS format automatically get three variables injected into their scope:
module
,exports
, andrequire
. These allow the code to import other modules and to export things from itself. The bundler automatically rewrites uses ofmodule
andexports
to refer to the module's exports and certain uses ofrequire
to a helper function that loads the imported module.Not all uses of
require
can be converted though, and un-converted uses ofrequire
will end up in the output. This is problematic becauserequire
is only present at run-time if the output is run as a CommonJS module. Otherwiserequire
is undefined, which means esbuild's behavior is inconsistent between compile-time and run-time. Themodule
andexports
variables are objects at compile-time and run-time butrequire
is a function at compile-time and undefined at run-time. This causes code that checks fortypeof require
to have inconsistent behavior:In the above example, ideally
CommonJS detected
would always be printed since the code is being bundled with a CommonJS-aware bundler. To fix this, esbuild will now substitute references torequire
with a stub__require
function when bundling if the output format is something other than CommonJS. This should ensure thatrequire
is now consistent between compile-time and run-time. When bundled, code that uses unbundled references torequire
will now look something like this:Fix incorrect caching of internal helper function library (#1292)
This release fixes a bug where running esbuild multiple times with different configurations sometimes resulted in code that would crash at run-time. The bug was introduced in version 0.11.19 and happened because esbuild's internal helper function library is parsed once and cached per configuration, but the new profiler name option was accidentally not included in the cache key. This option is now included in the cache key so this bug should now be fixed.
Minor performance improvements
This release contains some small performance improvements to offset an earlier minor performance regression due to the addition of certain features such as hashing for entry point files. The benchmark times on the esbuild website should now be accurate again (versions of esbuild after the regression but before this release were slightly slower than the benchmark).
v0.11.1
Compare Source
Allow esbuild to be restarted in Deno (#1238)
The esbuild API for Deno has an extra function called
stop()
that doesn't exist in esbuild's API for node. This is because Deno doesn't provide a way to stop esbuild automatically, so callingstop()
is required to allow Deno to exit. However, once stopped the esbuild API could not be restarted.With this release, you can now continue to use esbuild after calling
stop()
. This will restart esbuild's API and means that you will need to callstop()
again for Deno to be able to exit. This feature was contributed by @lucacasonato.Fix code splitting edge case (#1252)
This release fixes an edge case where bundling with code splitting enabled generated incorrect code if multiple ESM entry points re-exported the same re-exported symbol from a CommonJS file. In this case the cross-chunk symbol dependency should be the variable that holds the return value from the
require()
call instead of the original ESM namedimport
clause item. When this bug occurred, the generated ESM code contained an export and import for a symbol that didn't exist, which caused a module initialization error. This case should now work correctly.Fix code generation with
declare
class fields (#1242)This fixes a bug with TypeScript code that uses
declare
on a class field and yourtsconfig.json
file has"useDefineForClassFields": true
. Fields marked asdeclare
should not be defined in the generated code, but they were incorrectly being declared asundefined
. These fields are now correctly omitted from the generated code.Annotate module wrapper functions in debug builds (#1236)
Sometimes esbuild needs to wrap certain modules in a function when bundling. This is done both for lazy evaluation and for CommonJS modules that use a top-level
return
statement. Previously these functions were all anonymous, so stack traces for errors thrown during initialization looked like this:This release adds names to these anonymous functions when minification is disabled. The above stack trace now looks like this:
This is similar to Webpack's development-mode behavior:
These descriptive function names will additionally be available when using a profiler such as the one included in the "Performance" tab in Chrome Developer Tools. Previously all functions were named
(anonymous)
which made it difficult to investigate performance issues during bundle initialization.Add CSS minification for more cases
The following CSS minification cases are now supported:
The CSS
margin
property family is now minified including combining themargin-top
,margin-right
,margin-bottom
, andmargin-left
properties into a singlemargin
property.The CSS
padding
property family is now minified including combining thepadding-top
,padding-right
,padding-bottom
, andpadding-left
properties into a singlepadding
property.The CSS
border-radius
property family is now minified including combining theborder-top-left-radius
,border-top-right-radius
,border-bottom-right-radius
, andborder-bottom-left-radius
properties into a singleborder-radius
property.The four special pseudo-elements
::before
,::after
,::first-line
, and::first-letter
are allowed to be parsed with one:
for legacy reasons, so the::
is now converted to:
for these pseudo-elements.Duplicate CSS rules are now deduplicated. Only the last rule is kept, since that's the only one that has any effect. This applies for both top-level rules and nested rules.
Preserve quotes around properties when minification is disabled (#1251)
Previously the parser did not distinguish between unquoted and quoted properties, since there is no semantic difference. However, some tools such as Google Closure Compiler with "advanced mode" enabled attach their own semantic meaning to quoted properties, and processing code intended for Google Closure Compiler's advanced mode with esbuild was changing those semantics. The distinction between unquoted and quoted properties is now made in the following cases:
The parser will now preserve the quoted properties in these cases as long as
--minify-syntax
is not enabled. This does not mean that esbuild is officially supporting Google Closure Compiler's advanced mode, just that quoted properties are now preserved when the AST is pretty-printed. Google Closure Compiler's advanced mode accepts a language that shares syntax with JavaScript but that deviates from JavaScript semantics and there could potentially be other situations where preprocessing code intended for Google Closure Compiler's advanced mode with esbuild first causes it to break. If that happens, that is not a bug with esbuild.v0.11.0
Compare Source
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
esbuild
in yourpackage.json
file or be using a version range syntax that only accepts patch upgrades such as~0.10.0
. See the documentation about semver for more information.The changes in this release mostly relate to how entry points are handled. The way output paths are generated has changed in some cases, so you may need to update how you refer to the output path for a given entry point when you update to this release (see below for details). These breaking changes are as follows:
Change how
require()
andimport()
of ESM works (#667, #706)Previously if you call
require()
on an ESM file, or callimport()
on an ESM file with code splitting disabled, esbuild would convert the ESM file to CommonJS. For example, if you had the following input files:The previous bundling behavior would generate something like this:
This behavior has been changed and esbuild now generates something like this instead:
The variables have been pulled out of the lazily-initialized closure and are accessible to the rest of the module's scope. Some benefits of this approach:
If another file does
import {foo} from "./esm-file.js"
, it will just referencefoo
directly and will not pay the performance penalty or code size overhead of the dynamic property accesses that come with CommonJS-style exports. So this improves performance and reduces code size in some cases.This fixes a long-standing bug (#706) where entry point exports could be broken if the entry point is a target of a
require()
call and the output format was ESM. This happened because previously callingrequire()
on an entry point converted it to CommonJS, which then meant it only had a singledefault
export, and the exported variables were inside the CommonJS closure and inaccessible to an ESM-styleexport {}
clause. Now callingrequire()
on an entry point only causes it to be lazily-initialized but all exports are still in the module scope and can still be exported using a normalexport {}
clause.Now that this has been changed,
import()
of a module with top-level await (#253) is now allowed when code splitting is disabled. Previously this didn't work becauseimport()
with code splitting disabled was implemented by converting the module to CommonJS and usingPromise.resolve().then(() => require())
, but converting a module with top-level await to CommonJS is impossible because the CommonJS call signature must be synchronous. Now that this implemented using lazy initialization instead of CommonJS conversion, the closure wrapping the ESM file can now beasync
and theimport()
expression can be replaced by a call to the lazy initializer.Adding the ability for ESM files to be lazily-initialized is an important step toward additional future code splitting improvements including: manual chunk names (#207), correct import evaluation order (#399), and correct top-level await evaluation order (#253). These features all need to make use of deferred evaluation of ESM code.
In addition, calling
require()
on an ESM file now recursively wraps all transitive dependencies of that file instead of just wrapping that ESM file itself. This is an increase in the size of the generated code, but it is important for correctness (#667). Callingrequire()
on a module means its evaluation order is determined at run-time, which means the evaluation order of all dependencies must also be determined at run-time. If you don't want the increase in code size, you should use animport
statement instead of arequire()
call.Dynamic imports now use chunk names instead of entry names (#1056)
Previously the output paths of dynamic imports (files imported using the
import()
syntax) were determined by the--entry-names=
setting. However, this can cause problems if you configure the--entry-names=
setting to omit both[dir]
and[hash]
because then two dynamic imports with the same name will cause an output file name collision.Now dynamic imports use the
--chunk-names=
setting instead, which is used for automatically-generated chunks. This setting is effectively required to include[hash]
so dynamic import name collisions should now be avoided.In addition, dynamic imports no longer affect the automatically-computed default value of
outbase
. By defaultoutbase
is computed to be the lowest common ancestor directory of all entry points. Previously dynamic imports were considered entry points in this calculation so adding a dynamic entry point could unexpectedly affect entry point output file paths. This issue has now been fixed.Allow custom output paths for individual entry points
By default, esbuild will automatically generate an output path for each entry point by computing the relative path from the
outbase
directory to the entry point path, and then joining that relative path to theoutdir
directory. The output path can be customized usingoutpath
, but that only works for a single file. Sometimes you may need custom output paths while using multiple entry points. You can now do this by passing the entry points as a map instead of an array:CLI
esbuild out1=in1.js out2=in2.js --outdir=out
JS
Go
This will cause esbuild to generate the files
out/out1.js
andout/out2.js
inside the output directory. These custom output paths are used as input for the--entry-names=
path template setting, so you can use something like--entry-names=[dir]/[name]-[hash]
to add an automatically-computed hash to each entry point while still using the custom output path.Derive entry point output paths from the original input path (#945)
Previously esbuild would determine the output path for an entry point by looking at the post-resolved path. For example, running
esbuild --bundle react --outdir=out
would generate the output pathout/index.js
because the input pathreact
was resolved tonode_modules/react/index.js
. With this release, the output path is now determined by looking at the pre-resolved path. For example, runningesbuild --bundle react --outdir=out
now generates the output pathout/react.js
. If you need to keep using the output path that esbuild previously generated with the old behavior, you can use the custom output path feature (described above).Use the
file
namespace for file entry points (#791)Plugins that contain an
onResolve
callback with thefile
filter don't apply to entry point paths because it's not clear that entry point paths are files. For example, you could potentially bundle an entry point ofhttps://www.example.com/file.js
with a HTTP plugin that automatically downloads data from the server at that URL. But this behavior can be unexpected for people writing plugins.With this release, esbuild will do a quick check first to see if the entry point path exists on the file system before running plugins. If it exists as a file, the namespace will now be
file
for that entry point path. This only checks the exact entry point name and doesn't attempt to search for the file, so for example it won't handle cases where you pass a package path as an entry point or where you pass an entry point without an extension. Hopefully this should help improve this situation in the common case where the entry point is an exact path.In addition to the breaking changes above, the following features are also included in this release:
Warn about mutation of private methods (#1067)
Mutating a private method in JavaScript is not allowed, and will throw at run-time:
This is the case both when esbuild passes the syntax through untransformed and when esbuild transforms the syntax into the equivalent code that uses a
WeakSet
to emulate private methods in older browsers. However, it's clear from this code that doing this will always throw, so this code is almost surely a mistake. With this release, esbuild will now warn when you do this. This change was contributed by @jridgewell.Fix some obscure TypeScript type parsing edge cases
In TypeScript, type parameters come after a type and are placed in angle brackets like
Foo<T>
. However, certain built-in types do not accept type parameters including primitive types such asnumber
. This meansif (x as number < 1) {}
is not a syntax error whileif (x as Foo < 1) {}
is a syntax error. This release changes TypeScript type parsing to allow type parameters in a more restricted set of situations, which should hopefully better resolve these type parsing ambiguities.v0.10.2
Compare Source
Fix a crash that was introduced in the previous release (#1064)
This crash happens when code splitting is active and there is a CSS entry point as well as two or more JavaScript entry points. There is a known issue where CSS bundling does not work when code splitting is active (code splitting is still a work in progress, see #608) so doing this will likely not work as expected. But esbuild obviously shouldn't crash. This release fixes the crash, although esbuild still does not yet generate the correct CSS output in this case.
Fix private fields inside destructuring assignment (#1066)
Private field syntax (i.e.
this.#field
) is supported for older language targets by converting the code into accesses into aWeakMap
. However, although regular assignment (i.e.this.#field = 1
) was handled destructuring assignment (i.e.[this.#field] = [1]
) was not handled due to an oversight. Support for private fields inside destructuring assignment is now included with this release.Fix an issue with direct
eval
and top-level symbolsIt was previously the case that using direct
eval
caused the file containing it to be considered a CommonJS file, even if the file used ESM syntax. This was because the evaluated code could potentially attempt to interact with top-level symbols by name and the CommonJS closure was used to isolate those symbols from other modules so their names could be preserved (otherwise their names may need to be renamed to avoid collisions). However, ESM files are no longer convertable to CommonJS files due to the need to support top-level await.This caused a bug where scope hoisting could potentially merge two modules containing direct
eval
and containing the same top-level symbol name into the same scope. These symbols were prevented from being renamed due to the directeval
, which caused a syntax error at run-time due to the name collision.Because of this, esbuild is dropping the guarantee that using direct
eval
in an ESM file will be able to access top-level symbols. These symbols are now free to be renamed to avoid name collisions, and will now be minified when identifier minification is enabled. This is unlikely to affect real-world code because most real-world uses of directeval
only attempt to access local variables, not top-level symbols.Using direct
eval
in an ESM file when bundling with esbuild will generate a warning. The warning is not new and is present in previous releases of esbuild as well. The way to avoid the warning is to avoid directeval
, since directeval
is somewhat of an anti-pattern and there are better alternatives.v0.10.1
Compare Source
Expose
metafile
toonRebuild
in watch mode (#1057)Previously the build results returned to the watch mode
onRebuild
callback was missing themetafile
property when themetafile: true
option was present. This bug has been fixed.Add a
formatMessages
API (#1058)This API lets you print log messages to the terminal using the same log format that esbuild itself uses. This can be used to filter esbuild's warnings while still making the output look the same. Here's an example of calling this API:
Remove the file splitting optimization (#998)
This release removes the "file splitting optimization" that has up to this point been a part of esbuild's code splitting algorithm. This optimization allowed code within a single file to end up in separate chunks as long as that code had no side effects. For example, bundling two entry points that both use a disjoint set of code from a shared file consisting only of code without side effects would previously not generate any shared code chunks at all.
This optimization is being removed because the top-level await feature was added to JavaScript after this optimization was added, and performing this optimization in the presence of top-level await is more difficult than before. The correct evaulation order of a module graph containing top-level await is extremely complicated and is specified at the module boundary. Moving code that is marked as having no side effects across module boundaries under these additional constraints is even more complexity and is getting in the way of implementing top-level await. So the optimization has been removed to unblock work on top-level await, which esbuild must support.
v0.10.0
Compare Source
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
esbuild
in yourpackage.json
file or be using a version range syntax that only accepts patch upgrades such as~0.9.0
. See the documentation about semver for more information.That said, there are no breaking API changes in this release. The breaking changes are instead about how input files are interpreted and/or how output files are generated in some cases. So upgrading should be relatively straightforward as your API calls should still work the same way, but please make sure to test your code when you upgrade because the output may be different. These breaking changes are as follows:
No longer support
module
orexports
in an ESM file (#769)This removes support for using CommonJS exports in a file with ESM exports. Previously this worked by converting the ESM file to CommonJS and then mixing the CommonJS and ESM exports into the same
exports
object. But it turns out that supporting this is additional complexity for the bundler, so it has been removed. It's also not something that works in real JavaScript environments since modules will never support both export syntaxes at once.Note that this doesn't remove support for using
require
in ESM files. Doing this still works (and can be made to work in a real ESM environment by assigning toglobalThis.require
). This also doesn't remove support for usingimport
in CommonJS files. Doing this also still works.No longer change
import()
torequire()
(#1029)Previously esbuild's transform for
import()
matched TypeScript's behavior, which is to transform it intoPromise.resolve().then(() => require())
when the current output format is something other than ESM. This was done when an import is external (i.e. not bundled), either due to the expression not being a string or due to the string matching an external import path.With this release, esbuild will no longer do this. Now
import()
expressions will be preserved in the output instead. These expressions can be handled in non-ESM code by arranging for theimport
identifier to be a function that imports ESM code. This is how node works, so it will now be possible to useimport()
with node when the output format is something other than ESM.Run-time
export * as
statements no longer convert the file to CommonJSCertain
export * as
statements require a bundler to evaluate them at run-time instead of at compile-time like the JavaScript specification. This is the case when re-exporting symbols from an external file and a file in CommonJS format.Previously esbuild would handle this by converting the module containing the
export * as
statement to CommonJS too, since CommonJS exports are evaluated at run-time while ESM exports are evaluated at bundle-time. However, this is undesirable because tree shaking only works for ESM, not for CommonJS, and the CommonJS wrapper causes additional code bloat. Another upcoming problem is that top-level await cannot work within a CommonJS module because CommonJSrequire()
is synchronous.With this release, esbuild will now convert modules containing a run-time
export * as
statement to a special ESM-plus-dynamic-fallback mode. In this mode, named exports present at bundle time can still be imported directly by name, but any imports that don't match one of the explicit named imports present at bundle time will be converted to a property access on the fallback object instead of being a bundle error. These property accesses are then resolved at run-time and will be undefined if the export is missing.Change whether certain files are interpreted as ESM or CommonJS (#1043)
The bundling algorithm currently doesn't contain any logic that requires flagging modules as CommonJS vs. ESM beforehand. Instead it handles a superset and then sort of decides later if the module should be treated as CommonJS vs. ESM based on whether the module uses the
module
orexports
variables and/or theexports
keyword.With this release, files that follow node's rules for module types will be flagged as explicitly ESM. This includes files that end in
.mjs
and files within a package containing"type": "module"
in the enclosingpackage.json
file. The CommonJSmodule
andexports
features will be unavailable in these files. This matters most for files without any exports, since then it's otherwise ambiguous what the module type is.In addition, files without exports should now accurately fall back to being considered CommonJS. They should now generate a
default
export of an empty object when imported using animport
statement, since that's what happens in node when you import a CommonJS file into an ESM file in node. Previously the default export could be undefined because these export-less files were sort of treated as ESM but with missing import errors turned into warnings instead.This is an edge case that rarely comes up in practice, since you usually never import things from a module that has no exports.
In addition to the breaking changes above, the following features are also included in this release:
Initial support for bundling with top-level await (#253)
Top-level await is a feature that lets you use an
await
expression at the top level (outside of anasync
function). Here is an example:Top-level await only works in ECMAScript modules, and does not work in CommonJS modules. This means that you must use an
import
statement or animport()
expression to import a module containing top-level await. You cannot userequire()
because it's synchronous while top-level await is asynchronous. There should be a descriptive error message when you try to do this.This initial release only has limited support for top-level await. It is only supported with the
esm
output format, but not with theiife
orcjs
output formats. In addition, the compilation is not correct in that two modules that both contain top-level await and that are siblings in the import graph will be evaluated in serial instead of in parallel. Full support for top-level await will come in a future release.Add the ability to set
sourceRoot
in source maps (#1028)You can now use the
--source-root=
flag to set thesourceRoot
field in source maps generated by esbuild. When asourceRoot
is present in a source map, all source paths are resolved relative to it. This is particularly useful when you are hosting compiled code on a server and you want to point the source files to a GitHub repo, such as what AMP does.Here is the description of
sourceRoot
from the source map specification:This feature was contributed by @jridgewell.
Allow plugins to return custom file watcher paths
Currently esbuild's watch mode automatically watches all file system paths that are handled by esbuild itself, and also automatically watches the paths of files loaded by plugins when the paths are in the
file
namespace. The paths of files that plugins load in namespaces other than thefile
namespace are not automatically watched.Also, esbuild never automatically watches any file system paths that are consulted by the plugin during its processing, since esbuild is not aware of those paths. For example, this means that if a plugin calls
require.resolve()
, all of the various "does this file exist" checks that it does will not be watched automatically. So if one of those files is created in the future, esbuild's watch mode will not rebuild automatically even though the build is now outdated.To fix this problem, this release introduces the
watchFiles
andwatchDirs
properties on plugin return values. Plugins can specify these to add additional custom file system paths to esbuild's internal watch list. Paths in thewatchFiles
array cause esbuild to rebuild if the file contents change, and paths in thewatchDirs
array cause esbuild to rebuild if the set of directory entry names changes for that directory path.Note that
watchDirs
does not cause esbuild to rebuild if any of the contents of files inside that directory are changed. It also does not recursively traverse through subdirectories. It only watches the set of directory entry names (i.e. the output of the Unixls
command).v0.9.7
Compare Source
Add support for Android on ARM 64-bit (#803)
This release includes support for Android in the official
esbuild
package. It should now be possible to install and run esbuild on Android devices through npm.Fix incorrect MIME types on Windows (#1030)
The web server built into esbuild uses the file extension to determine the value of the
Content-Type
header. This was previously done using themime.TypeByExtension()
function from Go's standard library. However, this function is apparently broken on Windows because installed programs can change MIME types in the Windows registry: golang/go#32350. This release fixes the problem by using a copy of Go'smime.TypeByExtension()
function without the part that reads from the Windows registry.Using a top-level return inside an ECMAScript module is now forbidden
The CommonJS module format is implemented as an anonymous function wrapper, so technically you can use a top-level
return
statement and it will actually work. Some packages in the wild use this to exit early from module initialization, so esbuild supports this. However, the ECMAScript module format doesn't allow top-level returns. With this release, esbuild no longer allows top-level returns in ECMAScript modules.v0.9.6
Compare Source
Expose build options to plugins (#373)
Plugins can now access build options from within the plugin using the
initialOptions
property. For example:Fix an edge case with the object spread transform (#1017)
This release fixes esbuild's object spread transform in cases where property assignment could be different than property definition. For example:
This should print
{x: 1}
but transforming this through esbuild with--target=es6
causes the resulting code to throw an error. The problem is that esbuild currently transforms this code to a call toObject.assign
and that uses property assignment semantics, which causes the assignment to throw (since you can't assign to a getter-only property).With this release, esbuild will now transform this into code that manually loops over the properties and copies them over one-by-one using
Object.defineProperty
instead. This uses property definition semantics which better matches the specification.Fix a TypeScript parsing edge case with arrow function return types (#1016)
This release fixes the following TypeScript parsing edge case:
This was tripping up esbuild's TypeScript parser because the
>=
token was split into a>
token and a=
token because the>
token is needed to close the type parameter list, but the=
token was not being combined with the following>
token to form a=>
token. This is normally not an issue because there is normally a space in between the>
and the=>
tokens here. The issue only happened when the spaces were removed. This bug has been fixed. Now after the>=
token is split, esbuild will expand the=
token into the following characters if possible, which can result in a=>
,==
, or===
token.Enable faster synchronous transforms under a flag (#1000)
Currently the synchronous JavaScript API calls
transformSync
andbuildSync
spawn a new child process on every call. This is due to limitations with node'schild_process
API. Doing this meanstransformSync
andbuildSync
are much slower thantransform
andbuild
, which share the same child process across calls.There was previously a workaround for this limitation that uses node's
worker_threads
API and atomics to block the main thread while asynchronous communication happens in a worker, but that was reverted due to a bug in node'sworker_threads
implementation. Now that this bug has been fixed by node, I am re-enabling this workaround. This should result intransformSync
andbuildSync
being much faster.This approach is experimental and is currently only enabled if the
ESBUILD_WORKER_THREADS
environment variable is present. If this use case matters to you, please try it out and let me know if you find any problems with it.Update how optional chains are compiled to match new V8 versions (#1019)
An optional chain is an expression that uses the
?.
operator, which roughly avoids evaluation of the right-hand side if the left-hand side isnull
orundefined
. Soa?.b
is basically equivalent toa == null ? void 0 : a.b
. When the language target is set toes2019
or below, esbuild will transform optional chain expressions into equivalent expressions that do not use the?.
operator.This transform is designed to match the behavior of V8 exactly, and is designed to do something similar to the equivalent transform done by the TypeScript compiler. However, V8 has recently changed its behavior in two cases:
Forced call of an optional member expression should propagate the object to the method:
V8 bug: https://bugs.chromium.org/p/v8/issues/detail?id=10024
Optional call of
eval
must be an indirect eval:V8 bug: https://bugs.chromium.org/p/v8/issues/detail?id=10630
This release changes esbuild's transform to match V8's new behavior. The transform in the TypeScript compiler is still emulating the old behavior as of version 4.2.3, so these syntax forms should be avoided in TypeScript code for portability.
v0.9.5
Compare Source
Fix parsing of the
[dir]
placeholder (#1013)The entry names feature in the previous release accidentally didn't include parsing for the
[dir]
placeholder, so the[dir]
placeholder was passed through verbatim into the resulting output paths. This release fixes the bug, which means you can now use the[dir]
placeholder. Sorry about the oversight.v0.9.4
Compare Source
Enable hashes in entry point file paths (#518)
This release adds the new
--entry-names=
flag. It's similar to the--chunk-names=
and--asset-names=
flags except it sets the output paths for entry point files. The pattern defaults to[dir]/[name]
which should be equivalent to the previous entry point output path behavior, so this should be a backward-compatible change.This change has the following consequences:
It is now possible for entry point output paths to contain a hash. For example, this now happens if you pass
--entry-names=[dir]/[name]-[hash]
. This means you can now use esbuild to generate output files such that all output paths have a hash in them, which means it should now be possible to serve the output files with an infinite cache lifetime so they are only downloaded once and then cached by the browser forever.It is now possible to prevent the generation of subdirectories inside the output directory. Previously esbuild replicated the directory structure of the input entry points relative to the
outbase
directory (which defaults to the lowest common ancestor directory across all entry points). This value is substituted into the newly-added[dir]
placeholder. But you can now omit it by omitting that placeholder, like this:--entry-names=[name]
.Source map names should now be equal to the corresponding output file name plus an additional
.map
extension. Previously the hashes were content hashes, so the source map had a different hash than the corresponding output file because they had different contents. Now they have the same hash so finding the source map should now be easier (just add.map
).Due to the way the new hashing algorithm works, all chunks can now be generated fully in parallel instead of some chunks having to wait until their dependency chunks have been generated first. The import paths for dependency chunks are now swapped in after chunk generation in a second pass (detailed below). This could theoretically result in a speedup although I haven't done any benchmarks around this.
Implementing this feature required overhauling how hashes are calculated to prevent the chicken-and-egg hashing problem due to dynamic imports, which can cause cycles in the import graph of the resulting output files when code splitting is enabled. Since generating a hash involved first hashing all of your dependencies, you could end up in a situation where you needed to know the hash to calculate the hash (if a file was a dependency of itself).
The hashing algorithm now works in three steps (potentially subject to change in the future):
The initial versions of all output files are generated in parallel, with temporary paths used for any imports of other output files. Each temporary path is a randomly-generated string that is unique for each output file. An initial source map is also generated at this step if source maps are enabled.
The hash for the first step includes: the raw content of the output file excluding the temporary paths, the relative file paths of all input files present in that output file, the relative output path for the resulting output file (with
[hash]
for the hash that hasn't been computed yet), and contents of the initial source map.After the initial versions of all output files have been generated, calculate the final hash and final output path for each output file. Calculating the final output path involves substituting the final hash for the
[hash]
placeholder in the entry name template.The hash for the second step includes: the hash from the first step for this file and all of its transitive dependencies.
After all output files have a final output path, the import paths in each output file for importing other output files are substituted. Source map offsets also have to be adjusted because the final output path is likely a different length than the temporary path used in the first step. This is also done in parallel for each output file.
This whole algorithm roughly means the hash of a given output file should change if an only if any input file in that output file or any output file it depends on is changed. So the output path and therefore the browser's cache key should not change for a given output file in between builds if none of the relevant input files were changed.
Fix importing a path containing a
?
character on Windows (#989)On Windows, the
?
character is not allowed in path names. This causes esbuild to fail to import paths containing this character. This is usually fine because people don't put?
in their file names for this reason. However, the import paths for some ancient CSS code contains the?
character as a hack to work around a bug in Internet Explorer:The intent is for the bundler to ignore the
?#iefix
part. However, there may actually be a file calledicons.eot?#iefix
on the file system so esbuild checks the file system for bothicons.eot?#iefix
andicons.eot
. This check was triggering this issue. With this release, an invalid path is considered the same as a missing file so bundling code like this should now work on Windows.Parse and ignore the deprecated
@-ms-viewport
CSS rule (#997)The
@viewport
rule has been deprecated and removed from the web. Modern browsers now completely ignore this rule. However, in theory it sounds like would still work for mobile versions of Internet Explorer, if those still exist. The https://ant.design/ library contains an instance of the@-ms-viewport
rule and it currently causes a warning with esbuild, so this release adds support for parsing this rule to disable the warning.Avoid mutating the binary executable file in place (#963)
This release changes the install script for the
esbuild
npm package to use the "rename a temporary file" approach instead of the "write the file directly" approach to replace theesbuild
command stub file with the real binary executable. This should hopefully work around a problem with the pnpm package manager and its use of hard links.Avoid warning about potential issues with
sideEffects
in packages (#999)Bare imports such as
import "foo"
mean the package is only imported for its side effects. Doing this when the package contains"sideEffects": false
inpackage.json
causes a warning because it means esbuild will not import the file since it has been marked as having no side effects, even though the import statement clearly expects it to have side effects. This is usually caused by an incorrectsideEffects
annotation in the package.However, this warning is not immediately actionable if the file containing the import statement is itself in a package. So with this release, esbuild will no longer issue this warning if the file containing the import is inside a
node_modules
folder. Note that even though the warning is no longer there, this situation can still result in a broken bundle if thesideEffects
annotation is incorrect.v0.9.3
Compare Source
Fix path resolution with the
exports
field for scoped packagesThis release fixes a bug where the
exports
field inpackage.json
files was not being detected for scoped packages (i.e. packages of the form@scope/pkg-name
instead of justpkg-name
). Theexports
field should now be respected for these kinds of packages.Improved error message in
exports
failure caseNode's new conditional exports feature can be non-intuitive and hard to use. Now that esbuild supports this feature (as of version 0.9.0), you can get into a situation where it's impossible to import a package if the package's
exports
field in itspackage.json
file isn't configured correctly.Previously the error message for this looked like this:
With this release, the error message will now provide additional information about why the package cannot be imported:
In this case, one solution could be import this module using
require()
since this package provides an export for therequire
condition. Another solution could be to pass--conditions=module
to esbuild since this package provides an export for themodule
condition (thetypes
condition is likely not valid JavaScript code).This problem occurs because this package doesn't provide an import path for ESM code using the
import
condition and also doesn't provide a fallback import path using thedefault
condition.Mention glob syntax in entry point error messages (#976)
In this release, including a
*
in the entry point path now causes the failure message to tell you that glob syntax must be expanded first before passing the paths to esbuild. People that hit this are usually converting an existing CLI command to a JavaScript API call and don't know that glob expansion is done by their shell instead of by esbuild. An appropriate fix is to use a library such asglob
to expand the glob pattern first before passing the paths to esbuild.Raise certain VM versions in the JavaScript feature compatibility table
JavaScript VM feature compatibility data is derived from this dataset: https://kangax.github.io/compat-table/. The scripts that process the dataset expand the data to include all VM versions that support a given feature (e.g.
chrome44
,chrome45
,chrome46
, ...) so esbuild takes the minimum observed version as the first version for which the feature is supported.However, some features can have subtests that each check a different aspect of the feature. In this case the desired version is the minimum version within each individual subtest, but the maximum of those versions across all subtests (since esbuild should only use the feature if it works in all cases). Previously esbuild computed the minimum version across all subtests, but now esbuild computes the maximum version across all subtests. This means esbuild will now lower JavaScript syntax in more cases.
Mention the configured target environment in error messages (#975)
Using newer JavaScript syntax with an older target environment (e.g.
chrome10
) can cause a build error if esbuild doesn't support transforming that syntax such that it is compatible with that target environment. Previously the error message was generic but with this release, the target environment is called outp explicitly in the error message. This is helpful if esbuild is being wrapped by some other tool since the other tool can obscure what target environment is actually being passed to esbuild.Fix an issue with Unicode and source maps
This release fixes a bug where non-ASCII content that ended up in an output file but that was not part of an input file could throw off source mappings. An example of this would be passing a string containing non-ASCII characters to the
globalName
setting with theminify
setting active and thecharset
setting set toutf8
. The conditions for this bug are fairly specific and unlikely to be hit, so it's unsurprising that this issue hasn't been discovered earlier. It's also unlikely that this issue affected real-world code.The underlying cause is that while the meaning of column numbers in source maps is undefined in the specification, in practice most tools treat it as the number of UTF-16 code units from the start of the line. The bug happened because column increments for outside-of-file characters were incorrectly counted using byte offsets instead of UTF-16 code unit counts.
v0.9.2
Compare Source
Fix export name annotations in CommonJS output for node (#960)
The previous release introduced a regression that caused a syntax error when building ESM files that have a default export with
--platform=node
. This is because the generated export contained thedefault
keyword like this:0 && (module.exports = {default});
. This regression has been fixed.v0.9.1
Compare Source
Fix bundling when parent directory is inaccessible (#938)
Previously bundling with esbuild when a parent directory is inaccessible did not work because esbuild would try to read the directory to search for a
node_modules
folder and would then fail the build when that failed. In practice this caused issues in certain Linux environments where a directory close to the root directory was inaccessible (e.g. on Android). With this release, esbuild will treat inaccessible directories as empty to allow for thenode_modules
search to continue past the inaccessible directory and into its parent directory. This means it should now be possible to bundle with esbuild in these situations.Avoid allocations in JavaScript API stdout processing (#941)
This release improves the efficiency of the JavaScript API. The API runs the binary esbuild executable in a child process and then communicates with it over stdin/stdout. Previously the stdout buffer containing the remaining partial message was copied after each batch of messages due to a bug. This was unintentional and unnecessary, and has been removed. Now this part of the code no longer involves any allocations. This fix was contributed by @jridgewell.
Support conditional
@import
syntax when not bundling (#953)Previously conditional CSS imports such as
@import "print.css" print;
was not supported at all and was considered a syntax error. With this release, it is now supported in all cases except when bundling an internal import. Support for bundling internal CSS imports is planned but will happen in a later release.Always lower object spread and rest when targeting V8 (#951)
This release causes object spread (e.g.
a = {...b}
) and object rest (e.g.{...a} = b
) to always be lowered to a manual implementation instead of using native syntax when the--target=
parameter includes a V8-based JavaScript runtime such aschrome
,edge
, ornode
. It turns out this feature is implemented inefficiently in V8 and copying properties over to a new object is around a 2x performance improvement. In addition, doing this manually instead of using the native implementation generates a lot less work for the garbage collector. You can see V8 bug 11536 for details. If the V8 performance bug is eventually fixed, the translation of this syntax will be disabled again for V8-based targets containing the bug fix.Fix object rest return value (#956)
This release fixes a bug where the value of an object rest assignment was incorrect if the object rest assignment was lowered:
Previously this code would incorrectly print
{y: 2}
(the value assigned toy
) when the object rest expression was lowered (i.e. with--target=es2017
or below). Now this code will correctly print{x: 1, y: 2}
instead. This bug did not affect code that did not rely on the return value of the assignment expression, such as this code:Basic support for CSS page margin rules (#955)
There are 16 different special at-rules that can be nested inside the
@page
rule. They are defined in this specification. Previously esbuild treated these as unknown rules, but with this release esbuild will now treat these as known rules. The only real difference in behavior is that esbuild will no longer warn about these rules being unknown.Add export name annotations to CommonJS output for node
When you import a CommonJS file using an ESM
import
statement in node, thedefault
import is the value ofmodule.exports
in the CommonJS file. In addition, node attempts to generate named exports for properties of themodule.exports
object.Except that node doesn't actually ever look at the properties of that object to determine the export names. Instead it parses the CommonJS file and scans the AST for certain syntax patterns. A full list of supported patterns can be found in the documentation for the
cjs-module-lexer
package. This library doesn't currently support the syntax patterns used by esbuild.While esbuild could adapt its syntax to these patterns, the patterns are less compact than the ones used by esbuild and doing this would lead to code bloat. Supporting two separate ways of generating export getters would also complicate esbuild's internal implementation, which is undesirable.
Another alternative could be to update the implementation of
cjs-module-lexer
to support the specific patterns used by esbuild. This is also undesirable because this pattern detection would break when minification is enabled, this would tightly couple esbuild's output format with node and prevent esbuild from changing it, and it wouldn't work for existing and previous versions of node that still have the old version of this library.Instead, esbuild will now add additional code to "annotate" ESM files that have been converted to CommonJS when esbuild's platform has been set to
node
. The annotation is dead code but is still detected by thecjs-module-lexer
library. If the original ESM file has the exportsfoo
andbar
, the additional annotation code will look like this:This allows you to use named imports with an ESM
import
statement in node (previously you could only use thedefault
import):v0.9.0
Compare Source
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
esbuild
in yourpackage.json
file or be using a version range syntax that only accepts patch upgrades such as^0.8.0
. See the documentation about semver for more information.Add support for node's
exports
field inpackage.json
files (#187)This feature was recently added to node. It allows you to rewrite what import paths inside your package map to as well as to prevent people from importing certain files in your package. Adding support for this to esbuild is a breaking change (i.e. code that was working fine before can easily stop working) so adding support for it has been delayed until this breaking change release.
One way to use this feature is to remap import paths for your package. For example, this would remap an import of
your-pkg/esm/lib.js
(the "public" import path) toyour-pkg/dist/esm/lib.js
(the "private" file system path):Another way to use this feature is to have conditional imports where the same import path can mean different things in different situations. For example, this would remap
require('your-pkg')
toyour-pkg/required.cjs
andimport 'your-pkg'
toyour-pkg/imported.mjs
:There is built-in support for the
import
andrequire
conditions depending on the kind of import and thebrowser
andnode
conditions depending on the current platform. In addition, thedefault
condition always applies regardless of the current configuration settings and can be used as a catch-all fallback condition.Note that when you use conditions, your package may end up in the bundle multiple times! This is a subtle issue that can cause bugs due to duplicate copies of your code's state in addition to bloating the resulting bundle. This is commonly known as the dual package hazard. The primary way of avoiding this is to put all of your code in the
require
condition and have theimport
condition just be a light wrapper that callsrequire
on your package and re-exports the package using ESM syntax.There is also support for custom conditions with the
--conditions=
flag. The meaning of these is entirely up to package authors. For example, you could imagine a package that requires you to configure--conditions=test,en-US
. Node has currently only endorsed thedevelopment
andproduction
custom conditions for recommended use.Remove the
esbuild.startService()
APIDue to #656, Calling
service.stop()
no longer does anything, so there is no longer a strong reason for keeping theesbuild.startService()
API around. The primary thing it currently does is just make the API more complicated and harder to use. You can now just callesbuild.build()
andesbuild.transform()
directly instead of callingesbuild.startService().then(service => service.build())
oresbuild.startService().then(service => service.transform())
.If you are using esbuild in the browser, you now need to call
esbuild.initialize({ wasmURL })
and wait for the returned promise before callingesbuild.transform()
. It takes the same options thatesbuild.startService()
used to take. Note that theesbuild.buildSync()
andesbuild.transformSync()
APIs still exist when using esbuild in node. Nothing has changed about the synchronous esbuild APIs.Remove the
metafile
fromoutputFiles
(#633)Previously using
metafile
with the API is unnecessarily cumbersome because you have to extract the JSON metadata from the output file yourself instead of it just being provided to you as a return value. This is especially a bummer if you are usingwrite: false
because then you need to use a for loop over the output files and do string comparisons with the file paths to try to find the one corresponding to themetafile
. Returning the metadata directly is an important UX improvement for the API. It means you can now do this:The banner and footer options are now language-specific (#712)
The
--banner=
and--footer=
options now require you to pass the file type:CLI:
JavaScript
Go
This was changed because the feature was originally added in a JavaScript-specific manner, which was an oversight. CSS banners and footers must be separate from JavaScript banners and footers to avoid injecting JavaScript syntax into your CSS files.
The extensions
.mjs
and.cjs
are no longer implicitPreviously the "resolve extensions" setting included
.mjs
and.cjs
but this is no longer the case. This wasn't a good default because it doesn't match node's behavior and could break some packages. You now have to either explicitly specify these extensions or configure the "resolve extensions" setting yourself.Remove the
--summary
flag and instead just always print a summary (#704)The summary can be disabled if you don't want it by passing
--log-level=warning
instead. And it can be enabled in the API by settinglogLevel: 'info'
. I'm going to try this because I believe it will improve the UX. People have this problem with esbuild when they first try it where it runs so quickly that they think it must be broken, only to later discover that it actually worked fine. While this is funny, it seems like a good indication that the UX could be improved. So I'm going to try automatically printing a summary to see how that goes. Note that the summary is not printed if incremental builds are active (this includes the watch and serve modes).Rename
--error-limit=
to--log-limit=
This parameter has been renamed because it now applies to both warnings and errors, not just to errors. Previously setting the error limit did not apply any limits to the number of warnings printed, which could sometimes result in a deluge of warnings that are problematic for Windows Command Prompt, which is very slow to print to and has very limited scrollback. Now the log limit applies to the total number of log messages including both errors and warnings, so no more than that number of messages will be printed. The log usually prints log messages immediately but it will now intentionally hold back warnings when approaching the limit to make room for possible future errors during a build. So if a build fails you should be guaranteed to see an error message (i.e. warnings can't use up the entire log limit and then prevent errors from being printed).
Remove the deprecated
--avoid-tdz
optionThis option is now always enabled and cannot be disabled, so it is being removed from the API. The existing API parameter no longer does anything so this removal has no effect the generated output.
Remove
SpinnerBusy
andSpinnerIdle
from the Go APIThese options were part of an experiment with the CLI that didn't work out. Watch mode no longer uses a spinner because it turns out people want to be able to interleave esbuild's stderr pipe with other tools and were getting tripped up by the spinner animation. These options no longer do anything and have been removed.
v0.8.57
Compare Source
Fix overlapping chunk names when code splitting is active (#928)
Code splitting chunks use a content hash in their file name. This is good for caching because it means the file name is guaranteed to change if the chunk contents change, and the file name is guaranteed to stay the same if the chunk contents don't change (e.g. someone only modifies a comment). However, using a pure content hash can cause bugs if two separate chunks end up with the same contents.
A high-level example would be two identical copies of a library being accidentally collapsed into a single copy. While this results in a smaller bundle, this is incorrect because each copy might need to have its own state and so must be represented independently in the bundle.
This release fixes this issue by mixing additional information into the file name hash, which is no longer a content hash. The information includes the paths of the input files as well as the ranges of code within the file that are included in the chunk. File paths are used because they are a stable file identifier, but the relative path is used with
/
as the path separator to hopefully eliminate cross-platform differences between Unix and Windows.Fix
--keep-names
for lowered class fieldsAnonymous function expressions used in class field initializers are automatically assigned a
.name
property in JavaScript:This usually doesn't need special handling from esbuild's
--keep-names
option because esbuild doesn't modify field names, so the.name
property will not change. However, esbuild will relocate the field initializer if the configured language target doesn't support class fields (e.g.--target=es6
). In that case the.name
property wasn't preserved even when--keep-names
was specified. This bug has been fixed. Now the.name
property should be preserved in this case as long as you enable--keep-names
.Enable importing certain data URLs in CSS and JavaScript
You can now import data URLs of type
text/css
using a CSS@import
rule and import data URLs of typetext/javascript
andapplication/json
using a JavaScriptimport
statement. For example, doing this is now possible:This is for compatibility with node which supports this feature natively. Importing from a data URL is sometimes useful for injecting code to be evaluated before an external import without needing to generate a separate imported file.
v0.8.56
Compare Source
Fix a discrepancy with esbuild's
tsconfig.json
implementation (#913)If a
tsconfig.json
file contains a"baseUrl"
value and"extends"
anothertsconfig.json
file that contains a"paths"
value, the base URL used for interpreting the paths should be the overridden value. Previously esbuild incorrectly used the inherited value, but with this release esbuild will now use the overridden value instead.Work around the Jest testing framework breaking node's
Buffer
API (#914)Running esbuild within a Jest test fails because Jest causes
Buffer
instances to not be consideredUint8Array
instances, which then breaks the code esbuild uses to communicate with its child process. More info is here: https://github.com/facebook/jest/issues/4422. This release contains a workaround that copies eachBuffer
object into aUint8Array
object when this invariant is broken. That should prevent esbuild from crashing when it's run from within a Jest test.Better handling of implicit
main
fields inpackage.json
If esbuild's automatic
main
vs.module
detection is enabled forpackage.json
files, esbuild will now useindex.js
as an implicitmain
field if themain
field is missing butindex.js
is present. This means if apackage.json
file only contains amodule
field but not amain
field and the package is imported using both an ESMimport
statement and a CommonJSrequire
call, theindex.js
file will now be picked instead of the file in themodule
field.v0.8.55
Compare Source
Align more closely with node's
default
import behavior for CommonJS (#532)Note: This could be considered a breaking change or a bug fix depending on your point of view.
Importing a CommonJS file into an ESM file does not behave the same everywhere. Historically people compiled their ESM code into CommonJS using Babel before ESM was supported natively. More recently, node has made it possible to use ESM syntax natively but to still import CommonJS files into ESM. These behave differently in many ways but one of the most unfortunate differences is how the
default
export is handled.When you import a normal CommonJS file, both Babel and node agree that the value of
module.exports
should be stored in the ESM import nameddefault
. However, if the CommonJS file used to be an ESM file but was compiled into a CommonJS file, Babel will set the ESM import nameddefault
to the value of the original ESM export nameddefault
while node will continue to set the ESM import nameddefault
to the value ofmodule.exports
. Babel detects if a CommonJS file used to be an ESM file by the presence of theexports.__esModule = true
marker.This is unfortunate because it means there is no general way to make code work with both ecosystems. With Babel the code
import * as someFile from './some-file'
can access the originaldefault
export withsomeFile.default
but with node you need to usesomeFile.default.default
instead. Previously esbuild followed Babel's approach but starting with this release, esbuild will now try to use a blend between the Babel and node approaches.This is the new behavior: importing a CommonJS file will set the
default
import tomodule.exports
in all cases except whenmodule.exports.__esModule && "default" in module.exports
, in which case it will fall through tomodule.exports.default
. In other words: in cases where the default import was previouslyundefined
for CommonJS files whenexports.__esModule === true
, the default import will now bemodule.exports
. This should hopefully keep Babel cross-compiled ESM code mostly working but at the same time now enable some node-oriented code to start working.If you are authoring a library using ESM but shipping it as CommonJS, the best way to avoid this mess is to just never use
default
exports in ESM. Only use named exports with names other thandefault
.Fix bug when ESM file has empty exports and is converted to CommonJS (#910)
A file containing the contents
export {}
is still considered to be an ESM file even though it has no exports. However, if a file containing this edge case is converted to CommonJS internally during bundling (e.g. when it is the target ofrequire()
), esbuild failed to mark theexports
symbol from the CommonJS wrapping closure as used even though it is actually needed. This resulted in an output file that crashed when run. Theexports
symbol is now considered used in this case, so the bug has been fixed.Avoid introducing
this
for imported function callsIt is possible to import a function exported by a CommonJS file into an ESM file like this:
When you do this, esbuild currently transforms your code into something like this:
However, doing that changes the value of
this
observed by the exportfn
. The property accesscjs_file.fn
is in the syntactic "call target" position so the value ofthis
becomes the value ofcjs_file
. With this release, esbuild will now use a different syntax in this case to avoid passingcjs_file
asthis
:This change in esbuild mirrors a similar recent TypeScript compiler change, and also makes esbuild more consistent with Babel which already does this transformation.
v0.8.54
Compare Source
Fix ordering issue with private class methods (#901)
This release fixes an ordering issue with private class fields where private methods were not available inside class field initializers. The issue affected code such as the following when the compilation target was set to
es2020
or lower:With this release, code that does this should now work correctly.
Fix
--keep-names
for private class membersNormal class methods and class fields don't need special-casing with esbuild when the
--keep-names
option is enabled because esbuild doesn't rename property names and doesn't transform class syntax in a way that breaks method names, so the names are kept without needing to generate any additional code.However, this is not the case for private class methods and private class fields. When esbuild transforms these for
--target=es2020
and earlier, the private class methods and private class field initializers are turned into code that uses aWeakMap
or aWeakSet
for access to preserve the privacy semantics. This ends up breaking the.name
property and previously--keep-names
didn't handle this edge case.With this release,
--keep-names
will also preserve the names of private class methods and private class fields. That means code like this should now work with--keep-names --target=es2020
:Fix cross-chunk import paths (#899)
This release fixes an issue with the
--chunk-names=
feature where import paths in between two different automatically-generated code splitting chunks were relative to the output directory instead of relative to the importing chunk. This caused an import failure with the imported chunk if the chunk names setting was configured to put the chunks into a subdirectory. This bug has been fixed.Remove the guarantee that direct
eval
can access imported symbolsUsing direct
eval
when bundling is not a good idea because esbuild must assume that it can potentially reach anything in any of the containing scopes. Using directeval
has the following negative consequences:All names in all containing scopes are frozen and are not renamed during bundling, since the code in the direct
eval
could potentially access them. This prevents code in all scopes containing the call to directeval
from being minified or from being removed as dead code.The entire file is converted to CommonJS. This increases code size and decreases performance because exports are now resolved at run-time instead of at compile-time. Normally name collisions with other files are avoided by renaming conflicting symbols, but direct
eval
prevents symbol renaming so name collisions are prevented by wrapping the file in a CommonJS closure instead.Even with all of esbuild's special-casing of direct
eval
, referencing an ESMimport
from directeval
still doesn't necessarily work. ESM imports are live bindings to a symbol from another file and are represented by referencing that symbol directly in the flattened bundle. That symbol may use a different name which could break directeval
.I recently realized that the last consequence of direct
eval
(the problem about not being able to referenceimport
symbols) could cause subtle correctness bugs. Specifically esbuild tries to prevent the imported symbol from being renamed, but doing so could cause name collisions that make the resulting bundle crash when it's evaluated. Two files containing directeval
that both import the same symbol from a third file but that import it with different aliases create a system of unsatisfiable naming constraints.So this release contains these changes to address this:
Direct
eval
is no longer guaranteed to be able to access imported symbols. This means imported symbols may be renamed or removed as dead code even though a call to directeval
could theoretically need to access them. If you need this to work, you'll have to store the relevant imports in a variable in a nested scope and move the call to directeval
into that nested scope.Using direct
eval
in a file in ESM format is now a warning. This is because the semantics of directeval
are poorly understood (most people don't intend to use directeval
at all) and because the negative consequences of bundling code with directeval
are usually unexpected and undesired. Of the few valid use cases for directeval
, it is usually a good idea to rewrite your code to avoid using directeval
in the first place.For example, if you write code that looks like this:
you should almost certainly write the code this way instead:
This still gives
code
access tofeatureFlags
but avoids all of the negative consequences of bundling code with directeval
.v0.8.53
Compare Source
Support chunk and asset file name templates (#733, #888)
This release introduces the
--chunk-names=
and--asset-names=
flags. These flags let you customize the output paths for chunks and assets within the output directory. Each output path is a template and currently supports these placeholders:[name]
: The original name of the file. This will bechunk
for chunks and will be the original file name (without the extension) for assets.[hash]
: The content hash of the file. This is not necessarily stable across different esbuild versions but will be stable within the same esbuild version.For example, if you want to move all chunks and assets into separate subdirectories, you could use
--chunk-names=chunks/[name]-[hash]
and--asset-names=assets/[name]-[hash]
. Note that the path template should not include the file extension since the file extension is always automatically added to the end of the path template.Additional name template features are planned in the future including a
[dir]
placeholder for the relative path from theoutbase
directory to the original input directory as well as an--entry-names=
flag, but these extra features have not been implemented yet.Handle
this
in class static field initializers (#885)When you use
this
in a static field initializer inside aclass
statement or expression, it references the class object itself:This case previously wasn't handled because doing this is a compile error in TypeScript code. However, JavaScript does allow this so esbuild needs to be able to handle this. This edge case should now work correctly with this release.
Do not warn about dynamic imports when
.catch()
is detected (#893)Previously esbuild avoids warning about unbundled
import()
expressions when using thetry { await import(_) }
pattern, since presumably thetry
block is there to handle the run-time failure of theimport()
expression failing. This release adds some new patterns that will also suppress the warning:import(_).catch(_)
,import(_).then(_).catch(_)
, andimport(_).then(_, _)
.CSS namespaces are no longer supported
CSS namespaces are a weird feature that appears to only really be useful for styling XML. And the world has moved on from XHTML to HTML5 so pretty much no one uses CSS namespaces anymore. They are also complicated to support in a bundler because CSS namespaces are file-scoped, which means:
Default namespaces can be different in different files, in which case some default namespaces would have to be converted to prefixed namespaces to avoid collisions.
Prefixed namespaces from different files can use the same name, in which case some prefixed namespaces would need to be renamed to avoid collisions.
Instead of implementing all of that for an extremely obscure feature, CSS namespaces are now just explicitly not supported. The code to handle
@namespace
has been removed from esbuild. This will likely not affect anyone, especially because bundling code using CSS namespaces with esbuild didn't even work correctly in the first place.v0.8.52
Compare Source
Fix a concurrent map write with the
--inject:
feature (#878)This release fixes an issue where esbuild could potentially crash sometimes with a concurrent map write when using injected files and entry points that were neither relative nor absolute paths. This was an edge case where esbuild's low-level file subsystem was being used without being behind a mutex lock. This regression was likely introduced in version 0.8.21. The cause of the crash has been fixed.
Provide
kind
toonResolve
plugins (#879)Plugins that add
onResolve
callbacks now have access to thekind
parameter which tells you what kind of import is being resolved. It will be one of the following values:"entry-point"
in JS (api.ResolveEntryPoint
in Go)An entry point provided by the user
"import-statement"
in JS (api.ResolveJSImportStatement
in Go)A JavaScript
import
orexport
statement"require-call"
in JS (api.ResolveJSRequireCall
in Go)A JavaScript call to
require(...)
with a string argument"dynamic-import"
in JS (api.ResolveJSDynamicImport
in Go)A JavaScript
import(...)
expression with a string argument"require-resolve"
in JS (api.ResolveJSRequireResolve
in Go)A JavaScript call to
require.resolve(...)
with a string argument"import-rule"
in JS (api.ResolveCSSImportRule
in Go)A CSS
@import
rule"url-token"
in JS (api.ResolveCSSURLToken
in Go)A CSS
url(...)
tokenThese values are pretty much identical to the
kind
field in the JSON metadata file.Configuration
📅 Schedule: At any time (no schedule defined).
🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.
♻ Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.
🔕 Ignore: Close this PR and you won't be reminded about this update again.
This PR has been generated by Renovate Bot.