esbuild icon indicating copy to clipboard operation
esbuild copied to clipboard

Feature request: Evaluate code during build using a prebuild evaluation function from esbuild

Open johann1301s opened this issue 1 year ago • 2 comments

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:)

johann1301s avatar Dec 14 '23 15:12 johann1301s

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}/>
  )
}

johann1301s avatar Dec 14 '23 17:12 johann1301s

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.

evanw avatar Dec 14 '23 20:12 evanw