oven-sh / bun

Incredibly fast JavaScript runtime, bundler, test runner, and package manager – all in one
https://bun.sh
Other
74.16k stars 2.77k forks source link

Support `--env` with `bun build --compile` #13153

Open terrablue opened 3 months ago

terrablue commented 3 months ago

What is the problem this feature would solve?

When compiling apps using environment variables, if the env vars are not built-in into the program during compilation, and are instead loaded during runtime, the program would fail to run outside of the compilation directory.

What is the feature you are proposing to solve the problem?

The semantics of using Bun.env together with bun build --compile would be to use values read in during compilation process, similar to how Deno.env.get modifies its behaviour during compilation.

Deno has implemented this distinction in v1.45: https://deno.com/blog/v1.45#deno-compile-supports---env-flag

What alternatives have you considered?

Relying on Deno to compile apps, or trying to circumvent the issue by not using environment variables, and feeding in buildtime values using another mechanism to the app (say, a JSON import).

ralyodio commented 2 months ago

I'm also looking to support .env files in my binaries.

joglr commented 1 month ago

This is what I expected to happen when running:

bun build --compile --env-file=.env
joglr commented 1 month ago

I found a temporary work around:

Create a function in a separate file that reads the environment variables, either using Bun.env or process.env. Then, import the function in your main file using

import { getApiKey } from "./get-env" with { type: "macro" }

const apiKey = getApiKey()

This will include the environment variables at bundle time, which will be included in the executable.

terrablue commented 1 month ago

@joglr awesome work there, and thank you! I think I can use this in my framework to generate different code depending on build target.