evanw/esbuild
### [`v0.14.10`](https://togithub.com/evanw/esbuild/blob/HEAD/CHANGELOG.md#01410)
[Compare Source](https://togithub.com/evanw/esbuild/compare/v0.14.9...v0.14.10)
- Enable tree shaking of classes with lowered static fields ([#175](https://togithub.com/evanw/esbuild/issues/175))
If the configured target environment doesn't support static class fields, they are converted into a call to esbuild's `__publicField` function instead. However, esbuild's tree-shaking pass treated this call as a side effect, which meant that all classes with static fields were ineligible for tree shaking. This release fixes the problem by explicitly ignoring calls to the `__publicField` function during tree shaking side-effect determination. Tree shaking is now enabled for these classes:
```js
// Original code
class Foo { static foo = 'foo' }
class Bar { static bar = 'bar' }
new Bar()
// Old output (with --tree-shaking=true --target=es6)
class Foo {
}
__publicField(Foo, "foo", "foo");
class Bar {
}
__publicField(Bar, "bar", "bar");
new Bar();
// New output (with --tree-shaking=true --target=es6)
class Bar {
}
__publicField(Bar, "bar", "bar");
new Bar();
```
- Treat `--define:foo=undefined` as an undefined literal instead of an identifier ([#1407](https://togithub.com/evanw/esbuild/issues/1407))
References to the global variable `undefined` are automatically replaced with the literal value for undefined, which appears as `void 0` when printed. This allows for additional optimizations such as collapsing `undefined ?? bar` into just `bar`. However, this substitution was not done for values specified via `--define:`. As a result, esbuild could potentially miss out on certain optimizations in these cases. With this release, it's now possible to use `--define:` to substitute something with an undefined literal:
```js
// Original code
let win = typeof window !== 'undefined' ? window : {}
// Old output (with --define:window=undefined --minify)
let win=typeof undefined!="undefined"?undefined:{};
// New output (with --define:window=undefined --minify)
let win={};
```
- Add the `--drop:debugger` flag ([#1809](https://togithub.com/evanw/esbuild/issues/1809))
Passing this flag causes all [`debugger;` statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger) to be removed from the output. This is similar to the `drop_debugger: true` flag available in the popular UglifyJS and Terser JavaScript minifiers.
- Add the `--drop:console` flag ([#28](https://togithub.com/evanw/esbuild/issues/28))
Passing this flag causes all [`console.xyz()` API calls](https://developer.mozilla.org/en-US/docs/Web/API/console#methods) to be removed from the output. This is similar to the `drop_console: true` flag available in the popular UglifyJS and Terser JavaScript minifiers.
WARNING: Using this flag can introduce bugs into your code! This flag removes the entire call expression including all call arguments. If any of those arguments had important side effects, using this flag will change the behavior of your code. Be very careful when using this flag. If you want to remove console API calls without removing arguments with side effects (which does not introduce bugs), you should mark the relevant API calls as pure instead like this: `--pure:console.log --minify`.
- Inline calls to certain no-op functions when minifying ([#290](https://togithub.com/evanw/esbuild/issues/290), [#907](https://togithub.com/evanw/esbuild/issues/907))
This release makes esbuild inline two types of no-op functions: empty functions and identity functions. These most commonly arise when most of the function body is eliminated as dead code. In the examples below, this happens because we use `--define:window.DEBUG=false` to cause dead code elimination inside the function body of the resulting `if (false)` statement. This inlining is a small code size and performance win but, more importantly, it allows for people to use these features to add useful abstractions that improve the development experience without needing to worry about the run-time performance impact.
An identity function is a function that just returns its argument. Here's an example of inlining an identity function:
```js
// Original code
function logCalls(fn) {
if (window.DEBUG) return function(...args) {
console.log('calling', fn.name, 'with', args)
return fn.apply(this, args)
}
return fn
}
export const foo = logCalls(function foo() {})
// Old output (with --minify --define:window.DEBUG=false --tree-shaking=true)
function o(n){return n}export const foo=o(function(){});
// New output (with --minify --define:window.DEBUG=false --tree-shaking=true)
export const foo=function(){};
```
An empty function is a function with an empty body. Here's an example of inlining an empty function:
```ts
// Original code
function assertNotNull(val: Object | null): asserts val is Object {
if (window.DEBUG && val === null) throw new Error('null assertion failed');
}
export const val = getFoo();
assertNotNull(val);
console.log(val.bar);
// Old output (with --minify --define:window.DEBUG=false --tree-shaking=true)
function l(o){}export const val=getFoo();l(val);console.log(val.bar);
// New output (with --minify --define:window.DEBUG=false --tree-shaking=true)
export const val=getFoo();console.log(val.bar);
```
To get this behavior you'll need to use the `function` keyword to define your function since that causes the definition to be hoisted, which eliminates concerns around initialization order. These features also work across modules, so functions are still inlined even if the definition of the function is in a separate module from the call to the function. To get cross-module function inlining to work, you'll need to have bundling enabled and use the `import` and `export` keywords to access the function so that esbuild can see which functions are called. And all of this has been added without an observable impact to compile times.
I previously wasn't able to add this to esbuild easily because of esbuild's low-pass compilation approach. The compiler only does three full passes over the data for speed. The passes are roughly for parsing, binding, and printing. It's only possible to inline something after binding but it needs to be inlined before printing. Also the way module linking was done made it difficult to roll back uses of symbols that were inlined, so the symbol definitions were not tree shaken even when they became unused due to inlining.
The linking issue was somewhat resolved when I fixed [#128](https://togithub.com/evanw/esbuild/issues/128) in the previous release. To implement cross-module inlining of TypeScript enums, I came up with a hack to defer certain symbol uses until the linking phase, which happens after binding but before printing. Another hack is that inlining of TypeScript enums is done directly in the printer to avoid needing another pass.
The possibility of these two hacks has unblocked these simple function inlining use cases that are now handled. This isn't a fully general approach because optimal inlining is recursive. Inlining something may open up further inlining opportunities, which either requires multiple iterations or a worklist algorithm, both of which don't work when doing late-stage inlining in the printer. But the function inlining that esbuild now implements is still useful even though it's one level deep, and so I believe it's still worth adding.
### [`v0.14.9`](https://togithub.com/evanw/esbuild/blob/HEAD/CHANGELOG.md#0149)
[Compare Source](https://togithub.com/evanw/esbuild/compare/v0.14.8...v0.14.9)
- Implement cross-module tree shaking of TypeScript enum values ([#128](https://togithub.com/evanw/esbuild/issues/128))
If your bundle uses TypeScript enums across multiple files, esbuild is able to inline the enum values as long as you export and import the enum using the ES module `export` and `import` keywords. However, this previously still left the definition of the enum in the bundle even when it wasn't used anymore. This was because esbuild's tree shaking (i.e. dead code elimination) is based on information recorded during parsing, and at that point we don't know which imported symbols are inlined enum values and which aren't.
With this release, esbuild will now remove enum definitions that become unused due to cross-module enum value inlining. Property accesses off of imported symbols are now tracked separately during parsing and then resolved during linking once all inlined enum values are known. This behavior change means esbuild's support for cross-module inlining of TypeScript enums is now finally complete. Here's an example:
```js
// entry.ts
import { Foo } from './enum'
console.log(Foo.Bar)
// enum.ts
export enum Foo { Bar }
```
Bundling the example code above now results in the enum definition being completely removed from the bundle:
```js
// Old output (with --bundle --minify --format=esm)
var r=(o=>(o[o.Bar=0]="Bar",o))(r||{});console.log(0);
// New output (with --bundle --minify --format=esm)
console.log(0);
```
- Fix a regression with `export {} from` and CommonJS ([#1890](https://togithub.com/evanw/esbuild/issues/1890))
This release fixes a regression that was introduced by the change in 0.14.7 that avoids calling the `__toESM` wrapper for import statements that are converted to `require` calls and that don't use the `default` or `__esModule` export names. The previous change was correct for the `import {} from` syntax but not for the `export {} from` syntax, which meant that in certain cases with re-exported values, the value of the `default` import could be different than expected. This release fixes the regression.
- Warn about using `module` or `exports` in ESM code ([#1887](https://togithub.com/evanw/esbuild/issues/1887))
CommonJS export variables cannot be referenced in ESM code. If you do this, they are treated as global variables instead. This release includes a warning for people that try to use both CommonJS and ES module export styles in the same file. Here's an example:
```ts
export enum Something {
a,
b,
}
module.exports = { a: 1, b: 2 }
```
Running esbuild on that code now generates a warning that looks like this:
▲ [WARNING] The CommonJS "module" variable is treated as a global variable in an ECMAScript module and may not work as expected
example.ts:5:0:
5 │ module.exports = { a: 1, b: 2 }
╵ ~~~~~~
This file is considered to be an ECMAScript module because of the "export" keyword here:
example.ts:1:0:
1 │ export enum Something {
╵ ~~~~~~
### [`v0.14.8`](https://togithub.com/evanw/esbuild/blob/HEAD/CHANGELOG.md#0148)
[Compare Source](https://togithub.com/evanw/esbuild/compare/v0.14.7...v0.14.8)
- Add a `resolve` API for plugins ([#641](https://togithub.com/evanw/esbuild/issues/641), [#1652](https://togithub.com/evanw/esbuild/issues/1652))
Plugins now have access to a new API called `resolve` that runs esbuild's path resolution logic and returns the result to the caller. This lets you write plugins that can reuse esbuild's complex built-in path resolution logic to change the inputs and/or adjust the outputs. Here's an example:
```js
let examplePlugin = {
name: 'example',
setup(build) {
build.onResolve({ filter: /^example$/ }, async () => {
const result = await build.resolve('./foo', { resolveDir: '/bar' })
if (result.errors.length > 0) return result
return { ...result, external: true }
})
},
}
```
This plugin intercepts imports to the path `example`, tells esbuild to resolve the import `./foo` in the directory `/bar`, and then forces whatever path esbuild returns to be considered external. Here are some additional details:
- If you don't pass the optional `resolveDir` parameter, esbuild will still run `onResolve` plugin callbacks but will not attempt any path resolution itself. All of esbuild's path resolution logic depends on the `resolveDir` parameter including looking for packages in `node_modules` directories (since it needs to know where those `node_modules` directories might be).
- If you want to resolve a file name in a specific directory, make sure the input path starts with `./`. Otherwise the input path will be treated as a package path instead of a relative path. This behavior is identical to esbuild's normal path resolution logic.
- If path resolution fails, the `errors` property on the returned object will be a non-empty array containing the error information. This function does not always throw an error when it fails. You need to check for errors after calling it.
- The behavior of this function depends on the build configuration. That's why it's a property of the `build` object instead of being a top-level API call. This also means you can't call it until all plugin `setup` functions have finished since these give plugins the opportunity to adjust the build configuration before it's frozen at the start of the build. So the new `resolve` function is going to be most useful inside your `onResolve` and/or `onLoad` callbacks.
- There is currently no attempt made to detect infinite path resolution loops. Calling `resolve` from within `onResolve` with the same parameters is almost certainly a bad idea.
- Avoid the CJS-to-ESM wrapper in some cases ([#1831](https://togithub.com/evanw/esbuild/issues/1831))
Import statements are converted into `require()` calls when the output format is set to CommonJS. To convert from CommonJS semantics to ES module semantics, esbuild wraps the return value in a call to esbuild's `__toESM()` helper function. However, the conversion is only needed if it's possible that the exports named `default` or `__esModule` could be accessed.
This release avoids calling this helper function in cases where esbuild knows it's impossible for the `default` or `__esModule` exports to be accessed, which results in smaller and faster code. To get this behavior, you have to use the `import {} from` import syntax:
```js
// Original code
import { readFile } from "fs";
readFile();
// Old output (with --format=cjs)
var __toESM = (module, isNodeMode) => {
...
};
var import_fs = __toESM(require("fs"));
(0, import_fs.readFile)();
// New output (with --format=cjs)
var import_fs = require("fs");
(0, import_fs.readFile)();
```
- Strip overwritten function declarations when minifying ([#610](https://togithub.com/evanw/esbuild/issues/610))
JavaScript allows functions to be re-declared, with each declaration overwriting the previous declaration. This type of code can sometimes be emitted by automatic code generators. With this release, esbuild now takes this behavior into account when minifying to drop all but the last declaration for a given function:
```js
// Original code
function foo() { console.log(1) }
function foo() { console.log(2) }
// Old output (with --minify)
function foo(){console.log(1)}function foo(){console.log(2)}
// New output (with --minify)
function foo(){console.log(2)}
```
- Add support for the Linux IBM Z 64-bit Big Endian platform ([#1864](https://togithub.com/evanw/esbuild/pull/1864))
With this release, the esbuild package now includes a Linux binary executable for the IBM System/390 64-bit architecture. This new platform was contributed by [@shahidhs-ibm](https://togithub.com/shahidhs-ibm).
- Allow whitespace around `:` in JSX elements ([#1877](https://togithub.com/evanw/esbuild/issues/1877))
This release allows you to write the JSX `` as `` instead. Doing this is not forbidden by [the JSX specification](https://facebook.github.io/jsx/). While this doesn't work in TypeScript, it does work with other JSX parsers in the ecosystem, so support for this has been added to esbuild.
### [`v0.14.7`](https://togithub.com/evanw/esbuild/blob/HEAD/CHANGELOG.md#0147)
[Compare Source](https://togithub.com/evanw/esbuild/compare/v0.14.6...v0.14.7)
- Cross-module inlining of TypeScript `enum` constants ([#128](https://togithub.com/evanw/esbuild/issues/128))
This release adds inlining of TypeScript `enum` constants across separate modules. It activates when bundling is enabled and when the enum is exported via the `export` keyword and imported via the `import` keyword:
```ts
// foo.ts
export enum Foo { Bar }
// bar.ts
import { Foo } from './foo.ts'
console.log(Foo.Bar)
```
The access to `Foo.Bar` will now be compiled into `0 /* Bar */` even though the enum is defined in a separate file. This inlining was added without adding another pass (which would have introduced a speed penalty) by splitting the code for the inlining between the existing parsing and printing passes. Enum inlining is active whether or not you use `enum` or `const enum` because it improves performance.
To demonstrate the performance improvement, I compared the performance of the TypeScript compiler built by bundling the TypeScript compiler source code with esbuild before and after this change. The speed of the compiler was measured by using it to type check a small TypeScript code base. Here are the results:
| | `tsc` | with esbuild 0.14.6 | with esbuild 0.14.7 |
|------|-------|---------------------|---------------------|
| Time | 2.96s | 3.45s | 2.95s |
As you can see, enum inlining gives around a 15% speedup, which puts the esbuild-bundled version at the same speed as the offical TypeScript compiler build (the `tsc` column)!
The specifics of the benchmark aren't important here since it's just a demonstration of how enum inlining can affect performance. But if you're wondering, I type checked the [Rollup](https://togithub.com/rollup/rollup) code base using a work-in-progress branch of the TypeScript compiler that's part of the ongoing effort to convert their use of namespaces into ES modules.
- Mark node built-in modules as having no side effects ([#705](https://togithub.com/evanw/esbuild/issues/705))
This release marks node built-in modules such as `fs` as being side-effect free. That means unused imports to these modules are now removed when bundling, which sometimes results in slightly smaller code. For example:
```js
// Original code
import fs from 'fs';
import path from 'path';
console.log(path.delimiter);
// Old output (with --bundle --minify --platform=node --format=esm)
import"fs";import o from"path";console.log(o.delimiter);
// New output (with --bundle --minify --platform=node --format=esm)
import o from"path";console.log(o.delimiter);
```
Note that these modules are only automatically considered side-effect when bundling for node, since they are only known to be side-effect free imports in that environment. However, you can customize this behavior with a plugin by returning `external: true` and `sideEffects: false` in an `onResolve` callback for whatever paths you want to be treated this way.
- Recover from a stray top-level `}` in CSS ([#1876](https://togithub.com/evanw/esbuild/pull/1876))
This release fixes a bug where a stray `}` at the top-level of a CSS file would incorrectly truncate the remainder of the file in the output (although not without a warning). With this release, the remainder of the file is now still parsed and printed:
```css
/* Original code */
.red {
color: red;
}
}
.blue {
color: blue;
}
.green {
color: green;
}
/* Old output (with --minify) */
.red{color:red}
/* New output (with --minify) */
.red{color:red}} .blue{color:#00f}.green{color:green}
```
This fix was contributed by [@sbfaulkner](https://togithub.com/sbfaulkner).
### [`v0.14.6`](https://togithub.com/evanw/esbuild/blob/HEAD/CHANGELOG.md#0146)
[Compare Source](https://togithub.com/evanw/esbuild/compare/v0.14.5...v0.14.6)
- Fix a minifier bug with BigInt literals
Previously expression simplification optimizations in the minifier incorrectly assumed that numeric operators always return numbers. This used to be true but has no longer been true since the introduction of BigInt literals in ES2020. Now numeric operators can return either a number or a BigInt depending on the arguments. This oversight could potentially have resulted in behavior changes. For example, this code printed `false` before being minified and `true` after being minified because esbuild shortened `===` to `==` under the false assumption that both operands were numbers:
```js
var x = 0;
console.log((x ? 2 : -1n) === -1);
```
The type checking logic has been rewritten to take into account BigInt literals in this release, so this incorrect simplification is no longer applied.
- Enable removal of certain unused template literals ([#1853](https://togithub.com/evanw/esbuild/issues/1853))
This release contains improvements to the minification of unused template literals containing primitive values:
```js
// Original code
`${1}${2}${3}`;
`${x ? 1 : 2}${y}`;
// Old output (with --minify)
""+1+2+3,""+(x?1:2)+y;
// New output (with --minify)
x,`${y}`;
```
This can arise when the template literals are nested inside of another function call that was determined to be unnecessary such as an unused call to a function marked with the `/* @__PURE__ */` pragma.
This release also fixes a bug with this transformation where minifying the unused expression `` `foo ${bar}` `` into `"" + bar` changed the meaning of the expression. Template string interpolation always calls `toString` while string addition may call `valueOf` instead. This unused expression is now minified to `` `${bar}` ``, which is slightly longer but which avoids the behavior change.
- Allow `keyof`/`readonly`/`infer` in TypeScript index signatures ([#1859](https://togithub.com/evanw/esbuild/pull/1859))
This release fixes a bug that prevented these keywords from being used as names in index signatures. The following TypeScript code was previously rejected, but is now accepted:
```ts
interface Foo {
[keyof: string]: number
}
```
This fix was contributed by [@magic-akari](https://togithub.com/magic-akari).
- Avoid warning about `import.meta` if it's replaced ([#1868](https://togithub.com/evanw/esbuild/issues/1868))
It's possible to replace the `import.meta` expression using the `--define:` feature. Previously doing that still warned that the `import.meta` syntax was not supported when targeting ES5. With this release, there will no longer be a warning in this case.
### [`v0.14.5`](https://togithub.com/evanw/esbuild/blob/HEAD/CHANGELOG.md#0145)
[Compare Source](https://togithub.com/evanw/esbuild/compare/v0.14.4...v0.14.5)
- Fix an issue with the publishing script
This release fixes a missing dependency issue in the publishing script where it was previously possible for the published binary executable to have an incorrect version number.
### [`v0.14.4`](https://togithub.com/evanw/esbuild/blob/HEAD/CHANGELOG.md#0144)
[Compare Source](https://togithub.com/evanw/esbuild/compare/v0.14.3...v0.14.4)
- Adjust esbuild's handling of `default` exports and the `__esModule` marker ([#532](https://togithub.com/evanw/esbuild/issues/532), [#1591](https://togithub.com/evanw/esbuild/issues/1591), [#1719](https://togithub.com/evanw/esbuild/issues/1719))
This change requires some background for context. Here's the history to the best of my understanding:
When the ECMAScript module `import`/`export` syntax was being developed, the CommonJS module format (used in Node.js) was already widely in use. Because of this the export name called `default` was given special a syntax. Instead of writing `import { default as foo } from 'bar'` you can just write `import foo from 'bar'`. The idea was that when ECMAScript modules (a.k.a. ES modules) were introduced, you could import existing CommonJS modules using the new import syntax for compatibility. Since CommonJS module exports are dynamic while ES module exports are static, it's not generally possible to determine a CommonJS module's export names at module instantiation time since the code hasn't been evaluated yet. So the value of `module.exports` is just exported as the `default` export and the special `default` import syntax gives you easy access to `module.exports` (i.e. `const foo = require('bar')` is the same as `import foo from 'bar'`).
However, it took a while for ES module syntax to be supported natively by JavaScript runtimes, and people still wanted to start using ES module syntax in the meantime. The [Babel](https://babeljs.io/) JavaScript compiler let you do this. You could transform each ES module file into a CommonJS module file that behaved the same. However, this transformation has a problem: emulating the `import` syntax accurately as described above means that `export default 0` and `import foo from 'bar'` will no longer line up when transformed to CommonJS. The code `export default 0` turns into `module.exports.default = 0` and the code `import foo from 'bar'` turns into `const foo = require('bar')`, meaning `foo` is `0` before the transformation but `foo` is `{ default: 0 }` after the transformation.
To fix this, Babel sets the property `__esModule` to true as a signal to itself when it converts an ES module to a CommonJS module. Then, when importing a `default` export, it can know to use the value of `module.exports.default` instead of `module.exports` to make sure the behavior of the CommonJS modules correctly matches the behavior of the original ES modules. This fix has been widely adopted across the ecosystem and has made it into other tools such as TypeScript and even esbuild.
However, when Node.js finally released their ES module implementation, they went with the original implementation where the `default` export is always `module.exports`, which broke compatibility with the existing ecosystem of ES modules that had been cross-compiled into CommonJS modules by Babel. You now have to either add or remove an additional `.default` property depending on whether your code needs to run in a Node environment or in a Babel environment, which created an interoperability headache. In addition, JavaScript tools such as esbuild now need to guess whether you want Node-style or Babel-style `default` imports. There's no way for a tool to know with certainty which one a given file is expecting and if your tool guesses wrong, your code will break.
This release changes esbuild's heuristics around `default` exports and the `__esModule` marker to attempt to improve compatibility with Webpack and Node, which is what most packages are tuned for. The behavior changes are as follows:
Old behavior:
- If an `import` statement is used to load a CommonJS file and a) `module.exports` is an object, b) `module.exports.__esModule` is truthy, and c) the property `default` exists in `module.exports`, then esbuild would set the `default` export to `module.exports.default` (like Babel). Otherwise the `default` export was set to `module.exports` (like Node).
- If a `require` call is used to load an ES module file, the returned module namespace object had the `__esModule` property set to true. This behaved as if the ES module had been converted to CommonJS via a Babel-compatible transformation.
- The `__esModule` marker could inconsistently appear on module namespace objects (i.e. `import * as`) when writing pure ESM code. Specifically, if a module namespace object was materialized then the `__esModule` marker was present, but if it was optimized away then the `__esModule` marker was absent.
- It was not allowed to create an ES module export named `__esModule`. This avoided generating code that might break due to the inconsistency mentioned above, and also avoided issues with duplicate definitions of `__esModule`.
New behavior:
- If an `import` statement is used to load a CommonJS file and a) `module.exports` is an object, b) `module.exports.__esModule` is truthy, and c) the file name does not end in either `.mjs` or `.mts` and the `package.json` file does not contain `"type": "module"`, then esbuild will set the `default` export to `module.exports.default` (like Babel). Otherwise the `default` export is set to `module.exports` (like Node).
Note that this means the `default` export may now be undefined in situations where it previously wasn't undefined. This matches Webpack's behavior so it should hopefully be more compatible.
Also note that this means import behavior now depends on the file extension and on the contents of `package.json`. This also matches Webpack's behavior to hopefully improve compatibility.
- If a `require` call is used to load an ES module file, the returned module namespace object has the `__esModule` property set to `true`. This behaves as if the ES module had been converted to CommonJS via a Babel-compatible transformation.
- If an `import` statement or `import()` expression is used to load an ES module, the `__esModule` marker should now never be present on the module namespace object. This frees up the `__esModule` export name for use with ES modules.
- It's now allowed to use `__esModule` as a normal export name in an ES module. This property will be accessible to other ES modules but will not be accessible to code that loads the ES module using `require`, where they will observe the property set to `true` instead.
### [`v0.14.3`](https://togithub.com/evanw/esbuild/blob/HEAD/CHANGELOG.md#0143)
[Compare Source](https://togithub.com/evanw/esbuild/compare/v0.14.2...v0.14.3)
- Pass the current esbuild instance to JS plugins ([#1790](https://togithub.com/evanw/esbuild/issues/1790))
Previously JS plugins that wanted to run esbuild had to `require('esbuild')` to get the esbuild object. However, that could potentially result in a different version of esbuild. This is also more complicated to do outside of node (such as within a browser). With this release, the current esbuild instance is now passed to JS plugins as the `esbuild` property:
```js
let examplePlugin = {
name: 'example',
setup(build) {
console.log(build.esbuild.version)
console.log(build.esbuild.transformSync('1+2'))
},
}
```
- Disable `calc()` transform for results with non-finite numbers ([#1839](https://togithub.com/evanw/esbuild/issues/1839))
This release disables minification of `calc()` expressions when the result contains `NaN`, `-Infinity`, or `Infinity`. These numbers are valid inside of `calc()` expressions but not outside of them, so the `calc()` expression must be preserved in these cases.
- Move `"use strict"` before injected shim imports ([#1837](https://togithub.com/evanw/esbuild/issues/1837))
If a CommonJS file contains a `"use strict"` directive, it could potentially be unintentionally disabled by esbuild when using the "inject" feature when bundling is enabled. This is because the inject feature was inserting a call to the initializer for the injected file before the `"use strict"` directive. In JavaScript, directives do not apply if they come after a non-directive statement. This release fixes the problem by moving the `"use strict"` directive before the initializer for the injected file so it isn't accidentally disabled.
- Pass the ignored path query/hash suffix to `onLoad` plugins ([#1827](https://togithub.com/evanw/esbuild/issues/1827))
The built-in `onResolve` handler that comes with esbuild can strip the query/hash suffix off of a path during path resolution. For example, `url("fonts/icons.eot?#iefix")` can be resolved to the file `fonts/icons.eot`. For context, IE8 has a bug where it considers the font face URL to extend to the last `)` instead of the first `)`. In the example below, IE8 thinks the URL for the font is `Example.eot?#iefix') format('eot'), url('Example.ttf') format('truetype` so by adding `?#iefix`, IE8 thinks the URL has a path of `Example.eot` and a query string of `?#iefix') format('eot...` and can load the font file:
```css
@font-face {
font-family: 'Example';
src: url('Example.eot?#iefix') format('eot'), url('Example.ttf') format('truetype');
}
```
However, the suffix is not currently passed to esbuild and plugins may want to use this suffix for something. Previously plugins had to add their own `onResolve` handler if they wanted to use the query suffix. With this release, the suffix can now be returned by plugins from `onResolve` and is now passed to plugins in `onLoad`:
```js
let examplePlugin = {
name: 'example',
setup(build) {
build.onResolve({ filter: /.*/ }, args => {
return { path: args.path, suffix: '?#iefix' }
})
build.onLoad({ filter: /.*/ }, args => {
console.log({ path: args.path, suffix: args.suffix })
})
},
}
```
The suffix is deliberately not included in the path that's provided to plugins because most plugins won't know to handle this strange edge case and would likely break. Keeping the suffix out of the path means that plugins can opt-in to handling this edge case if they want to, and plugins that aren't aware of this edge case will likely still do something reasonable.
### [`v0.14.2`](https://togithub.com/evanw/esbuild/blob/HEAD/CHANGELOG.md#0142)
[Compare Source](https://togithub.com/evanw/esbuild/compare/v0.14.1...v0.14.2)
- Add `[ext]` placeholder for path templates ([#1799](https://togithub.com/evanw/esbuild/pull/1799))
This release adds the `[ext]` placeholder to the `--entry-names=`, `--chunk-names=`, and `--asset-names=` configuration options. The `[ext]` placeholder takes the value of the file extension without the leading `.`, and can be used to place output files with different file extensions into different folders. For example, `--asset-names=assets/[ext]/[name]-[hash]` might generate an output path of `assets/png/image-LSAMBFUD.png`.
This feature was contributed by [@LukeSheard](https://togithub.com/LukeSheard).
- Disable star-to-clause transform for external imports ([#1801](https://togithub.com/evanw/esbuild/issues/1801))
When bundling is enabled, esbuild automatically transforms `import * as x from 'y'; x.z()` into `import {z} as 'y'; z()` to improve tree shaking. This avoids needing to create the import namespace object `x` if it's unnecessary, which can result in the removal of large amounts of unused code. However, this transform shouldn't be done for external imports because that incorrectly changes the semantics of the import. If the export `z` doesn't exist in the previous example, the value `x.z` is a property access that is undefined at run-time, but the value `z` is an import error that will prevent the code from running entirely. This release fixes the problem by avoiding doing this transform for external imports:
```js
// Original code
import * as x from 'y';
x.z();
// Old output (with --bundle --format=esm --external:y)
import { z } from "y";
z();
// New output (with --bundle --format=esm --external:y)
import * as x from "y";
x.z();
```
- Disable `calc()` transform for numbers with many fractional digits ([#1821](https://togithub.com/evanw/esbuild/issues/1821))
Version 0.13.12 introduced simplification of `calc()` expressions in CSS when minifying. For example, `calc(100% / 4)` turns into `25%`. However, this is problematic for numbers with many fractional digits because either the number is printed with reduced precision, which is inaccurate, or the number is printed with full precision, which could be longer than the original expression. For example, turning `calc(100% / 3)` into `33.33333%` is inaccurate and turning it into `33.333333333333336%` likely isn't desired. In this release, minification of `calc()` is now disabled when any number in the result cannot be represented to full precision with at most five fractional digits.
- Fix an edge case with `catch` scope handling ([#1812](https://togithub.com/evanw/esbuild/issues/1812))
This release fixes a subtle edge case with `catch` scope and destructuring assignment. Identifiers in computed properties and/or default values inside the destructuring binding pattern should reference the outer scope, not the inner scope. The fix was to split the destructuring pattern into its own scope, separate from the `catch` body. Here's an example of code that was affected by this edge case:
```js
// Original code
let foo = 1
try {
throw ['a', 'b']
} catch ({ [foo]: y }) {
let foo = 2
assert(y === 'b')
}
// Old output (with --minify)
let foo=1;try{throw["a","b"]}catch({[o]:t}){let o=2;assert(t==="b")}
// New output (with --minify)
let foo=1;try{throw["a","b"]}catch({[foo]:t}){let o=2;assert(t==="b")}
```
- Go 1.17.2 was upgraded to Go 1.17.4
The previous release was built with Go 1.17.2, but this release is built with Go 1.17.4. This is just a routine upgrade. There are no changes significant to esbuild outside of some security-related fixes to Go's HTTP stack (but you shouldn't be running esbuild's dev server in production anyway).
One notable change related to this is that esbuild's publishing script now ensures that git's state is free of uncommitted and/or untracked files before building. Previously this wasn't the case because publishing esbuild involved changing the version number, running the publishing script, and committing at the end, which meant that files were uncommitted during the build process. I also typically had some untracked test files in the same directory during publishing (which is harmless).
This matters because there's an upcoming change in Go 1.18 where the Go compiler will include metadata about whether there are untracked files or not when doing a build: [https://github.com/golang/go/issues/37475](https://togithub.com/golang/go/issues/37475). Changing esbuild's publishing script should mean that when esbuild upgrades to Go 1.18, esbuild's binary executables will be marked as being built off of a specific commit without any modifications. This is important for reproducibility. Checking out a specific esbuild commit and building it should give a bitwise-identical binary executable to one that I published. But if this metadata indicated that there were untracked files during the published build, then the resulting executable would no longer be bitwise-identical.
Configuration
📅 Schedule: "on the first day of the month" (UTC).
🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.
♻ Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.
🔕 Ignore: Close this PR and you won't be reminded about this update again.
[ ] If you want to rebase/retry this PR, click this checkbox.
This PR contains the following updates:
0.14.1
->0.14.10
Release Notes
evanw/esbuild
### [`v0.14.10`](https://togithub.com/evanw/esbuild/blob/HEAD/CHANGELOG.md#01410) [Compare Source](https://togithub.com/evanw/esbuild/compare/v0.14.9...v0.14.10) - Enable tree shaking of classes with lowered static fields ([#175](https://togithub.com/evanw/esbuild/issues/175)) If the configured target environment doesn't support static class fields, they are converted into a call to esbuild's `__publicField` function instead. However, esbuild's tree-shaking pass treated this call as a side effect, which meant that all classes with static fields were ineligible for tree shaking. This release fixes the problem by explicitly ignoring calls to the `__publicField` function during tree shaking side-effect determination. Tree shaking is now enabled for these classes: ```js // Original code class Foo { static foo = 'foo' } class Bar { static bar = 'bar' } new Bar() // Old output (with --tree-shaking=true --target=es6) class Foo { } __publicField(Foo, "foo", "foo"); class Bar { } __publicField(Bar, "bar", "bar"); new Bar(); // New output (with --tree-shaking=true --target=es6) class Bar { } __publicField(Bar, "bar", "bar"); new Bar(); ``` - Treat `--define:foo=undefined` as an undefined literal instead of an identifier ([#1407](https://togithub.com/evanw/esbuild/issues/1407)) References to the global variable `undefined` are automatically replaced with the literal value for undefined, which appears as `void 0` when printed. This allows for additional optimizations such as collapsing `undefined ?? bar` into just `bar`. However, this substitution was not done for values specified via `--define:`. As a result, esbuild could potentially miss out on certain optimizations in these cases. With this release, it's now possible to use `--define:` to substitute something with an undefined literal: ```js // Original code let win = typeof window !== 'undefined' ? window : {} // Old output (with --define:window=undefined --minify) let win=typeof undefined!="undefined"?undefined:{}; // New output (with --define:window=undefined --minify) let win={}; ``` - Add the `--drop:debugger` flag ([#1809](https://togithub.com/evanw/esbuild/issues/1809)) Passing this flag causes all [`debugger;` statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger) to be removed from the output. This is similar to the `drop_debugger: true` flag available in the popular UglifyJS and Terser JavaScript minifiers. - Add the `--drop:console` flag ([#28](https://togithub.com/evanw/esbuild/issues/28)) Passing this flag causes all [`console.xyz()` API calls](https://developer.mozilla.org/en-US/docs/Web/API/console#methods) to be removed from the output. This is similar to the `drop_console: true` flag available in the popular UglifyJS and Terser JavaScript minifiers. WARNING: Using this flag can introduce bugs into your code! This flag removes the entire call expression including all call arguments. If any of those arguments had important side effects, using this flag will change the behavior of your code. Be very careful when using this flag. If you want to remove console API calls without removing arguments with side effects (which does not introduce bugs), you should mark the relevant API calls as pure instead like this: `--pure:console.log --minify`. - Inline calls to certain no-op functions when minifying ([#290](https://togithub.com/evanw/esbuild/issues/290), [#907](https://togithub.com/evanw/esbuild/issues/907)) This release makes esbuild inline two types of no-op functions: empty functions and identity functions. These most commonly arise when most of the function body is eliminated as dead code. In the examples below, this happens because we use `--define:window.DEBUG=false` to cause dead code elimination inside the function body of the resulting `if (false)` statement. This inlining is a small code size and performance win but, more importantly, it allows for people to use these features to add useful abstractions that improve the development experience without needing to worry about the run-time performance impact. An identity function is a function that just returns its argument. Here's an example of inlining an identity function: ```js // Original code function logCalls(fn) { if (window.DEBUG) return function(...args) { console.log('calling', fn.name, 'with', args) return fn.apply(this, args) } return fn } export const foo = logCalls(function foo() {}) // Old output (with --minify --define:window.DEBUG=false --tree-shaking=true) function o(n){return n}export const foo=o(function(){}); // New output (with --minify --define:window.DEBUG=false --tree-shaking=true) export const foo=function(){}; ``` An empty function is a function with an empty body. Here's an example of inlining an empty function: ```ts // Original code function assertNotNull(val: Object | null): asserts val is Object { if (window.DEBUG && val === null) throw new Error('null assertion failed'); } export const val = getFoo(); assertNotNull(val); console.log(val.bar); // Old output (with --minify --define:window.DEBUG=false --tree-shaking=true) function l(o){}export const val=getFoo();l(val);console.log(val.bar); // New output (with --minify --define:window.DEBUG=false --tree-shaking=true) export const val=getFoo();console.log(val.bar); ``` To get this behavior you'll need to use the `function` keyword to define your function since that causes the definition to be hoisted, which eliminates concerns around initialization order. These features also work across modules, so functions are still inlined even if the definition of the function is in a separate module from the call to the function. To get cross-module function inlining to work, you'll need to have bundling enabled and use the `import` and `export` keywords to access the function so that esbuild can see which functions are called. And all of this has been added without an observable impact to compile times. I previously wasn't able to add this to esbuild easily because of esbuild's low-pass compilation approach. The compiler only does three full passes over the data for speed. The passes are roughly for parsing, binding, and printing. It's only possible to inline something after binding but it needs to be inlined before printing. Also the way module linking was done made it difficult to roll back uses of symbols that were inlined, so the symbol definitions were not tree shaken even when they became unused due to inlining. The linking issue was somewhat resolved when I fixed [#128](https://togithub.com/evanw/esbuild/issues/128) in the previous release. To implement cross-module inlining of TypeScript enums, I came up with a hack to defer certain symbol uses until the linking phase, which happens after binding but before printing. Another hack is that inlining of TypeScript enums is done directly in the printer to avoid needing another pass. The possibility of these two hacks has unblocked these simple function inlining use cases that are now handled. This isn't a fully general approach because optimal inlining is recursive. Inlining something may open up further inlining opportunities, which either requires multiple iterations or a worklist algorithm, both of which don't work when doing late-stage inlining in the printer. But the function inlining that esbuild now implements is still useful even though it's one level deep, and so I believe it's still worth adding. ### [`v0.14.9`](https://togithub.com/evanw/esbuild/blob/HEAD/CHANGELOG.md#0149) [Compare Source](https://togithub.com/evanw/esbuild/compare/v0.14.8...v0.14.9) - Implement cross-module tree shaking of TypeScript enum values ([#128](https://togithub.com/evanw/esbuild/issues/128)) If your bundle uses TypeScript enums across multiple files, esbuild is able to inline the enum values as long as you export and import the enum using the ES module `export` and `import` keywords. However, this previously still left the definition of the enum in the bundle even when it wasn't used anymore. This was because esbuild's tree shaking (i.e. dead code elimination) is based on information recorded during parsing, and at that point we don't know which imported symbols are inlined enum values and which aren't. With this release, esbuild will now remove enum definitions that become unused due to cross-module enum value inlining. Property accesses off of imported symbols are now tracked separately during parsing and then resolved during linking once all inlined enum values are known. This behavior change means esbuild's support for cross-module inlining of TypeScript enums is now finally complete. Here's an example: ```js // entry.ts import { Foo } from './enum' console.log(Foo.Bar) // enum.ts export enum Foo { Bar } ``` Bundling the example code above now results in the enum definition being completely removed from the bundle: ```js // Old output (with --bundle --minify --format=esm) var r=(o=>(o[o.Bar=0]="Bar",o))(r||{});console.log(0); // New output (with --bundle --minify --format=esm) console.log(0); ``` - Fix a regression with `export {} from` and CommonJS ([#1890](https://togithub.com/evanw/esbuild/issues/1890)) This release fixes a regression that was introduced by the change in 0.14.7 that avoids calling the `__toESM` wrapper for import statements that are converted to `require` calls and that don't use the `default` or `__esModule` export names. The previous change was correct for the `import {} from` syntax but not for the `export {} from` syntax, which meant that in certain cases with re-exported values, the value of the `default` import could be different than expected. This release fixes the regression. - Warn about using `module` or `exports` in ESM code ([#1887](https://togithub.com/evanw/esbuild/issues/1887)) CommonJS export variables cannot be referenced in ESM code. If you do this, they are treated as global variables instead. This release includes a warning for people that try to use both CommonJS and ES module export styles in the same file. Here's an example: ```ts export enum Something { a, b, } module.exports = { a: 1, b: 2 } ``` Running esbuild on that code now generates a warning that looks like this: ▲ [WARNING] The CommonJS "module" variable is treated as a global variable in an ECMAScript module and may not work as expected example.ts:5:0: 5 │ module.exports = { a: 1, b: 2 } ╵ ~~~~~~ This file is considered to be an ECMAScript module because of the "export" keyword here: example.ts:1:0: 1 │ export enum Something { ╵ ~~~~~~ ### [`v0.14.8`](https://togithub.com/evanw/esbuild/blob/HEAD/CHANGELOG.md#0148) [Compare Source](https://togithub.com/evanw/esbuild/compare/v0.14.7...v0.14.8) - Add a `resolve` API for plugins ([#641](https://togithub.com/evanw/esbuild/issues/641), [#1652](https://togithub.com/evanw/esbuild/issues/1652)) Plugins now have access to a new API called `resolve` that runs esbuild's path resolution logic and returns the result to the caller. This lets you write plugins that can reuse esbuild's complex built-in path resolution logic to change the inputs and/or adjust the outputs. Here's an example: ```js let examplePlugin = { name: 'example', setup(build) { build.onResolve({ filter: /^example$/ }, async () => { const result = await build.resolve('./foo', { resolveDir: '/bar' }) if (result.errors.length > 0) return result return { ...result, external: true } }) }, } ``` This plugin intercepts imports to the path `example`, tells esbuild to resolve the import `./foo` in the directory `/bar`, and then forces whatever path esbuild returns to be considered external. Here are some additional details: - If you don't pass the optional `resolveDir` parameter, esbuild will still run `onResolve` plugin callbacks but will not attempt any path resolution itself. All of esbuild's path resolution logic depends on the `resolveDir` parameter including looking for packages in `node_modules` directories (since it needs to know where those `node_modules` directories might be). - If you want to resolve a file name in a specific directory, make sure the input path starts with `./`. Otherwise the input path will be treated as a package path instead of a relative path. This behavior is identical to esbuild's normal path resolution logic. - If path resolution fails, the `errors` property on the returned object will be a non-empty array containing the error information. This function does not always throw an error when it fails. You need to check for errors after calling it. - The behavior of this function depends on the build configuration. That's why it's a property of the `build` object instead of being a top-level API call. This also means you can't call it until all plugin `setup` functions have finished since these give plugins the opportunity to adjust the build configuration before it's frozen at the start of the build. So the new `resolve` function is going to be most useful inside your `onResolve` and/or `onLoad` callbacks. - There is currently no attempt made to detect infinite path resolution loops. Calling `resolve` from within `onResolve` with the same parameters is almost certainly a bad idea. - Avoid the CJS-to-ESM wrapper in some cases ([#1831](https://togithub.com/evanw/esbuild/issues/1831)) Import statements are converted into `require()` calls when the output format is set to CommonJS. To convert from CommonJS semantics to ES module semantics, esbuild wraps the return value in a call to esbuild's `__toESM()` helper function. However, the conversion is only needed if it's possible that the exports named `default` or `__esModule` could be accessed. This release avoids calling this helper function in cases where esbuild knows it's impossible for the `default` or `__esModule` exports to be accessed, which results in smaller and faster code. To get this behavior, you have to use the `import {} from` import syntax: ```js // Original code import { readFile } from "fs"; readFile(); // Old output (with --format=cjs) var __toESM = (module, isNodeMode) => { ... }; var import_fs = __toESM(require("fs")); (0, import_fs.readFile)(); // New output (with --format=cjs) var import_fs = require("fs"); (0, import_fs.readFile)(); ``` - Strip overwritten function declarations when minifying ([#610](https://togithub.com/evanw/esbuild/issues/610)) JavaScript allows functions to be re-declared, with each declaration overwriting the previous declaration. This type of code can sometimes be emitted by automatic code generators. With this release, esbuild now takes this behavior into account when minifying to drop all but the last declaration for a given function: ```js // Original code function foo() { console.log(1) } function foo() { console.log(2) } // Old output (with --minify) function foo(){console.log(1)}function foo(){console.log(2)} // New output (with --minify) function foo(){console.log(2)} ``` - Add support for the Linux IBM Z 64-bit Big Endian platform ([#1864](https://togithub.com/evanw/esbuild/pull/1864)) With this release, the esbuild package now includes a Linux binary executable for the IBM System/390 64-bit architecture. This new platform was contributed by [@shahidhs-ibm](https://togithub.com/shahidhs-ibm). - Allow whitespace around `:` in JSX elements ([#1877](https://togithub.com/evanw/esbuild/issues/1877)) This release allows you to write the JSX `Configuration
📅 Schedule: "on the first day of the month" (UTC).
🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.
♻ Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.
🔕 Ignore: Close this PR and you won't be reminded about this update again.
This PR has been generated by WhiteSource Renovate. View repository job log here.