evanw / evanw/esbuild

Option to assign default export to globalName for iife format

Open
#3,740 3 comments 2 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
40.1k
Forks
1.3k
PR merge metrics
No merged PRs in 30d

Description

```js
// foo.js
const awesomeFunction = () => {
// bunch of code
}

export default awesomeFunction

// bundle.js
await esbuild.build({
entryPoints: ['foo.js'],
minify: true,
format: "iife",
globalName: "awesomeFunction",
outfile: 'foo.min.js'
})
```

in the browser `window.awesomeFunction` is the object `{__esModule: true}`, where as `window.awesomeFunction.default` is the actual function.
I understand why this is the case, but the solution from when the [issue was mention earlier](https://github.com/evanw/esbuild/issues/869) was to change the exported function type to `module.exports`. **But** wouldn't it be nicer/more convienient if there was an option in the builder to assign the default export directly to the globalName?

```js
// bundle.js
await esbuild.build({
entryPoints: ['foo.js'],
minify: true,
format: "iife",
globalName: "awesomeFunction",

assignDefault: true, // default can be false if ommited, so it'll be backward compatible

outfile: 'foo.min.js'
})
```

...Or, is there a way to do this already, _without_ having to change the import

Extending on this... Maybe an option for using the name of the function (if it has been named) from the import as the `globalName`

```js
// bundle.js
await esbuild.build({
entryPoints: ['foo.js'],
minify: true,
format: "iife",
globalName: true, // not sure how one could pass implicity naming???
// Probably would require a fallback incase there wasn't a default (or if it wasn't named)
outfile: 'foo.min.js'
})
```

Contributor guide

No contributing guide indexed for this repository

Research direction

Start with the foo.js entry point and the esbuild.build configuration using format "iife" and globalName. Reproduce the current window.awesomeFunction value, then review the build API behavior around default exports and global names. Done means a clearly specified compatible option assigns the default export directly while preserving existing behavior when omitted.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
build-system, web-dev
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.