esbuild
esbuild copied to clipboard
Feature request: Evaluate code during build using a prebuild evaluation function from esbuild
Hi, I have a feature request!
Evaluate code during build using a prebuild evaluation function from esbuild
I would love a feature where I could import a special function from esbuild, say prebuild
, and use it to perform custom build tasks, like constant folding, loop optimization, string injection and other optimizations.
The prebuild
function would take in a function as the only argument, with some data about the current build. For example the version number from the projects package.json file.
The function provided to prebuild
would run during build, with all the typescript intellisense one would expect, and maybe it must return a string, or at least something serializable.
import React from 'react'
import {prebuild} from 'esbuild'
export const MyComponent = () => {
return (
<div data-version={prebuild((build) => build.version)}/>
)
}
In the first version, the developer would be responsible for making sure the resulting code is valid.
Is this feature in the backlog for esbuild?
PS: I am aware that string injection is part of esbuild, but I find that solution a bit outdated and messy. Feel free to disagree:)
Here is another example of how It could work.
If the file below is built,
import React from 'react'
import {prebuild} from 'esbuild'
import {SomeComponent} from './SomeComponent'
export const MyComponent = () => {
return (
<textarea value={prebuild(() => {
return React.renderToStaticMarkup(<SomeComponent id={'my-id'}/>)
})}
/>
)
}
the result could be something like,
import React from 'react'
export const MyComponent = () => {
return (
<textarea value={'<div id="my-id"></div>'}/>
)
}
provided that
import React from 'react'
type Props = {
id: string
}
export const SomeComponent = (props: Props) => {
return (
<div id={props.id}/>
)
}
Unfortunately esbuild is not a JavaScript run-time, and this feature might not be a good fit for esbuild. You may be interested in Bun though, as it does have something like that: https://bun.sh/blog/bun-macros.