Packages

@esbuild/linux-arm64

0.28.2 · 8 Aug 2026MIT44.7M / weekRepositoryHomepagenpmAtom feed

Your version

113 stable releases, newest first, by release line. Notes are quoted as the maintainers published them.

  1. 0.19.x
  2. 0.19.2

    14 Aug 2023
    • Update how CSS nesting is parsed again

      CSS nesting syntax has been changed again, and esbuild has been updated to match. Type selectors may now be used with CSS nesting:

      .foo {
        div {
          color: red;
        }
      }

      Previously this was disallowed in the CSS specification because it's ambiguous whether an identifier is a declaration or a nested rule starting with a type selector without requiring unbounded lookahead in the parser. It has now been allowed because the CSS working group has decided that requiring unbounded lookahead is acceptable after all.

      Note that this change means esbuild no longer considers any existing browser to support CSS nesting since none of the existing browsers support this new syntax. CSS nesting will now always be transformed when targeting a browser. This situation will change in the future as browsers add support for this new syntax.

    • Fix a scope-related bug with --drop-labels=

      The recently-released --drop-labels= feature previously had a bug where esbuild's internal scope stack wasn't being restored properly when a statement with a label was dropped. This could manifest as a tree-shaking issue, although it's possible that this could have also been causing other subtle problems too. The bug has been fixed in this release.

    • Make renamed CSS names unique across entry points

      Previously esbuild's generated names for local names in CSS were only unique within a given entry point (or across all entry points when code splitting was enabled). That meant that building multiple entry points with esbuild could result in local names being renamed to the same identifier even when those entry points were built simultaneously within a single esbuild API call. This problem was especially likely to happen with minification enabled. With this release, esbuild will now avoid renaming local names from two separate entry points to the same name if those entry points were built with a single esbuild API call, even when code splitting is disabled.

  3. 0.19.1

    11 Aug 2023
    • Fix a regression with baseURL in tsconfig.json

      The previous release moved tsconfig.json path resolution before --packages=external checks to allow the paths field in tsconfig.json to avoid a package being marked as external. However, that reordering accidentally broke the behavior of the baseURL field from tsconfig.json. This release moves these path resolution rules around again in an attempt to allow both of these cases to work.

    • Parse TypeScript type arguments for JavaScript decorators

      When parsing JavaScript decorators in TypeScript (i.e. with experimentalDecorators disabled), esbuild previously didn't parse type arguments. Type arguments will now be parsed starting with this release. For example:

      @foo<number>
      @bar<number, string>()
      class Foo {}
    • Fix glob patterns matching extra stuff at the end

      Previously glob patterns such as ./*.js would incorrectly behave like ./*.js* during path matching (also matching .js.map files, for example). This was never intentional behavior, and has now been fixed.

  4. 0.19.0

    8 Aug 2023
    • Handle import paths containing wildcards (#56, #700, #875, #976, #2221, #2515)

      This release introduces wildcards in import paths in two places:

    • Path aliases in tsconfig.json no longer count as packages (#2792, #3003, #3160, #3238)

      Setting --packages=external tells esbuild to make all import paths external when they look like a package path. For example, an import of ./foo/bar is not a package path and won't be external while an import of foo/bar is a package path and will be external. However, the paths field in tsconfig.json allows you to create import paths that look like package paths but that do not resolve to packages. People do not want these paths to count as package paths. So with this release, the behavior of --packages=external has been changed to happen after the tsconfig.json path remapping step.

    • Use the local-css loader for .module.css files by default

      With this release the css loader is still used for .css files except that .module.css files now use the local-css loader. This is a common convention in the web development community. If you need .module.css files to use the css loader instead, then you can override this behavior with --loader:.module.css=css.

  5. 0.18.x
  6. 0.18.20

    8 Aug 2023
    • Support advanced CSS @import rules (#953, #3137)

      CSS @import statements have been extended to allow additional trailing tokens after the import path. These tokens sort of make the imported file behave as if it were wrapped in a @layer, @supports, and/or @media rule. Here are some examples:

      @import url(foo.css);
      @import url(foo.css) layer;
      @import url(foo.css) layer(bar);
      @import url(foo.css) layer(bar) supports(display: flex);
      @import url(foo.css) layer(bar) supports(display: flex) print;
      @import url(foo.css) layer(bar) print;
      @import url(foo.css) supports(display: flex);
      @import url(foo.css) supports(display: flex) print;
      @import url(foo.css) print;

      You can read more about this advanced syntax here. With this release, esbuild will now bundle @import rules with these trailing tokens and will wrap the imported files in the corresponding rules. Note that this now means a given imported file can potentially appear in multiple places in the bundle. However, esbuild will still only load it once (e.g. on-load plugins will only run once per file, not once per import).

  7. 0.18.19

    7 Aug 2023
    • Implement composes from CSS modules

      This release implements the composes annotation from the CSS modules specification. It provides a way for class selectors to reference other class selectors (assuming you are using the local-css loader). And with the from syntax, this can even work with local names across CSS files. For example:

      // app.js
      import { submit } from './style.css'
      const div = document.createElement('div')
      div.className = submit
      document.body.appendChild(div)
      /* style.css */
      .button {
        composes: pulse from "anim.css";
        display: inline-block;
      }
      .submit {
        composes: button;
        font-weight: bold;
      }
      /* anim.css */
      @keyframes pulse {
        from, to { opacity: 1 }
        50% { opacity: 0.5 }
      }
      .pulse {
        animation: 2s ease-in-out infinite pulse;
      }

      Bundling this with esbuild using --bundle --outdir=dist --loader:.css=local-css now gives the following:

      (() => {
        // style.css
        var submit = "anim_pulse style_button style_submit";
      
        // app.js
        var div = document.createElement("div");
        div.className = submit;
        document.body.appendChild(div);
      })();
      /* anim.css */
      @keyframes anim_pulse {
        from, to {
          opacity: 1;
        }
        50% {
          opacity: 0.5;
        }
      }
      .anim_pulse {
        animation: 2s ease-in-out infinite anim_pulse;
      }
      
      /* style.css */
      .style_button {
        display: inline-block;
      }
      .style_submit {
        font-weight: bold;
      }

      Import paths in the composes: ... from syntax are resolved using the new composes-from import kind, which can be intercepted by plugins during import path resolution when bundling is enabled.

      Note that the order in which composed CSS classes from separate files appear in the bundled output file is deliberately undefined by design (see the specification for details). You are not supposed to declare the same CSS property in two separate class selectors and then compose them together. You are only supposed to compose CSS class selectors that declare non-overlapping CSS properties.

      Issue #20 (the issue tracking CSS modules) is esbuild's most-upvoted issue! With this change, I now consider esbuild's implementation of CSS modules to be complete. There are still improvements to make and there may also be bugs with the current implementation, but these can be tracked in separate issues.

    • Fix non-determinism with tsconfig.json and symlinks

      This release fixes an issue that could cause esbuild to sometimes emit incorrect build output in cases where a file under the effect of tsconfig.json is inconsistently referenced through a symlink. It can happen when using npm link to create a symlink within node_modules to an unpublished package. The build result was non-deterministic because esbuild runs module resolution in parallel and the result of the tsconfig.json lookup depended on whether the import through the symlink or not through the symlink was resolved first. This problem was fixed by moving the realpath operation before the tsconfig.json lookup.

    • Add a hash property to output files (#3084, #3293)

      As a convenience, every output file in esbuild's API now includes a hash property that is a hash of the contents field. This is the hash that's used internally by esbuild to detect changes between builds for esbuild's live-reload feature. You may also use it to detect changes between your own builds if its properties are sufficient for your use case.

      This feature has been added directly to output file objects since it's just a hash of the contents field, so it makes conceptual sense to store it in the same location. Another benefit of putting it there instead of including it as a part of the watch mode API is that it can be used without watch mode enabled. You can use it to compare the output of two independent builds that were done at different times.

      The hash algorithm (currently XXH64) is implementation-dependent and may be changed at any time in between esbuild versions. If you don't like esbuild's choice of hash algorithm then you are welcome to hash the contents yourself instead. As with any hash algorithm, note that while two different hashes mean that the contents are different, two equal hashes do not necessarily mean that the contents are equal. You may still want to compare the contents in addition to the hashes to detect with certainty when output files have been changed.

  8. 0.18.18

    5 Aug 2023
    • Fix asset references with the --line-limit flag

      The recently-released --line-limit flag tells esbuild to terminate long lines after they pass this length limit. This includes automatically wrapping long strings across multiple lines using escaped newline syntax. However, using this could cause esbuild to generate incorrect code for references from generated output files to assets in the bundle (i.e. files loaded with the file or copy loaders). This is because esbuild implements asset references internally using find-and-replace with a randomly-generated string, but the find operation fails if the string is split by an escaped newline due to line wrapping. This release fixes the problem by not wrapping these strings. This issue affected asset references in both JS and CSS files.

    • Support local names in CSS for @keyframe, @counter-style, and @container

      This release extends support for local names in CSS files loaded with the local-css loader to cover the @keyframe, @counter-style, and @container rules (and also animation, list-style, and container declarations). Here's an example:

      @keyframes pulse {
        from, to { opacity: 1 }
        50% { opacity: 0.5 }
      }
      @counter-style moon {
        system: cyclic;
        symbols: 🌕 🌖 🌗 🌘 🌑 🌒 🌓 🌔;
      }
      @container squish {
        li { float: left }
      }
      ul {
        animation: 2s ease-in-out infinite pulse;
        list-style: inside moon;
        container: squish / size;
      }

      With the local-css loader enabled, that CSS will be turned into something like this (with the local name mapping exposed to JS):

      @keyframes stdin_pulse {
        from, to {
          opacity: 1;
        }
        50% {
          opacity: 0.5;
        }
      }
      @counter-style stdin_moon {
        system: cyclic;
        symbols: 🌕 🌖 🌗 🌘 🌑 🌒 🌓 🌔;
      }
      @container stdin_squish {
        li {
          float: left;
        }
      }
      ul {
        animation: 2s ease-in-out infinite stdin_pulse;
        list-style: inside stdin_moon;
        container: stdin_squish / size;
      }

      If you want to use a global name within a file loaded with the local-css loader, you can use a :global selector to do that:

      div {
        /* All symbols are global inside this scope (i.e.
         * "pulse", "moon", and "squish" are global below) */
        :global {
          animation: 2s ease-in-out infinite pulse;
          list-style: inside moon;
          container: squish / size;
        }
      }

      If you want to use @keyframes, @counter-style, or @container with a global name, make sure it's in a file that uses the css or global-css loader instead of the local-css loader. For example, you can configure --loader:.module.css=local-css so that the local-css loader only applies to *.module.css files.

    • Support strings as keyframe animation names in CSS

      With this release, esbuild will now parse animation names that are specified as strings and will convert them to identifiers. The CSS specification allows animation names to be specified using either identifiers or strings but Chrome only understands identifiers, so esbuild will now always convert string names to identifier names for Chrome compatibility:

      /* Original code */
      @keyframes "hide menu" {
        from { opacity: 1 }
        to { opacity: 0 }
      }
      menu.hide {
        animation: 0.5s ease-in-out "hide menu";
      }
      
      /* Old output */
      @keyframes "hide menu" { from { opacity: 1 } to { opacity: 0 } }
      menu.hide {
        animation: 0.5s ease-in-out "hide menu";
      }
      
      /* New output */
      @keyframes hide\ menu {
        from {
          opacity: 1;
        }
        to {
          opacity: 0;
        }
      }
      menu.hide {
        animation: 0.5s ease-in-out hide\ menu;
      }
  9. 0.18.17

    26 Jul 2023
    • Support An+B syntax and :nth-*() pseudo-classes in CSS

      This adds support for the :nth-child(), :nth-last-child(), :nth-of-type(), and :nth-last-of-type() pseudo-classes to esbuild, which has the following consequences:

      /* Original code */
      .foo:nth-child(+2n+1 of :local(.bar)) {
        color: red;
      }
      
      /* Old output (with --loader=local-css) */
      .stdin_foo:nth-child(+2n + 1 of :local(.bar)) {
        color: red;
      }
      
      /* New output (with --loader=local-css) */
      .stdin_foo:nth-child(2n+1 of .stdin_bar) {
        color: red;
      }
    • Adjust CSS nesting parser for IE7 hacks

      This fixes a regression with esbuild's treatment of IE7 hacks in CSS. CSS nesting allows selectors to be used where declarations are expected. There's an IE7 hack where prefixing a declaration with a * causes that declaration to only be applied in IE7 due to a bug in IE7's CSS parser. However, it's valid for nested CSS selectors to start with *. So esbuild was incorrectly parsing these declarations and anything following it up until the next { as a selector for a nested CSS rule. This release changes esbuild's parser to terminate the parsing of selectors for nested CSS rules when a ; is encountered to fix this edge case:

      /* Original code */
      .item {
        *width: 100%;
        height: 1px;
      }
      
      /* Old output */
      .item {
        *width: 100%; height: 1px; {
        }
      }
      
      /* New output */
      .item {
        *width: 100%;
        height: 1px;
      }

      Note that the syntax for CSS nesting is about to change again, so esbuild's CSS parser may still not be completely accurate with how browsers do and/or will interpret CSS nesting syntax. Expect additional updates to esbuild's CSS parser in the future to deal with upcoming CSS specification changes.

    • Adjust esbuild's warning about undefined imports for TypeScript import equals declarations

      In JavaScript, accessing a missing property on an import namespace object is supposed to result in a value of undefined at run-time instead of an error at compile-time. This is something that esbuild warns you about by default because doing this can indicate a bug with your code. For example:

      // app.js
      import * as styles from './styles'
      console.log(styles.buton)
      // styles.js
      export let button = {}

      If you bundle app.js with esbuild you will get this:

      ▲ [WARNING] Import "buton" will always be undefined because there is no matching export in "styles.js" [import-is-undefined]
      
          app.js:2:19:
            2 │ console.log(styles.buton)
              │                    ~~~~~
              ╵                    button
      
        Did you mean to import "button" instead?
      
          styles.js:1:11:
            1 │ export let button = {}
              ╵            ~~~~~~

      However, there is TypeScript-only syntax for import equals declarations that can represent either a type import (which esbuild should ignore) or a value import (which esbuild should respect). Since esbuild doesn't have a type system, it tries to only respect import equals declarations that are actually used as values. Previously esbuild always generated this warning for unused imports referenced within import equals declarations even when the reference could be a type instead of a value. Starting with this release, esbuild will now only warn in this case if the import is actually used. Here is an example of some code that no longer causes an incorrect warning:

      // app.ts
      import * as styles from './styles'
      import ButtonType = styles.Button
      // styles.ts
      export interface Button {}
  10. 0.18.16

    23 Jul 2023
    • Fix a regression with whitespace inside :is()

      The change to parse the contents of :is() in version 0.18.14 introduced a regression that incorrectly flagged the contents as a syntax error if the contents started with a whitespace token (for example div:is( .foo ) {}). This regression has been fixed.

  11. 0.18.15

    20 Jul 2023
    • Add the --serve-fallback= option

      The web server built into esbuild serves the latest in-memory results of the configured build. If the requested path doesn't match any in-memory build result, esbuild also provides the --servedir= option to tell esbuild to serve the requested path from that directory instead. And if the requested path doesn't match either of those things, esbuild will either automatically generate a directory listing (for directories) or return a 404 error.

      Starting with this release, that last step can now be replaced with telling esbuild to serve a specific HTML file using the --serve-fallback= option. This can be used to provide a "not found" page for missing URLs. It can also be used to implement a single-page app that mutates the current URL and therefore requires the single app entry point to be served when the page is loaded regardless of whatever the current URL is.

    • Use the tsconfig field in package.json during extends resolution

      This release adds a feature from TypeScript 3.2 where if a tsconfig.json file specifies a package name in the extends field and that package's package.json file has a tsconfig field, the contents of that field are used in the search for the base tsconfig.json file.

    • Implement CSS nesting without :is() when possible

      Previously esbuild would always produce a warning when transforming nested CSS for a browser that doesn't support the :is() pseudo-class. This was because the nesting transform needs to generate an :is() in some complex cases which means the transformed CSS would then not work in that browser. However, the CSS nesting transform can often be done without generating an :is(). So with this release, esbuild will no longer warn when targeting browsers that don't support :is() in the cases where an :is() isn't needed to represent the nested CSS.

      In addition, esbuild's nested CSS transform has been updated to avoid generating an :is() in cases where an :is() is preferable but there's a longer alternative that is also equivalent. This update means esbuild can now generate a combinatorial explosion of CSS for complex CSS nesting syntax when targeting browsers that don't support :is(). This combinatorial explosion is necessary to accurately represent the original semantics. For example:

      /* Original code */
      .first,
      .second,
      .third {
        & > & {
          color: red;
        }
      }
      
      /* Old output (with --target=chrome80) */
      :is(.first, .second, .third) > :is(.first, .second, .third) {
        color: red;
      }
      
      /* New output (with --target=chrome80) */
      .first > .first,
      .first > .second,
      .first > .third,
      .second > .first,
      .second > .second,
      .second > .third,
      .third > .first,
      .third > .second,
      .third > .third {
        color: red;
      }

      This change means you can now use CSS nesting with esbuild when targeting an older browser that doesn't support :is(). You'll now only get a warning from esbuild if you use complex CSS nesting syntax that esbuild can't represent in that older browser without using :is(). There are two such cases:

      /* Case 1 */
      a b {
        .foo & {
          color: red;
        }
      }
      
      /* Case 2 */
      a {
        > b& {
          color: red;
        }
      }

      These two cases still need to use :is(), both for different reasons, and cannot be used when targeting an older browser that doesn't support :is():

      /* Case 1 */
      .foo :is(a b) {
        color: red;
      }
      
      /* Case 2 */
      a > a:is(b) {
        color: red;
      }
  12. 0.18.14

    18 Jul 2023
    • Implement local CSS names

      This release introduces two new loaders called global-css and local-css and two new pseudo-class selectors :local() and :global(). This is a partial implementation of the popular CSS modules approach for avoiding unintentional name collisions in CSS. I'm not calling this feature "CSS modules" because although some people in the community call it that, other people in the community have started using "CSS modules" to refer to something completely different and now CSS modules is an overloaded term.

      Here's how this new local CSS name feature works with esbuild:

      Note that esbuild's implementation does not currently have feature parity with other implementations of modular CSS in similar tools. This is only a preliminary release with a partial implementation that includes some basic behavior to get the process started. Additional behavior may be added in future releases. In particular, this release does not implement:

      Issue #20 (the issue for this feature) is esbuild's most-upvoted issue! While this release still leaves that issue open, it's an important first step in that direction.

    • Parse :is, :has, :not, and :where in CSS

      With this release, esbuild will now parse the contents of these pseudo-class selectors as a selector list. This means you will now get syntax warnings within these selectors for invalid selector syntax. It also means that esbuild's CSS nesting transform behaves slightly differently than before because esbuild is now operating on an AST instead of a token stream. For example:

      /* Original code */
      div {
        :where(.foo&) {
          color: red;
        }
      }
      
      /* Old output (with --target=chrome90) */
      :where(.foo:is(div)) {
        color: red;
      }
      
      /* New output (with --target=chrome90) */
      :where(div.foo) {
        color: red;
      }
  13. 0.18.13

    15 Jul 2023
    • Add the --drop-labels= option

      If you want to conditionally disable some development-only code and have it not be present in the final production bundle, right now the most straightforward way of doing this is to use the --define: flag along with a specially-named global variable. For example, consider the following code:

      function main() {
        DEV && doAnExpensiveCheck()
      }

      You can build this for development and production like this:

      One drawback of this approach is that the resulting code crashes if you don't provide a value for DEV with --define:. In practice this isn't that big of a problem, and there are also various ways to work around this.

      However, another approach that avoids this drawback is to use JavaScript label statements instead. That's what the --drop-labels= flag implements. For example, consider the following code:

      function main() {
        DEV: doAnExpensiveCheck()
      }

      With this release, you can now build this for development and production like this:

      This means that code containing optional development-only checks can now be written such that it's safe to run without any additional configuration. The --drop-labels= flag takes comma-separated list of multiple label names to drop.

    • Avoid causing unhandledRejection during shutdown

      All pending esbuild JavaScript API calls are supposed to fail if esbuild's underlying child process is unexpectedly terminated. This can happen if SIGINT is sent to the parent node process with Ctrl+C, for example. Previously doing this could also cause an unhandled promise rejection when esbuild attempted to communicate this failure to its own child process that no longer exists. This release now swallows this communication failure, which should prevent this internal unhandled promise rejection. This change means that you can now use esbuild's JavaScript API with a custom SIGINT handler that extends the lifetime of the node process without esbuild's internals causing an early exit due to an unhandled promise rejection.

    • Update browser compatibility table scripts

      The scripts that esbuild uses to compile its internal browser compatibility table have been overhauled. Briefly:

      This change means it's now much easier to keep esbuild's internal compatibility tables up to date. You can review the table changes here if you need to debug something about this change:

  14. 0.18.12

    13 Jul 2023
    • Fix a panic with const enum inside parentheses

      This release fixes an edge case where esbuild could potentially panic if a TypeScript const enum statement was used inside of a parenthesized expression and was followed by certain other scope-related statements. Here's a minimal example that triggers this edge case:

      (() => {
        const enum E { a };
        () => E.a
      })
    • Allow a newline in the middle of TypeScript export type statement

      Previously esbuild incorrectly rejected the following valid TypeScript code:

      export type
      { T };
      
      export type
      * as foo from 'bar';

      Code that uses a newline after export type is now allowed starting with this release.

    • Fix cross-module inlining of string enums

      A refactoring typo in version 0.18.9 accidentally introduced a regression with cross-module inlining of string enums when combined with computed property accesses. This regression has been fixed.

  15. 0.18.11

    1 Jul 2023
    • Fix a TypeScript code generation edge case

      This release fixes a regression in version 0.18.4 where using a TypeScript namespace that exports a class declaration combined with --keep-names and a --target of es2021 or earlier could cause esbuild to export the class from the namespace using an incorrect name (notice the assignment to X2._Y vs. X2.Y):

      // Original code
      
      // Old output (with --keep-names --target=es2021)
      var X;
      ((X2) => {
        const _Y = class _Y {
        };
        __name(_Y, "Y");
        let Y = _Y;
        X2._Y = _Y;
      })(X || (X = {}));
      
      // New output (with --keep-names --target=es2021)
      var X;
      ((X2) => {
        const _Y = class _Y {
        };
        __name(_Y, "Y");
        let Y = _Y;
        X2.Y = _Y;
      })(X || (X = {}));
  16. 0.18.10

    26 Jun 2023
    • Fix a tree-shaking bug that removed side effects

      This fixes a regression in version 0.18.4 where combining --minify-syntax with --keep-names could cause expressions with side effects after a function declaration to be considered side-effect free for tree shaking purposes. The reason was because --keep-names generates an expression statement containing a call to a helper function after the function declaration with a special flag that makes the function call able to be tree shaken, and then --minify-syntax could potentially merge that expression statement with following expressions without clearing the flag. This release fixes the bug by clearing the flag when merging expression statements together.

    • Fix an incorrect warning about CSS nesting

      A warning is currently generated when transforming nested CSS to a browser that doesn't support :is() because transformed nested CSS may need to use that feature to represent nesting. This was previously always triggered when an at-rule was encountered in a declaration context. Typically the only case you would encounter this is when using CSS nesting within a selector rule. However, there is a case where that's not true: when using a margin at-rule such as @top-left within @page. This release avoids incorrectly generating a warning in this case by checking that the at-rule is within a selector rule before generating a warning.

  17. 0.18.9

    26 Jun 2023
    • Fix await using declarations inside async generator functions

      I forgot about the new await using declarations when implementing lowering for async generator functions in the previous release. This change fixes the transformation of await using declarations when they are inside lowered async generator functions:

      // Original code
      async function* foo() {
        await using x = await y
      }
      
      // Old output (with --supported:async-generator=false)
      function foo() {
        return __asyncGenerator(this, null, function* () {
          await using x = yield new __await(y);
        });
      }
      
      // New output (with --supported:async-generator=false)
      function foo() {
        return __asyncGenerator(this, null, function* () {
          var _stack = [];
          try {
            const x = __using(_stack, yield new __await(y), true);
          } catch (_) {
            var _error = _, _hasError = true;
          } finally {
            var _promise = __callDispose(_stack, _error, _hasError);
            _promise && (yield new __await(_promise));
          }
        });
      }
    • Insert some prefixed CSS properties when appropriate

      With this release, esbuild will now insert prefixed CSS properties in certain cases when the target setting includes browsers that require a certain prefix. This is currently done for the following properties:

      Here is an example:

      /* Original code */
      div {
        mask-image: url(x.png);
      }
      
      /* Old output (with --target=chrome99) */
      div {
        mask-image: url(x.png);
      }
      
      /* New output (with --target=chrome99) */
      div {
        -webkit-mask-image: url(x.png);
        mask-image: url(x.png);
      }

      Browser compatibility data was sourced from the tables on caniuse.com. Support for more CSS properties can be added in the future as appropriate.

    • Fix an obscure identifier minification bug

      Function declarations in nested scopes behave differently depending on whether or not "use strict" is present. To avoid generating code that behaves differently depending on whether strict mode is enabled or not, esbuild transforms nested function declarations into variable declarations. However, there was a bug where the generated variable name was not being recorded as declared internally, which meant that it wasn't being renamed correctly by the minifier and could cause a name collision. This bug has been fixed:

      // Original code
      const n = ''
      for (let i of [0,1]) {
        function f () {}
      }
      
      // Old output (with --minify-identifiers --format=esm)
      const f = "";
      for (let o of [0, 1]) {
        let n = function() {
        };
        var f = n;
      }
      
      // New output (with --minify-identifiers --format=esm)
      const f = "";
      for (let o of [0, 1]) {
        let n = function() {
        };
        var t = n;
      }
  18. 0.18.8

    25 Jun 2023
    • Implement transforming async generator functions

      With this release, esbuild will now transform async generator functions into normal generator functions when the configured target environment doesn't support them. These functions behave similar to normal generator functions except that they use the Symbol.asyncIterator interface instead of the Symbol.iterator interface and the iteration methods return promises. Here's an example (helper functions are omitted):

      // Original code
      async function* foo() {
        yield Promise.resolve(1)
        await new Promise(r => setTimeout(r, 100))
        yield *[Promise.resolve(2)]
      }
      async function bar() {
        for await (const x of foo()) {
          console.log(x)
        }
      }
      bar()
      
      // New output (with --target=es6)
      function foo() {
        return __asyncGenerator(this, null, function* () {
          yield Promise.resolve(1);
          yield new __await(new Promise((r) => setTimeout(r, 100)));
          yield* __yieldStar([Promise.resolve(2)]);
        });
      }
      function bar() {
        return __async(this, null, function* () {
          try {
            for (var iter = __forAwait(foo()), more, temp, error; more = !(temp = yield iter.next()).done; more = false) {
              const x = temp.value;
              console.log(x);
            }
          } catch (temp) {
            error = [temp];
          } finally {
            try {
              more && (temp = iter.return) && (yield temp.call(iter));
            } finally {
              if (error)
                throw error[0];
            }
          }
        });
      }
      bar();

      This is an older feature that was added to JavaScript in ES2018 but I didn't implement the transformation then because it's a rarely-used feature. Note that esbuild already added support for transforming for await loops (the other part of the asynchronous iteration proposal) a year ago, so support for asynchronous iteration should now be complete.

      I have never used this feature myself and code that uses this feature is hard to come by, so this transformation has not yet been tested on real-world code. If you do write code that uses this feature, please let me know if esbuild's async generator transformation doesn't work with your code.

  19. 0.18.7

    24 Jun 2023
    • Add support for using declarations in TypeScript 5.2+

      TypeScript 5.2 (due to be released in August of 2023) will introduce using declarations, which will allow you to automatically dispose of the declared resources when leaving the current scope. You can read the TypeScript PR for this feature for more information. This release of esbuild adds support for transforming this syntax to target environments without support for using declarations (which is currently all targets other than esnext). Here's an example (helper functions are omitted):

      // Original code
      class Foo {
        [Symbol.dispose]() {
          console.log('cleanup')
        }
      }
      using foo = new Foo;
      foo.bar();
      
      // New output (with --target=es6)
      var _stack = [];
      try {
        var Foo = class {
          [Symbol.dispose]() {
            console.log("cleanup");
          }
        };
        var foo = __using(_stack, new Foo());
        foo.bar();
      } catch (_) {
        var _error = _, _hasError = true;
      } finally {
        __callDispose(_stack, _error, _hasError);
      }

      The injected helper functions ensure that the method named Symbol.dispose is called on new Foo when control exits the scope. Note that as with all new JavaScript APIs, you'll need to polyfill Symbol.dispose if it's not present before you use it. This is not something that esbuild does for you because esbuild only handles syntax, not APIs. Polyfilling it can be done with something like this:

      Symbol.dispose ||= Symbol('Symbol.dispose')

      This feature also introduces await using declarations which are like using declarations but they call await on the disposal method (not on the initializer). Here's an example (helper functions are omitted):

      // Original code
      class Foo {
        async [Symbol.asyncDispose]() {
          await new Promise(done => {
            setTimeout(done, 1000)
          })
          console.log('cleanup')
        }
      }
      await using foo = new Foo;
      foo.bar();
      
      // New output (with --target=es2022)
      var _stack = [];
      try {
        var Foo = class {
          async [Symbol.asyncDispose]() {
            await new Promise((done) => {
              setTimeout(done, 1e3);
            });
            console.log("cleanup");
          }
        };
        var foo = __using(_stack, new Foo(), true);
        foo.bar();
      } catch (_) {
        var _error = _, _hasError = true;
      } finally {
        var _promise = __callDispose(_stack, _error, _hasError);
        _promise && await _promise;
      }

      The injected helper functions ensure that the method named Symbol.asyncDispose is called on new Foo when control exits the scope, and that the returned promise is awaited. Similarly to Symbol.dispose, you'll also need to polyfill Symbol.asyncDispose before you use it.

    • Add a --line-limit= flag to limit line length

      Long lines are common in minified code. However, many tools and text editors can't handle long lines. This release introduces the --line-limit= flag to tell esbuild to wrap lines longer than the provided number of bytes. For example, --line-limit=80 tells esbuild to insert a newline soon after a given line reaches 80 bytes in length. This setting applies to both JavaScript and CSS, and works even when minification is disabled. Note that turning this setting on will make your files bigger, as the extra newlines take up additional space in the file (even after gzip compression).

  20. 0.18.6

    20 Jun 2023
    • Fix tree-shaking of classes with decorators

      This release fixes a bug where esbuild incorrectly allowed tree-shaking on classes with decorators. Each decorator is a function call, so classes with decorators must never be tree-shaken. This bug was a regression that was unintentionally introduced in version 0.18.2 by the change that enabled tree-shaking of lowered private fields. Previously decorators were always lowered, and esbuild always considered the automatically-generated decorator code to be a side effect. But this is no longer the case now that esbuild analyzes side effects using the AST before lowering takes place. This bug was fixed by considering any decorator a side effect.

    • Fix a minification bug involving function expressions

      When minification is enabled, esbuild does limited inlining of const symbols at the top of a scope. This release fixes a bug where inlineable symbols were incorrectly removed assuming that they were inlined. They may not be inlined in cases where they were referenced by earlier constants in the body of a function expression. The declarations involved in these edge cases are now kept instead of being removed:

      // Original code
      {
        const fn = () => foo
        const foo = 123
        console.log(fn)
      }
      
      // Old output (with --minify-syntax)
      console.log((() => foo)());
      
      // New output (with --minify-syntax)
      {
        const fn = () => foo, foo = 123;
        console.log(fn);
      }
  21. 0.18.5

    20 Jun 2023
    • Implement auto accessors

      This release implements the new auto-accessor syntax from the upcoming JavaScript decorators proposal. The auto-accessor syntax looks like this:

      class Foo {
        accessor foo;
        static accessor bar;
      }
      new Foo().foo = Foo.bar;

      This syntax is not yet a part of JavaScript but it was added to TypeScript in version 4.9. More information about this feature can be found in microsoft/TypeScript#49705. Auto-accessors will be transformed if the target is set to something other than esnext:

      // Output (with --target=esnext)
      class Foo {
        accessor foo;
        static accessor bar;
      }
      new Foo().foo = Foo.bar;
      
      // Output (with --target=es2022)
      class Foo {
        #foo;
        get foo() {
          return this.#foo;
        }
        set foo(_) {
          this.#foo = _;
        }
        static #bar;
        static get bar() {
          return this.#bar;
        }
        static set bar(_) {
          this.#bar = _;
        }
      }
      new Foo().foo = Foo.bar;
      
      // Output (with --target=es2021)
      var _foo, _bar;
      class Foo {
        constructor() {
          __privateAdd(this, _foo, void 0);
        }
        get foo() {
          return __privateGet(this, _foo);
        }
        set foo(_) {
          __privateSet(this, _foo, _);
        }
        static get bar() {
          return __privateGet(this, _bar);
        }
        static set bar(_) {
          __privateSet(this, _bar, _);
        }
      }
      _foo = new WeakMap();
      _bar = new WeakMap();
      __privateAdd(Foo, _bar, void 0);
      new Foo().foo = Foo.bar;

      You can also now use auto-accessors with esbuild's TypeScript experimental decorator transformation, which should behave the same as decorating the underlying getter/setter pair.

      Please keep in mind that this syntax is not yet part of JavaScript. This release enables auto-accessors in .js files with the expectation that it will be a part of JavaScript soon. However, esbuild may change or remove this feature in the future if JavaScript ends up changing or removing this feature. Use this feature with caution for now.

    • Pass through JavaScript decorators

      In this release, esbuild now parses decorators from the upcoming JavaScript decorators proposal and passes them through to the output unmodified (as long as the language target is set to esnext). Transforming JavaScript decorators to environments that don't support them has not been implemented yet. The only decorator transform that esbuild currently implements is still the TypeScript experimental decorator transform, which only works in .ts files and which requires "experimentalDecorators": true in your tsconfig.json file.

    • Static fields with assign semantics now use static blocks if possible

      Setting useDefineForClassFields to false in TypeScript requires rewriting class fields to assignment statements. Previously this was done by removing the field from the class body and adding an assignment statement after the class declaration. However, this also caused any private fields to also be lowered by necessity (in case a field initializer uses a private symbol, either directly or indirectly). This release changes this transform to use an inline static block if it's supported, which avoids needing to lower private fields in this scenario:

      // Original code
      class Test {
        static #foo = 123
        static bar = this.#foo
      }
      
      // Old output (with useDefineForClassFields=false)
      var _foo;
      const _Test = class _Test {
      };
      _foo = new WeakMap();
      __privateAdd(_Test, _foo, 123);
      _Test.bar = __privateGet(_Test, _foo);
      let Test = _Test;
      
      // New output (with useDefineForClassFields=false)
      class Test {
        static #foo = 123;
        static {
          this.bar = this.#foo;
        }
      }
  22. 0.18.4

    16 Jun 2023
    • Bundling no longer unnecessarily transforms class syntax (#1360, #1328, #1524, #2416)

      When bundling, esbuild automatically converts top-level class statements to class expressions. Previously this conversion had the unfortunate side-effect of also transforming certain other class-related syntax features to avoid correctness issues when the references to the class name within the class body. This conversion has been reworked to avoid doing this:

      // Original code
      export class Foo {
        static foo = () => Foo
      }
      
      // Old output (with --bundle)
      var _Foo = class {
      };
      var Foo = _Foo;
      __publicField(Foo, "foo", () => _Foo);
      
      // New output (with --bundle)
      var Foo = class _Foo {
        static foo = () => _Foo;
      };

      This conversion process is very complicated and has many edge cases (including interactions with static fields, static blocks, private class properties, and TypeScript experimental decorators). It should already be pretty robust but a change like this may introduce new unintentional behavior. Please report any issues with this upgrade on the esbuild bug tracker.

      You may be wondering why esbuild needs to do this at all. One reason to do this is that esbuild's bundler sometimes needs to lazily-evaluate a module. For example, a module may end up being both the target of a dynamic import() call and a static import statement. Lazy module evaluation is done by wrapping the top-level module code in a closure. To avoid a performance hit for static import statements, esbuild stores top-level exported symbols outside of the closure and references them directly instead of indirectly.

      Another reason to do this is that multiple JavaScript VMs have had and continue to have performance issues with TDZ (i.e. "temporal dead zone") checks. These checks validate that a let, or const, or class symbol isn't used before it's initialized. Here are two issues with well-known VMs:

      JavaScriptCore had a severe performance issue as their TDZ implementation had time complexity that was quadratic in the number of variables needing TDZ checks in the same scope (with the top-level scope typically being the worst offender). V8 has ongoing issues with TDZ checks being present throughout the code their JIT generates even when they have already been checked earlier in the same function or when the function in question has already been run (so the checks have already happened).

      Due to esbuild's parallel architecture, esbuild both a) needs to convert class statements into class expressions during parsing and b) doesn't yet know whether this module will need to be lazily-evaluated or not in the parser. So esbuild always does this conversion during bundling in case it's needed for correctness (and also to avoid potentially catastrophic performance issues due to bundling creating a large scope with many TDZ variables).

    • Enforce TDZ errors in computed class property keys

      JavaScript allows class property keys to be generated at run-time using code, like this:

      class Foo {
        static foo = 'foo'
        static [Foo.foo + '2'] = 2
      }

      Previously esbuild treated references to the containing class name within computed property keys as a reference to the partially-initialized class object. That meant code that attempted to reference properties of the class object (such as the code above) would get back undefined instead of throwing an error.

      This release rewrites references to the containing class name within computed property keys into code that always throws an error at run-time, which is how this JavaScript code is supposed to work. Code that does this will now also generate a warning. You should never write code like this, but it now should be more obvious when incorrect code like this is written.

    • Fix an issue with experimental decorators and static fields

      This release also fixes a bug regarding TypeScript experimental decorators and static class fields which reference the enclosing class name in their initializer. This affected top-level classes when bundling was enabled. Previously code that does this could crash because the class name wasn't initialized yet. This case should now be handled correctly:

      // Original code
      class Foo {
        @someDecorator
        static foo = 'foo'
        static bar = Foo.foo.length
      }
      
      // Old output
      const _Foo = class {
        static foo = "foo";
        static bar = _Foo.foo.length;
      };
      let Foo = _Foo;
      __decorateClass([
        someDecorator
      ], Foo, "foo", 2);
      
      // New output
      const _Foo = class _Foo {
        static foo = "foo";
        static bar = _Foo.foo.length;
      };
      __decorateClass([
        someDecorator
      ], _Foo, "foo", 2);
      let Foo = _Foo;
  23. 0.18.3

    15 Jun 2023
    • Fix a panic due to empty static class blocks

      This release fixes a bug where an internal invariant that was introduced in the previous release was sometimes violated, which then caused a panic. It happened when bundling code containing an empty static class block with both minification and bundling enabled.

  24. 0.18.2

    13 Jun 2023
    • Lower static blocks when static fields are lowered (#2800, #2950, #3025)

      This release fixes a bug where esbuild incorrectly did not lower static class blocks when static class fields needed to be lowered. For example, the following code should print 1 2 3 but previously printed 2 1 3 instead due to this bug:

      // Original code
      class Foo {
        static x = console.log(1)
        static { console.log(2) }
        static y = console.log(3)
      }
      
      // Old output (with --supported:class-static-field=false)
      class Foo {
        static {
          console.log(2);
        }
      }
      __publicField(Foo, "x", console.log(1));
      __publicField(Foo, "y", console.log(3));
      
      // New output (with --supported:class-static-field=false)
      class Foo {
      }
      __publicField(Foo, "x", console.log(1));
      console.log(2);
      __publicField(Foo, "y", console.log(3));
    • Use static blocks to implement --keep-names on classes

      This change fixes a bug where the name property could previously be incorrect within a class static context when using --keep-names. The problem was that the name property was being initialized after static blocks were run instead of before. This has been fixed by moving the name property initializer into a static block at the top of the class body:

      // Original code
      if (typeof Foo === 'undefined') {
        let Foo = class {
          static test = this.name
        }
        console.log(Foo.test)
      }
      
      // Old output (with --keep-names)
      if (typeof Foo === "undefined") {
        let Foo2 = /* @__PURE__ */ __name(class {
          static test = this.name;
        }, "Foo");
        console.log(Foo2.test);
      }
      
      // New output (with --keep-names)
      if (typeof Foo === "undefined") {
        let Foo2 = class {
          static {
            __name(this, "Foo");
          }
          static test = this.name;
        };
        console.log(Foo2.test);
      }

      This change was somewhat involved, especially regarding what esbuild considers to be side-effect free. Some unused classes that weren't removed by tree shaking in previous versions of esbuild may now be tree-shaken. One example is classes with static private fields that are transformed by esbuild into code that doesn't use JavaScript's private field syntax. Previously esbuild's tree shaking analysis ran on the class after syntax lowering, but with this release it will run on the class before syntax lowering, meaning it should no longer be confused by class mutations resulting from automatically-generated syntax lowering code.

  25. 0.18.1

    12 Jun 2023
    • Fill in null entries in input source maps

      If esbuild bundles input files with source maps and those source maps contain a sourcesContent array with null entries, esbuild previously copied those null entries over to the output source map. With this release, esbuild will now attempt to fill in those null entries by looking for a file on the file system with the corresponding name from the sources array. This matches esbuild's existing behavior that automatically generates the sourcesContent array from the file system if the entire sourcesContent array is missing.

    • Support /* @__KEY__ */ comments for mangling property names

      Property mangling is an advanced feature that enables esbuild to minify certain property names, even though it's not possible to automatically determine that it's safe to do so. The safe property names are configured via regular expression such as --mangle-props=_$ (mangle all properties ending in _).

      Sometimes it's desirable to also minify strings containing property names, even though it's not possible to automatically determine which strings are property names. This release makes it possible to do this by annotating those strings with /* @__KEY__ */. This is a convention that Terser added earlier this year, and which esbuild is now following too: #1365. Using it looks like this:

      // Original code
      console.log(
        [obj.mangle_, obj.keep],
        [obj.get('mangle_'), obj.get('keep')],
        [obj.get(/* @__KEY__ */ 'mangle_'), obj.get(/* @__KEY__ */ 'keep')],
      )
      
      // Old output (with --mangle-props=_$)
      console.log(
        [obj.a, obj.keep],
        [obj.get("mangle_"), obj.get("keep")],
        [obj.get(/* @__KEY__ */ "mangle_"), obj.get(/* @__KEY__ */ "keep")]
      );
      
      // New output (with --mangle-props=_$)
      console.log(
        [obj.a, obj.keep],
        [obj.get("mangle_"), obj.get("keep")],
        [obj.get(/* @__KEY__ */ "a"), obj.get(/* @__KEY__ */ "keep")]
      );
    • Support /* @__NO_SIDE_EFFECTS__ */ comments for functions

      Rollup has recently added support for /* @__NO_SIDE_EFFECTS__ */ annotations before functions to indicate that calls to these functions can be removed if the result is unused (i.e. the calls can be assumed to have no side effects). This release adds basic support for these to esbuild as well, which means esbuild will now parse these comments in input files and preserve them in output files. This should help people that use esbuild in combination with Rollup.

      Note that this doesn't necessarily mean esbuild will treat these calls as having no side effects, as esbuild's parallel architecture currently isn't set up to enable this type of cross-file tree-shaking information (tree-shaking decisions regarding a function call are currently local to the file they appear in). If you want esbuild to consider a function call to have no side effects, make sure you continue to annotate the function call with /* @__PURE__ */ (which is the previously-established convention for communicating this).

  26. 0.18.0

    9 Jun 2023
    • Add a way to try esbuild online

      There is now a way to try esbuild live on esbuild's website without installing it: esbuild.github.io/try/. In addition to being able to more easily evaluate esbuild, this should also make it more efficient to generate esbuild bug reports. For example, you can use it to compare the behavior of different versions of esbuild on the same input. The state of the page is stored in the URL for easy sharing. Many thanks to @hyrious for creating hyrious.me/esbuild-repl/, which was the main inspiration for this addition to esbuild's website.

      Two forms of build options are supported: either CLI-style (example) or JS-style (example). Both are converted into a JS object that's passed to esbuild's WebAssembly API. The CLI-style argument parser is a custom one that simulates shell quoting rules, and the JS-style argument parser is also custom and parses a superset of JSON (basically JSON5 + regular expressions). So argument parsing is an approximate simulation of what happens for real but hopefully it should be close enough.

    • Changes to esbuild's tsconfig.json support (#3019):

      This release makes the following changes to esbuild's tsconfig.json support:

      These changes are intended to improve esbuild's compatibility with tsc and reduce the number of unfortunate behaviors regarding tsconfig.json and esbuild.

    • Add a workaround for bugs in Safari 16.2 and earlier

      Safari's JavaScript parser had a bug (which has now been fixed) where at least something about unary/binary operators nested inside default arguments nested inside either a function or class expression was incorrectly considered a syntax error if that expression was the target of a property assignment. Here are some examples that trigger this Safari bug:

      ❱ x(function (y = -1) {}.z = 2)
      SyntaxError: Left hand side of operator '=' must be a reference.
      
      ❱ x(class { f(y = -1) {} }.z = 2)
      SyntaxError: Left hand side of operator '=' must be a reference.

      It's not clear what the exact conditions are that trigger this bug. However, a workaround for this bug appears to be to post-process your JavaScript to wrap any in function and class declarations that are the direct target of a property access expression in parentheses. That's the workaround that UglifyJS applies for this issue: mishoo/UglifyJS#2056. So that's what esbuild now does starting with this release:

      // Original code
      x(function (y = -1) {}.z = 2, class { f(y = -1) {} }.z = 2)
      
      // Old output (with --minify --target=safari16.2)
      x(function(c=-1){}.z=2,class{f(c=-1){}}.z=2);
      
      // New output (with --minify --target=safari16.2)
      x((function(c=-1){}).z=2,(class{f(c=-1){}}).z=2);

      This fix is not enabled by default. It's only enabled when --target= contains Safari 16.2 or earlier, such as with --target=safari16.2. You can also explicitly enable or disable this specific transform (called function-or-class-property-access) with --supported:function-or-class-property-access=false.

  27. 0.17.x
  28. 0.17.19

    13 May 2023
    • Fix CSS transform bugs with nested selectors that start with a combinator

      This release fixes several bugs regarding transforming nested CSS into non-nested CSS for older browsers. The bugs were due to lack of test coverage for nested selectors with more than one compound selector where they all start with the same combinator. Here's what some problematic cases look like before and after these fixes:

      /* Original code */
      .foo {
        > &a,
        > &b {
          color: red;
        }
      }
      .bar {
        > &a,
        + &b {
          color: green;
        }
      }
      
      /* Old output (with --target=chrome90) */
      .foo :is(> .fooa, > .foob) {
        color: red;
      }
      .bar :is(> .bara, + .barb) {
        color: green;
      }
      
      /* New output (with --target=chrome90) */
      .foo > :is(a.foo, b.foo) {
        color: red;
      }
      .bar > a.bar,
      .bar + b.bar {
        color: green;
      }
    • Fix bug with TypeScript parsing of instantiation expressions followed by =

      This release fixes esbuild's TypeScript-to-JavaScript conversion code in the case where a potential instantiation expression is followed immediately by a = token (such that the trailing > becomes a >= token). Previously esbuild considered that to still be an instantiation expression, but the official TypeScript compiler considered it to be a >= operator instead. This release changes esbuild's interpretation to match TypeScript. This edge case currently appears to be problematic for other TypeScript-to-JavaScript converters as well:

      Original codeTypeScriptesbuild 0.17.18esbuild 0.17.19SucraseBabel
      x<y>=a<b<c>>()x<y>=a();x=a();x<y>=a();x=a()Invalid left-hand side in assignment expression
    • Avoid removing unrecognized directives from the directive prologue when minifying

      The directive prologue in JavaScript is a sequence of top-level string expressions that come before your code. The only directives that JavaScript engines currently recognize are use strict and sometimes use asm. However, the people behind React have made up their own directive for their own custom dialect of JavaScript. Previously esbuild only preserved the use strict directive when minifying, although you could still write React JavaScript with esbuild using something like --banner:js="'your directive here';". With this release, you can now put arbitrary directives in the entry point and esbuild will preserve them in its minified output:

      // Original code
      'use wtf'; console.log(123)
      
      // Old output (with --minify)
      console.log(123);
      
      // New output (with --minify)
      "use wtf";console.log(123);

      Note that this means esbuild will no longer remove certain stray top-level strings when minifying. This behavior is an intentional change because these stray top-level strings are actually part of the directive prologue, and could potentially have semantics assigned to them (as was the case with React).

  29. 0.17.18

    22 Apr 2023
    • Fix non-default JSON import error with export {} from

      This release fixes a bug where esbuild incorrectly identified statements of the form export { default as x } from "y" assert { type: "json" } as a non-default import. The bug did not affect code of the form import { default as x } from ... (only code that used the export keyword).

    • Fix a crash with an invalid subpath import

      Previously esbuild could crash when attempting to generate a friendly error message for an invalid subpath import (i.e. an import starting with #). This happened because esbuild originally only supported the exports field and the code for that error message was not updated when esbuild later added support for the imports field. This crash has been fixed.

  30. 0.17.17

    16 Apr 2023
    • Fix CSS nesting transform for top-level &

      Previously esbuild could crash with a stack overflow when lowering CSS nesting rules with a top-level &, such as in the code below. This happened because esbuild's CSS nesting transform didn't handle top-level &, causing esbuild to inline the top-level selector into itself. This release handles top-level & by replacing it with the :scope pseudo-class:

      /* Original code */
      &,
      a {
        .b {
          color: red;
        }
      }
      
      /* New output (with --target=chrome90) */
      :is(:scope, a) .b {
        color: red;
      }
    • Support exports in package.json for extends in tsconfig.json

      TypeScript 5.0 added the ability to use extends in tsconfig.json to reference a path in a package whose package.json file contains an exports map that points to the correct location. This doesn't automatically work in esbuild because tsconfig.json affects esbuild's path resolution, so esbuild's normal path resolution logic doesn't apply.

      This release adds support for doing this by adding some additional code that attempts to resolve the extends path using the exports field. The behavior should be similar enough to esbuild's main path resolution logic to work as expected.

      Note that esbuild always treats this extends import as a require() import since that's what TypeScript appears to do. Specifically the require condition will be active and the import condition will be inactive.

    • Fix watch mode with NODE_PATH

      Node has a rarely-used feature where you can extend the set of directories that node searches for packages using the NODE_PATH environment variable. While esbuild supports this too, previously a bug prevented esbuild's watch mode from picking up changes to imported files that were contained directly in a NODE_PATH directory. You're supposed to use NODE_PATH for packages, but some people abuse this feature by putting files in that directory instead (e.g. node_modules/some-file.js instead of node_modules/some-pkg/some-file.js). The watch mode bug happens when you do this because esbuild first tries to read some-file.js as a directory and then as a file. Watch mode was incorrectly waiting for some-file.js to become a valid directory. This release fixes this edge case bug by changing watch mode to watch some-file.js as a file when this happens.

  31. 0.17.16

    10 Apr 2023
    • Fix CSS nesting transform for triple-nested rules that start with a combinator

      This release fixes a bug with esbuild where triple-nested CSS rules that start with a combinator were not transformed correctly for older browsers. Here's an example of such a case before and after this bug fix:

      /* Original input */
      .a {
        color: red;
        > .b {
          color: green;
          > .c {
            color: blue;
          }
        }
      }
      
      /* Old output (with --target=chrome90) */
      .a {
        color: red;
      }
      .a > .b {
        color: green;
      }
      .a .b > .c {
        color: blue;
      }
      
      /* New output (with --target=chrome90) */
      .a {
        color: red;
      }
      .a > .b {
        color: green;
      }
      .a > .b > .c {
        color: blue;
      }
    • Support --inject with a file loaded using the copy loader

      This release now allows you to use --inject with a file that is loaded using the copy loader. The copy loader copies the imported file to the output directory verbatim and rewrites the path in the import statement to point to the copied output file. When used with --inject, this means the injected file will be copied to the output directory as-is and a bare import statement for that file will be inserted in any non-copy output files that esbuild generates.

      Note that since esbuild doesn't parse the contents of copied files, esbuild will not expose any of the export names as usable imports when you do this (in the way that esbuild's --inject feature is typically used). However, any side-effects that the injected file has will still occur.

  32. 0.17.15

    1 Apr 2023
    • Allow keywords as type parameter names in mapped types

      TypeScript allows type keywords to be used as parameter names in mapped types. Previously esbuild incorrectly treated this as an error. Code that does this is now supported:

      type Foo = 'a' | 'b' | 'c'
      type A = { [keyof in Foo]: number }
      type B = { [infer in Foo]: number }
      type C = { [readonly in Foo]: number }
    • Add annotations for re-exported modules in node (#2486, #3029)

      Node lets you import named imports from a CommonJS module using ESM import syntax. However, the allowed names aren't derived from the properties of the CommonJS module. Instead they are derived from an arbitrary syntax-only analysis of the CommonJS module's JavaScript AST.

      To accommodate node doing this, esbuild's ESM-to-CommonJS conversion adds a special non-executable "annotation" for node that describes the exports that node should expose in this scenario. It takes the form 0 && (module.exports = { ... }) and comes at the end of the file (0 && expr means expr is never evaluated).

      Previously esbuild didn't do this for modules re-exported using the export * from syntax. Annotations for these re-exports will now be added starting with this release:

      // Original input
      export { foo } from './foo'
      export * from './bar'
      
      // Old output (with --format=cjs --platform=node)
      ...
      0 && (module.exports = {
        foo
      });
      
      // New output (with --format=cjs --platform=node)
      ...
      0 && (module.exports = {
        foo,
        ...require("./bar")
      });

      Note that you need to specify both --format=cjs and --platform=node to get these node-specific annotations.

    • Avoid printing an unnecessary space in between a number and a .

      JavaScript typically requires a space in between a number token and a . token to avoid the . being interpreted as a decimal point instead of a member expression. However, this space is not required if the number token itself contains a decimal point, an exponent, or uses a base other than 10. This release of esbuild now avoids printing the unnecessary space in these cases:

      // Original input
      foo(1000 .x, 0 .x, 0.1 .x, 0.0001 .x, 0xFFFF_0000_FFFF_0000 .x)
      
      // Old output (with --minify)
      foo(1e3 .x,0 .x,.1 .x,1e-4 .x,0xffff0000ffff0000 .x);
      
      // New output (with --minify)
      foo(1e3.x,0 .x,.1.x,1e-4.x,0xffff0000ffff0000.x);
  33. 0.17.14

    26 Mar 2023
    • Allow the TypeScript 5.0 const modifier in object type declarations

      The new TypeScript 5.0 const modifier was added to esbuild in version 0.17.5, and works with classes, functions, and arrow expressions. However, support for it wasn't added to object type declarations (e.g. interfaces) due to an oversight. This release adds support for these cases, so the following TypeScript 5.0 code can now be built with esbuild:

      interface Foo { <const T>(): T }
      type Bar = { new <const T>(): T }
    • Implement preliminary lowering for CSS nesting

      Chrome has implemented the new CSS nesting specification in version 112, which is currently in beta but will become stable very soon. So CSS nesting is now a part of the web platform!

      This release of esbuild can now transform nested CSS syntax into non-nested CSS syntax for older browsers. The transformation relies on the :is() pseudo-class in many cases, so the transformation is only guaranteed to work when targeting browsers that support :is() (e.g. Chrome 88+). You'll need to set esbuild's target to the browsers you intend to support to tell esbuild to do this transformation. You will get a warning if you use CSS nesting syntax with a target which includes older browsers that don't support :is().

      The lowering transformation looks like this:

      /* Original input */
      a.btn {
        color: #333;
        &:hover { color: #444 }
        &:active { color: #555 }
      }
      
      /* New output (with --target=chrome88) */
      a.btn {
        color: #333;
      }
      a.btn:hover {
        color: #444;
      }
      a.btn:active {
        color: #555;
      }

      More complex cases may generate the :is() pseudo-class:

      /* Original input */
      div, p {
        .warning, .error {
          padding: 20px;
        }
      }
      
      /* New output (with --target=chrome88) */
      :is(div, p) :is(.warning, .error) {
        padding: 20px;
      }

      In addition, esbuild now has a special warning message for nested style rules that start with an identifier. This isn't allowed in CSS because the syntax would be ambiguous with the existing declaration syntax. The new warning message looks like this:

      ▲ [WARNING] A nested style rule cannot start with "p" because it looks like the start of a declaration [css-syntax-error]
      
          <stdin>:1:7:
            1 │ main { p { margin: auto } }
              │        ^
              ╵        :is(p)
      
        To start a nested style rule with an identifier, you need to wrap the identifier in ":is(...)" to
        prevent the rule from being parsed as a declaration.

      Keep in mind that the transformation in this release is a preliminary implementation. CSS has many features that interact in complex ways, and there may be some edge cases that don't work correctly yet.

    • Minification now removes unnecessary & CSS nesting selectors

      This release introduces the following CSS minification optimizations:

      /* Original input */
      a {
        font-weight: bold;
        & {
          color: blue;
        }
        & :hover {
          text-decoration: underline;
        }
      }
      
      /* Old output (with --minify) */
      a{font-weight:700;&{color:#00f}& :hover{text-decoration:underline}}
      
      /* New output (with --minify) */
      a{font-weight:700;:hover{text-decoration:underline}color:#00f}
  34. 0.17.13

    24 Mar 2023
    • Work around an issue with NODE_PATH and Go's WebAssembly internals

      Go's WebAssembly implementation returns EINVAL instead of ENOTDIR when using the readdir syscall on a file. This messes up esbuild's implementation of node's module resolution algorithm since encountering ENOTDIR causes esbuild to continue its search (since it's a normal condition) while other encountering other errors causes esbuild to fail with an I/O error (since it's an unexpected condition). You can encounter this issue in practice if you use node's legacy NODE_PATH feature to tell esbuild to resolve node modules in a custom directory that was not installed by npm. This release works around this problem by converting EINVAL into ENOTDIR for the readdir syscall.

    • Fix a minification bug with CSS @layer rules that have parsing errors

      CSS at-rules require either a {} block or a semicolon at the end. Omitting both of these causes esbuild to treat the rule as an unknown at-rule. Previous releases of esbuild had a bug that incorrectly removed unknown at-rules without any children during minification if the at-rule token matched an at-rule that esbuild can handle. Specifically cssnano can generate @layer rules with parsing errors, and empty @layer rules cannot be removed because they have side effects (@layer didn't exist when esbuild's CSS support was added, so esbuild wasn't written to handle this). This release changes esbuild to no longer discard @layer rules with parsing errors when minifying (the rule @layer c has a parsing error):

      /* Original input */
      @layer a {
        @layer b {
          @layer c
        }
      }
      
      /* Old output (with --minify) */
      @layer a.b;
      
      /* New output (with --minify) */
      @layer a.b.c;
    • Unterminated strings in CSS are no longer an error

      The CSS specification provides rules for handling parsing errors. One of those rules is that user agents must close strings upon reaching the end of a line (i.e., before an unescaped line feed, carriage return or form feed character), but then drop the construct (declaration or rule) in which the string was found. For example:

      p {
        color: green;
        font-family: 'Courier New Times
        color: red;
        color: green;
      }

      ...would be treated the same as:

      p { color: green; color: green; }

      ...because the second declaration (from font-family to the semicolon after color: red) is invalid and is dropped.

      Previously using this CSS with esbuild failed to build due to a syntax error, even though the code can be interpreted by a browser. With this release, the code now produces a warning instead of an error, and esbuild prints the invalid CSS such that it stays invalid in the output:

      /* esbuild's new non-minified output: */
      p {
        color: green;
        font-family: 'Courier New Times
        color: red;
        color: green;
      }
      /* esbuild's new minified output: */
      p{font-family:'Courier New Times
      color: red;color:green}
  35. 0.17.12

    17 Mar 2023
    • Fix a crash when parsing inline TypeScript decorators

      Previously esbuild's TypeScript parser crashed when parsing TypeScript decorators if the definition of the decorator was inlined into the decorator itself:

      @(function sealed(constructor: Function) {
        Object.seal(constructor);
        Object.seal(constructor.prototype);
      })
      class Foo {}

      This crash was not noticed earlier because this edge case did not have test coverage. The crash is fixed in this release.

  36. 0.17.11

    3 Mar 2023
    • Fix the alias feature to always prefer the longest match

      It's possible to configure conflicting aliases such as --alias:a=b and --alias:a/c=d, which is ambiguous for the import path a/c/x (since it could map to either b/c/x or d/x). Previously esbuild would pick the first matching alias, which would non-deterministically pick between one of the possible matches. This release fixes esbuild to always deterministically pick the longest possible match.

    • Minify calls to some global primitive constructors

      With this release, esbuild's minifier now replaces calls to Boolean/Number/String/BigInt with equivalent shorter code when relevant:

      // Original code
      console.log(
        Boolean(a ? (b | c) !== 0 : (c & d) !== 0),
        Number(e ? '1' : '2'),
        String(e ? '1' : '2'),
        BigInt(e ? 1n : 2n),
      )
      
      // Old output (with --minify)
      console.log(Boolean(a?(b|c)!==0:(c&d)!==0),Number(e?"1":"2"),String(e?"1":"2"),BigInt(e?1n:2n));
      
      // New output (with --minify)
      console.log(!!(a?b|c:c&d),+(e?"1":"2"),e?"1":"2",e?1n:2n);
    • Adjust some feature compatibility tables for node

      This release makes the following adjustments to esbuild's internal feature compatibility tables for node, which tell esbuild which versions of node are known to support all aspects of that feature:

      Each of these adjustments was identified by comparing against data from the node-compat-table package and was manually verified using old node executables downloaded from nodejs.org/download/release/.

  37. 0.17.10

    20 Feb 2023
    • Update esbuild's handling of CSS nesting to match the latest specification changes

      The syntax for the upcoming CSS nesting feature has recently changed. The @nest prefix that was previously required in some cases is now gone, and nested rules no longer have to start with & (as long as they don't start with an identifier or function token).

      This release updates esbuild's pass-through handling of CSS nesting syntax to match the latest specification changes. So you can now use esbuild to bundle CSS containing nested rules and try them out in a browser that supports CSS nesting (which includes nightly builds of both Chrome and Safari).

      However, I'm not implementing lowering of nested CSS to non-nested CSS for older browsers yet. While the syntax has been decided, the semantics are still in flux. In particular, there is still some debate about changing the fundamental way that CSS nesting works. For example, you might think that the following CSS is equivalent to a .outer .inner button { ... } rule:

      .inner button {
        .outer & {
          color: red;
        }
      }

      But instead it's actually equivalent to a .outer :is(.inner button) { ... } rule which unintuitively also matches the following DOM structure:

      <div class="inner">
        <div class="outer">
          <button></button>
        </div>
      </div>

      The :is() behavior is preferred by browser implementers because it's more memory-efficient, but the straightforward translation into a .outer .inner button { ... } rule is preferred by developers used to the existing CSS preprocessing ecosystem (e.g. SASS). It seems premature to commit esbuild to specific semantics for this syntax at this time given the ongoing debate.

    • Fix cross-file CSS rule deduplication involving url() tokens

      Previously cross-file CSS rule deduplication didn't handle url() tokens correctly. These tokens contain references to import paths which may be internal (i.e. in the bundle) or external (i.e. not in the bundle). When comparing two url() tokens for equality, the underlying import paths should be compared instead of their references. This release of esbuild fixes url() token comparisons. One side effect is that @font-face rules should now be deduplicated correctly across files:

      /* Original code */
      @import "data:text/css, \
        @import 'http://example.com/style.css'; \
        @font-face { src: url(http://example.com/font.ttf) }";
      @import "data:text/css, \
        @font-face { src: url(http://example.com/font.ttf) }";
      
      /* Old output (with --bundle --minify) */
      @import"http://example.com/style.css";@font-face{src:url(http://example.com/font.ttf)}@font-face{src:url(http://example.com/font.ttf)}
      
      /* New output (with --bundle --minify) */
      @import"http://example.com/style.css";@font-face{src:url(http://example.com/font.ttf)}
  38. 0.17.9

    19 Feb 2023
    • Parse rest bindings in TypeScript types

      Previously esbuild was unable to parse the following valid TypeScript code:

      let tuple: (...[e1, e2, ...es]: any) => any

      This release includes support for parsing code like this.

    • Fix TypeScript code translation for certain computed declare class fields

      In TypeScript, the key of a computed declare class field should only be preserved if there are no decorators for that field. Previously esbuild always preserved the key, but esbuild will now remove the key to match the output of the TypeScript compiler:

      // Original code
      declare function dec(a: any, b: any): any
      declare const removeMe: unique symbol
      declare const keepMe: unique symbol
      class X {
          declare [removeMe]: any
          @dec declare [keepMe]: any
      }
      
      // Old output
      var _a;
      class X {
      }
      removeMe, _a = keepMe;
      __decorateClass([
        dec
      ], X.prototype, _a, 2);
      
      // New output
      var _a;
      class X {
      }
      _a = keepMe;
      __decorateClass([
        dec
      ], X.prototype, _a, 2);
    • Fix a crash with path resolution error generation

      In certain situations, a module containing an invalid import path could previously cause esbuild to crash when it attempts to generate a more helpful error message. This crash has been fixed.

  39. 0.17.8

    13 Feb 2023
    • Fix a minification bug with non-ASCII identifiers

      This release fixes a bug with esbuild where non-ASCII identifiers followed by a keyword were incorrectly not separated by a space. This bug affected both the in and instanceof keywords. Here's an example of the fix:

      // Original code
      π in a
      
      // Old output (with --minify --charset=utf8)
      πin a;
      
      // New output (with --minify --charset=utf8)
      π in a;
    • Fix a regression with esbuild's WebAssembly API in version 0.17.6

      Version 0.17.6 of esbuild updated the Go toolchain to version 1.20.0. This had the unfortunate side effect of increasing the amount of stack space that esbuild uses (presumably due to some changes to Go's WebAssembly implementation) which could cause esbuild's WebAssembly-based API to crash with a stack overflow in cases where it previously didn't crash. One such case is the package grapheme-splitter which contains code that looks like this:

      if (
        (0x0300 <= code && code <= 0x036F) ||
        (0x0483 <= code && code <= 0x0487) ||
        (0x0488 <= code && code <= 0x0489) ||
        (0x0591 <= code && code <= 0x05BD) ||
        // ... many hundreds of lines later ...
      ) {
        return;
      }

      This edge case involves a chain of binary operators that results in an AST over 400 nodes deep. Normally this wouldn't be a problem because Go has growable call stacks, so the call stack would just grow to be as large as needed. However, WebAssembly byte code deliberately doesn't expose the ability to manipulate the stack pointer, so Go's WebAssembly translation is forced to use the fixed-size WebAssembly call stack. So esbuild's WebAssembly implementation is vulnerable to stack overflow in cases like these.

      It's not unreasonable for this to cause a stack overflow, and for esbuild's answer to this problem to be "don't write code like this." That's how many other AST-manipulation tools handle this problem. However, it's possible to implement AST traversal using iteration instead of recursion to work around limited call stack space. This version of esbuild implements this code transformation for esbuild's JavaScript parser and printer, so esbuild's WebAssembly implementation is now able to process the grapheme-splitter package (at least when compiled with Go 1.20.0 and run with node's WebAssembly implementation).

  40. 0.17.7

    9 Feb 2023
    • Change esbuild's parsing of TypeScript instantiation expressions to match TypeScript 4.8+

      This release updates esbuild's implementation of instantiation expression erasure to match microsoft/TypeScript#49353. The new rules are as follows (copied from TypeScript's PR description):

      When a potential type argument list is followed by

      • a line break,

      • an ( token,

      • a template literal string, or

      • any token except < or > that isn't the start of an expression,

      we consider that construct to be a type argument list. Otherwise we consider the construct to be a < relational expression followed by a > relational expression.

    • Ignore sideEffects: false for imported CSS files (#1370, #1458, #2905)

      This release ignores the sideEffects annotation in package.json for CSS files that are imported into JS files using esbuild's css loader. This means that these CSS files are no longer be tree-shaken.

      Importing CSS into JS causes esbuild to automatically create a CSS entry point next to the JS entry point containing the bundled CSS. Previously packages that specified some form of "sideEffects": false could potentially cause esbuild to consider one or more of the JS files on the import path to the CSS file to be side-effect free, which would result in esbuild removing that CSS file from the bundle. This was problematic because the removal of that CSS is outwardly observable, since all CSS is global, so it was incorrect for previous versions of esbuild to tree-shake CSS files imported into JS files.

    • Add constant folding for certain additional equality cases (#2394, #2895)

      This release adds constant folding for expressions similar to the following:

      // Original input
      console.log(
        null === 'foo',
        null === undefined,
        null == undefined,
        false === 0,
        false == 0,
        1 === true,
        1 == true,
      )
      
      // Old output
      console.log(
        null === "foo",
        null === void 0,
        null == void 0,
        false === 0,
        false == 0,
        1 === true,
        1 == true
      );
      
      // New output
      console.log(
        false,
        false,
        true,
        false,
        true,
        false,
        true
      );
  41. 0.17.6

    6 Feb 2023
    • Fix a CSS parser crash on invalid CSS

      Previously the following invalid CSS caused esbuild's parser to crash:

      @media screen

      The crash was caused by trying to construct a helpful error message assuming that there was an opening { token, which is not the case here. This release fixes the crash.

    • Inline TypeScript enums that are referenced before their declaration

      Previously esbuild inlined enums within a TypeScript file from top to bottom, which meant that references to TypeScript enum members were only inlined within the same file if they came after the enum declaration. With this release, esbuild will now inline enums even when they are referenced before they are declared:

      // Original input
      export const foo = () => Foo.FOO
      const enum Foo { FOO = 0 }
      
      // Old output (with --tree-shaking=true)
      export const foo = () => Foo.FOO;
      var Foo = /* @__PURE__ */ ((Foo2) => {
        Foo2[Foo2["FOO"] = 0] = "FOO";
        return Foo2;
      })(Foo || {});
      
      // New output (with --tree-shaking=true)
      export const foo = () => 0 /* FOO */;

      This makes esbuild's TypeScript output smaller and faster when processing code that does this. I noticed this issue when I ran the TypeScript compiler's source code through esbuild's bundler. Now that the TypeScript compiler is going to be bundled with esbuild in the upcoming TypeScript 5.0 release, improvements like this will also improve the TypeScript compiler itself!

    • Fix esbuild installation on Arch Linux (#2785, #2812, #2865)

      Someone made an unofficial esbuild package for Linux that adds the ESBUILD_BINARY_PATH=/usr/bin/esbuild environment variable to the user's default environment. This breaks all npm installations of esbuild for users with this unofficial Linux package installed, which has affected many people. Most (all?) people who encounter this problem haven't even installed this unofficial package themselves; instead it was installed for them as a dependency of another Linux package. The problematic change to add the ESBUILD_BINARY_PATH environment variable was reverted in the latest version of this unofficial package. However, old versions of this unofficial package are still there and will be around forever. With this release, ESBUILD_BINARY_PATH is now ignored by esbuild's install script when it's set to the value /usr/bin/esbuild. This should unbreak using npm to install esbuild in these problematic Linux environments.

      Note: The ESBUILD_BINARY_PATH variable is an undocumented way to override the location of esbuild's binary when esbuild's npm package is installed, which is necessary to substitute your own locally-built esbuild binary when debugging esbuild's npm package. It's only meant for very custom situations and should absolutely not be forced on others by default, especially without their knowledge. I may remove the code in esbuild's installer that reads ESBUILD_BINARY_PATH in the future to prevent these kinds of issues. It will unfortunately make debugging esbuild harder. If ESBUILD_BINARY_PATH is ever removed, it will be done in a "breaking change" release.

  42. 0.17.5

    27 Jan 2023
    • Parse const type parameters from TypeScript 5.0

      The TypeScript 5.0 beta announcement adds const type parameters to the language. You can now add the const modifier on a type parameter of a function, method, or class like this:

      type HasNames = { names: readonly string[] };
      const getNamesExactly = <const T extends HasNames>(arg: T): T["names"] => arg.names;
      const names = getNamesExactly({ names: ["Alice", "Bob", "Eve"] });

      The type of names in the above example is readonly ["Alice", "Bob", "Eve"]. Marking the type parameter as const behaves as if you had written as const at every use instead. The above code is equivalent to the following TypeScript, which was the only option before TypeScript 5.0:

      type HasNames = { names: readonly string[] };
      const getNamesExactly = <T extends HasNames>(arg: T): T["names"] => arg.names;
      const names = getNamesExactly({ names: ["Alice", "Bob", "Eve"] } as const);

      You can read the announcement for more information.

    • Make parsing generic async arrow functions more strict in .tsx files

      Previously esbuild's TypeScript parser incorrectly accepted the following code as valid:

      let fn = async <T> () => {};

      The official TypeScript parser rejects this code because it thinks it's the identifier async followed by a JSX element starting with <T>. So with this release, esbuild will now reject this syntax in .tsx files too. You'll now have to add a comma after the type parameter to get generic arrow functions like this to parse in .tsx files:

      let fn = async <T,> () => {};
    • Allow the in and out type parameter modifiers on class expressions

      TypeScript 4.7 added the in and out modifiers on the type parameters of classes, interfaces, and type aliases. However, while TypeScript supported them on both class expressions and class statements, previously esbuild only supported them on class statements due to an oversight. This release now allows these modifiers on class expressions too:

      declare let Foo: any;
      Foo = class <in T> { };
      Foo = class <out T> { };
  43. 0.17.4

    22 Jan 2023
    • Implement HTTP HEAD requests in serve mode

      Previously esbuild's serve mode only responded to HTTP GET requests. With this release, esbuild's serve mode will also respond to HTTP HEAD requests, which are just like HTTP GET requests except that the body of the response is omitted.

    • Permit top-level await in dead code branches

      Adding top-level await to a file has a few consequences with esbuild:

      This release relaxes these rules slightly: rules 2 and 3 will now no longer apply when esbuild has identified the code branch as dead code, such as when it's behind an if (false) check. This should make it possible to use esbuild to convert code into different output formats that only uses top-level await conditionally. This release does not relax rule 1. Top-level await will still cause esbuild to unconditionally consider the input module format to be ESM, even when the top-level await is in a dead code branch. This is necessary because whether the input format is ESM or not affects the whole file, not just the dead code branch.

    • Fix entry points where the entire file name is the extension

      Previously if you passed esbuild an entry point where the file extension is the entire file name, esbuild would use the parent directory name to derive the name of the output file. For example, if you passed esbuild a file ./src/.ts then the output name would be src.js. This bug happened because esbuild first strips the file extension to get ./src/ and then joins the path with the working directory to get the absolute path (e.g. join("/working/dir", "./src/") gives /working/dir/src). However, the join operation also canonicalizes the path which strips the trailing /. Later esbuild uses the "base name" operation to extract the name of the output file. Since there is no trailing /, esbuild returns "src" as the base name instead of "", which causes esbuild to incorrectly include the directory name in the output file name. This release fixes this bug by deferring the stripping of the file extension until after all path manipulations have been completed. So now the file ./src/.ts will generate an output file named .js.

  44. 0.17.3

    18 Jan 2023
    • Fix incorrect CSS minification for certain rules

      Certain rules such as @media could previously be minified incorrectly. Due to a typo in the duplicate rule checker, two known @-rules that share the same hash code were incorrectly considered to be equal. This problem was made worse by the rule hashing code considering two unknown declarations (such as CSS variables) to have the same hash code, which also isn't optimal from a performance perspective. Both of these issues have been fixed:

      /* Original input */
      @media (prefers-color-scheme: dark) { body { --VAR-1: #000; } }
      @media (prefers-color-scheme: dark) { body { --VAR-2: #000; } }
      
      /* Old output (with --minify) */
      @media (prefers-color-scheme: dark){body{--VAR-2: #000}}
      
      /* New output (with --minify) */
      @media (prefers-color-scheme: dark){body{--VAR-1: #000}}@media (prefers-color-scheme: dark){body{--VAR-2: #000}}
  45. 0.17.2

    17 Jan 2023
    • Add onDispose to the plugin API (#2140, #2205)

      If your plugin wants to perform some cleanup after it's no longer going to be used, you can now use the onDispose API to register a callback for cleanup-related tasks. For example, if a plugin starts a long-running child process then it may want to terminate that process when the plugin is discarded. Previously there was no way to do this. Here's an example:

      let examplePlugin = {
        name: 'example',
        setup(build) {
          build.onDispose(() => {
            console.log('This plugin is no longer used')
          })
        },
      }

      These onDispose callbacks will be called after every build() call regardless of whether the build failed or not as well as after the first dispose() call on a given build context.

  46. 0.17.1

    16 Jan 2023
    • Make it possible to cancel a build

      The context object introduced in version 0.17.0 has a new cancel() method. You can use it to cancel a long-running build so that you can start a new one without needing to wait for the previous one to finish. When this happens, the previous build should always have at least one error and have no output files (i.e. it will be a failed build).

      Using it might look something like this:

      This API is a quick implementation and isn't maximally efficient, so the build may continue to do some work for a little bit before stopping. For example, I have added stop points between each top-level phase of the bundler and in the main module graph traversal loop, but I haven't added fine-grained stop points within the internals of the linker. How quickly esbuild stops can be improved in future releases. This means you'll want to wait for cancel() and/or the previous rebuild() to finish (i.e. await the returned promise in JavaScript) before starting a new build, otherwise rebuild() will give you the just-canceled build that still hasn't ended yet. Note that onEnd callbacks will still be run regardless of whether or not the build was canceled.

    • Fix server-sent events without servedir

      The server-sent events for live reload were incorrectly using servedir to calculate the path to modified output files. This means events couldn't be sent when servedir wasn't specified. This release uses the internal output directory (which is always present) instead of servedir (which might be omitted), so live reload should now work when servedir is not specified.

    • Custom entry point output paths now work with the copy loader

      Entry points can optionally provide custom output paths to change the path of the generated output file. For example, esbuild foo=abc.js bar=xyz.js --outdir=out generates the files out/foo.js and out/bar.js. However, this previously didn't work when using the copy loader due to an oversight. This bug has been fixed. For example, you can now do esbuild foo=abc.html bar=xyz.html --outdir=out --loader:.html=copy to generate the files out/foo.html and out/bar.html.

  47. 0.17.0

    14 Jan 2023
    • Move everything related to incremental builds to a new context API (#1037, #1606, #2280, #2418)

      This change removes the incremental and watch options as well as the serve() method, and introduces a new context() method. The context method takes the same arguments as the build() method but only validates its arguments and does not do an initial build. Instead, builds can be triggered using the rebuild(), watch(), and serve() methods on the returned context object. The new context API looks like this:

      // Create a context for incremental builds
      const context = await esbuild.context({
        entryPoints: ['app.ts'],
        bundle: true,
      })
      
      // Manually do an incremental build
      const result = await context.rebuild()
      
      // Enable watch mode
      await context.watch()
      
      // Enable serve mode
      await context.serve()
      
      // Dispose of the context
      context.dispose()

      The switch to the context API solves a major issue with the previous API which is that if the initial build fails, a promise is thrown in JavaScript which prevents you from accessing the returned result object. That prevented you from setting up long-running operations such as watch mode when the initial build contained errors. It also makes tearing down incremental builds simpler as there is now a single way to do it instead of three separate ways.

      In addition, this release also makes some subtle changes to how incremental builds work. Previously every call to rebuild() started a new build. If you weren't careful, then builds could actually overlap. This doesn't cause any problems with esbuild itself, but could potentially cause problems with plugins (esbuild doesn't even give you a way to identify which overlapping build a given plugin callback is running on). Overlapping builds also arguably aren't useful, or at least aren't useful enough to justify the confusion and complexity that they bring. With this release, there is now only ever a single active build per context. Calling rebuild() before the previous rebuild has finished now "merges" with the existing rebuild instead of starting a new build.

    • Allow using watch and serve together (#805, #1650, #2576)

      Previously it was not possible to use watch mode and serve mode together. The rationale was that watch mode is one way of automatically rebuilding your project and serve mode is another (since serve mode automatically rebuilds on every request). However, people want to combine these two features to make "live reloading" where the browser automatically reloads the page when files are changed on the file system.

      This release now allows you to use these two features together. You can only call the watch() and serve() APIs once each per context, but if you call them together on the same context then esbuild will automatically rebuild both when files on the file system are changed and when the server serves a request.

    • Support "live reloading" through server-sent events

      Server-sent events are a simple way to pass one-directional messages asynchronously from the server to the client. Serve mode now provides a /esbuild endpoint with an change event that triggers every time esbuild's output changes. So you can now implement simple "live reloading" (i.e. reloading the page when a file is edited and saved) like this:

      new EventSource('/esbuild').addEventListener('change', () => location.reload())

      The event payload is a JSON object with the following shape:

      interface ChangeEvent {
        added: string[]
        removed: string[]
        updated: string[]
      }

      This JSON should also enable more complex live reloading scenarios. For example, the following code hot-swaps changed CSS <link> tags in place without reloading the page (but still reloads when there are other types of changes):

      new EventSource('/esbuild').addEventListener('change', e => {
        const { added, removed, updated } = JSON.parse(e.data)
        if (!added.length && !removed.length && updated.length === 1) {
          for (const link of document.getElementsByTagName("link")) {
            const url = new URL(link.href)
            if (url.host === location.host && url.pathname === updated[0]) {
              const next = link.cloneNode()
              next.href = updated[0] + '?' + Math.random().toString(36).slice(2)
              next.onload = () => link.remove()
              link.parentNode.insertBefore(next, link.nextSibling)
              return
            }
          }
        }
        location.reload()
      })

      Implementing live reloading like this has a few known caveats:

  48. 0.16.x
  49. 0.16.17

    11 Jan 2023
    • Fix additional comment-related regressions

      This release fixes more edge cases where the new comment preservation behavior that was added in 0.16.14 could introduce syntax errors. Specifically:

      x = () => (/* comment */ {})
      for ((/* comment */ let).x of y) ;
      function *f() { yield (/* comment */class {}) }

      These cases caused esbuild to generate code with a syntax error in version 0.16.14 or above. These bugs have now been fixed.

  50. 0.16.16

    8 Jan 2023
    • Fix a regression caused by comment preservation

      The new comment preservation behavior that was added in 0.16.14 introduced a regression where comments in certain locations could cause esbuild to omit certain necessary parentheses in the output. The outermost parentheses were incorrectly removed for the following syntax forms, which then introduced syntax errors:

      (/* comment */ { x: 0 }).x;
      (/* comment */ function () { })();
      (/* comment */ class { }).prototype;

      This regression has been fixed.

  51. 0.16.15

    7 Jan 2023
    • Add format to input files in the JSON metafile data

      When --metafile is enabled, input files may now have an additional format field that indicates the export format used by this file. When present, the value will either be cjs for CommonJS-style exports or esm for ESM-style exports. This can be useful in bundle analysis.

      For example, esbuild's new Bundle Size Analyzer now uses this information to visualize whether ESM or CommonJS was used for each directory and file of source code (click on the CJS/ESM bar at the top).

      This information is helpful when trying to reduce the size of your bundle. Using the ESM variant of a dependency instead of the CommonJS variant always results in a faster and smaller bundle because it omits CommonJS wrappers, and also may result in better tree-shaking as it allows esbuild to perform tree-shaking at the statement level instead of the module level.

    • Fix a bundling edge case with dynamic import

      This release fixes a bug where esbuild's bundler could produce incorrect output. The problematic edge case involves the entry point importing itself using a dynamic import() expression in an imported file, like this:

      // src/a.js
      export const A = 42;
      
      // src/b.js
      export const B = async () => (await import(".")).A
      
      // src/index.js
      export * from "./a"
      export * from "./b"
    • Remove new type syntax from type declarations in the esbuild package

      Previously you needed to use TypeScript 4.3 or newer when using the esbuild package from TypeScript code due to the use of a getter in an interface in node_modules/esbuild/lib/main.d.ts. This release removes this newer syntax to allow people with versions of TypeScript as far back as TypeScript 3.5 to use this latest version of the esbuild package. Here is change that was made to esbuild's type declarations:

       export interface OutputFile {
         /** "text" as bytes */
         contents: Uint8Array;
         /** "contents" as text (changes automatically with "contents") */
      -  get text(): string;
      +  readonly text: string;
       }
  52. 0.16.14

    4 Jan 2023
    • Preserve some comments in expressions

      Various tools give semantic meaning to comments embedded inside of expressions. For example, Webpack and Vite have special "magic comments" that can be used to affect code splitting behavior:

      import(/* webpackChunkName: "foo" */ '../foo');
      import(/* @vite-ignore */ dynamicVar);
      new Worker(/* webpackChunkName: "bar" */ new URL("../bar.ts", import.meta.url));
      new Worker(new URL('./path', import.meta.url), /* @vite-ignore */ dynamicOptions);

      Since esbuild can be used as a preprocessor for these tools (e.g. to strip TypeScript types), it can be problematic if esbuild doesn't do additional work to try to retain these comments. Previously esbuild special-cased Webpack comments in these specific locations in the AST. But Vite would now like to use similar comments, and likely other tools as well.

      So with this release, esbuild now will attempt to preserve some comments inside of expressions in more situations than before. This behavior is mainly intended to preserve these special "magic comments" that are meant for other tools to consume, although esbuild will no longer only preserve Webpack-specific comments so it should now be tool-agnostic. There is no guarantee that all such comments will be preserved (especially when --minify-syntax is enabled). So this change does not mean that esbuild is now usable as a code formatter. In particular comment preservation is more likely to happen with leading comments than with trailing comments. You should put comments that you want to be preserved before the relevant expression instead of after it. Also note that this change does not retain any more statement-level comments than before (i.e. comments not embedded inside of expressions). Comment preservation is not enabled when --minify-whitespace is enabled (which is automatically enabled when you use --minify).

  53. 0.16.13

    2 Jan 2023
    • Publish a new bundle visualization tool

      While esbuild provides bundle metadata via the --metafile flag, previously esbuild left analysis of it completely up to third-party tools (well, outside of the rudimentary --analyze flag). However, the esbuild website now has a built-in bundle visualization tool:

      You can pass --metafile to esbuild to output bundle metadata, then upload that JSON file to this tool to visualize your bundle. This is helpful for answering questions such as:

      I'm publishing this tool because I think esbuild should provide some answer to "how do I visualize my bundle" without requiring people to reach for third-party tools. At the moment the tool offers two types of visualizations: a radial "sunburst chart" and a linear "flame chart". They serve slightly different but overlapping use cases (e.g. the sunburst chart is more keyboard-accessible while the flame chart is easier with the mouse). This tool may continue to evolve over time.

    • Fix --metafile and --mangle-cache with --watch

      The CLI calls the Go API and then also writes out the metafile and/or mangle cache JSON files if those features are enabled. This extra step is necessary because these files are returned by the Go API as in-memory strings. However, this extra step accidentally didn't happen for all builds after the initial build when watch mode was enabled. This behavior used to work but it was broken in version 0.14.18 by the introduction of the mangle cache feature. This release fixes the combination of these features, so the metafile and mangle cache features should now work with watch mode. This behavior was only broken for the CLI, not for the JS or Go APIs.

    • Add an original field to the metafile

      The metadata file JSON now has an additional field: each import in an input file now contains the pre-resolved path in the original field in addition to the post-resolved path in the path field. This means it's now possible to run certain additional analysis over your bundle. For example, you should be able to use this to detect when the same package subpath is represented multiple times in the bundle, either because multiple versions of a package were bundled or because a package is experiencing the dual-package hazard.

  54. 0.16.12

    28 Dec 2022
    • Loader defaults to js for extensionless files

      Certain packages contain files without an extension. For example, the yargs package contains the file yargs/yargs which has no extension. Node, Webpack, and Parcel can all understand code that imports yargs/yargs because they assume that the file is JavaScript. However, esbuild was previously unable to understand this code because it relies on the file extension to tell it how to interpret the file. With this release, esbuild will now assume files without an extension are JavaScript files. This can be customized by setting the loader for "" (the empty string, representing files without an extension) to another loader. For example, if you want files without an extension to be treated as CSS instead, you can do that like this:

      In addition, the "type" field in package.json files now only applies to files with an explicit .js, .jsx, .ts, or .tsx extension. Previously it was incorrectly applied by esbuild to all files that had an extension other than .mjs, .mts, .cjs, or .cts including extensionless files. So for example an extensionless file in a "type": "module" package is now treated as CommonJS instead of ESM.

A whole project to check? Paste its package.json in the dependency check: every deprecated, outdated or vulnerable dependency, with what to upgrade to. Free, no account.