Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions docs/bundler/executables.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ BUN_OPTIONS="--smol --cpu-prof-md" ./myapp

Standalone executables can automatically load configuration files from the directory where they are run. By default:

- **`tsconfig.json`** and **`package.json`** loading is **disabled** — these are typically only needed at development time, and the bundler already uses them when compiling
- **`tsconfig.json`** and **`package.json`** loading is **disabled** — these are typically only needed at development time, and the bundler already uses them when compiling. This applies to the `package.json` of the directory the executable runs in and of its parent directories (the project's `"type"`, `"imports"`, and self-reference through `"exports"`). Any other `package.json`, such as a dependency's in `node_modules`, is always read, so a `require()` of a dependency that is not embedded keeps working.
- **`.env`** and **`bunfig.toml`** loading is **enabled** — these often contain runtime configuration that may vary per deployment

<Note>
Expand All @@ -456,7 +456,7 @@ Standalone executables can automatically load configuration files from the direc

### Enabling config loading at runtime

If your executable needs to read `tsconfig.json` or `package.json` at runtime, opt in with these flags:
If your executable needs to read `tsconfig.json` or the project's `package.json` at runtime, opt in with these flags:

```bash icon="terminal" terminal
# Enable runtime loading of tsconfig.json
Expand Down Expand Up @@ -494,7 +494,7 @@ To disable `.env` or `bunfig.toml` loading for deterministic execution:
compile: {
// tsconfig.json and package.json are disabled by default
autoloadTsconfig: true, // Enable tsconfig.json loading
autoloadPackageJson: true, // Enable package.json loading
autoloadPackageJson: true, // Enable the project's package.json loading

// .env and bunfig.toml are enabled by default
autoloadDotenv: false, // Disable .env loading
Expand Down Expand Up @@ -1299,7 +1299,7 @@ interface CompileBuildOptions {
execArgv?: string[]; // Runtime arguments (process.execArgv)
executablePath?: string; // Bun executable to use instead of downloading one for target
autoloadTsconfig?: boolean; // Load tsconfig.json (default: false)
autoloadPackageJson?: boolean; // Load package.json (default: false)
autoloadPackageJson?: boolean; // Load the project's package.json (default: false)
autoloadDotenv?: boolean; // Load .env files (default: true)
autoloadBunfig?: boolean; // Load bunfig.toml (default: true)
bytecodeOrder?: string | string[] | false | null; // Order file(s) to lay the bytecode out by (requires bytecode: true)
Expand Down
4 changes: 2 additions & 2 deletions docs/snippets/cli/build.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -227,11 +227,11 @@ bun build <entry points>
</ParamField>

<ParamField path="--compile-autoload-package-json" type="boolean" default="false">
Enable autoloading of <code>package.json</code> at runtime in the standalone executable
Read the project's own <code>package.json</code> at runtime in the standalone executable. A dependency's <code>package.json</code> is always read
</ParamField>

<ParamField path="--no-compile-autoload-package-json" type="boolean">
Disable autoloading of <code>package.json</code> at runtime in the standalone executable
Do not read the project's own <code>package.json</code> at runtime in the standalone executable
</ParamField>

<ParamField path="--compile-executable-path" type="string">
Expand Down
4 changes: 3 additions & 1 deletion packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3772,7 +3772,9 @@ declare module "bun" {
*/
autoloadTsconfig?: boolean;
/**
* Whether the standalone executable loads package.json when it runs
* Whether the standalone executable reads the project's own package.json
* (its `type`, `imports`, and self-reference `exports`) when it runs.
* A dependency's package.json is always read.
*
* Equivalent CLI flags: `--compile-autoload-package-json`, `--no-compile-autoload-package-json`
*
Expand Down
1 change: 1 addition & 0 deletions src/resolver/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ pub struct BundleOptions {
// projects this from its own `Option<NonNull<api::BunInstall>>` field
// (CLI-owned `Box<BunInstall>`, process-lifetime).
pub install: Option<core::ptr::NonNull<bun_options_types::schema::api::BunInstall>>,
/// Read the `package.json` of the cwd and its parents. Any other `package.json` is always read.
pub load_package_json: bool,
pub load_tsconfig_json: bool,
pub main_field_extension_order: Box<[Box<[u8]>]>,
Expand Down
9 changes: 8 additions & 1 deletion src/resolver/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6428,7 +6428,7 @@ impl<'a> Resolver<'a> {
}

// Record if this directory has a package.json file
if self.opts.load_package_json {
if self.opts.load_package_json || !self.is_project_config_dir(path) {
Comment thread
robobun marked this conversation as resolved.
Resolved
if let Some(lookup) = entries!().get_comptime_query(b"package.json") {
// SAFETY: EntryStore-owned slot; `entries_mutex` held — read-only borrow,
// dies (NLL) before any later `&mut` to this slot.
Expand Down Expand Up @@ -6700,6 +6700,13 @@ impl<'a> Resolver<'a> {
Ok(None)
}

/// `dir` is the cwd or one of its parents. Their `package.json` is the project's config,
/// which `load_package_json` gates. Any other `package.json` is a resolution target.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn is_project_config_dir(&self, dir: &[u8]) -> bool {
use ResolvePath::resolve_path::{ParentEqual, is_parent_or_equal};
is_parent_or_equal(dir, self.fs_ref().top_level_dir()) != ParentEqual::Unrelated
Comment thread
robobun marked this conversation as resolved.
Resolved
}

/// `opts.tsconfig_override`, which this resolver and its workers read in place of the
/// configuration file of every directory. It is not in `DirInfo`, which every resolver of the
/// process shares: the runtime, and every `Bun.build`. `None`: there is none.
Expand Down
4 changes: 2 additions & 2 deletions src/runtime/cli/Arguments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -433,10 +433,10 @@ pub(crate) const BUILD_ONLY_PARAMS: &[ParamType] = concat_params!(
"--no-compile-autoload-tsconfig Disable autoloading of tsconfig.json at runtime in standalone executable"
),
parse_param!(
"--compile-autoload-package-json Enable autoloading of package.json at runtime in standalone executable (default: false)"
"--compile-autoload-package-json Read the project's package.json at runtime in standalone executable (default: false)"
),
parse_param!(
"--no-compile-autoload-package-json Disable autoloading of package.json at runtime in standalone executable"
"--no-compile-autoload-package-json Do not read the project's package.json at runtime in standalone executable"
),
parse_param!(
"--compile-executable-path <STR> Path to a Bun executable to use for cross-compilation instead of downloading"
Expand Down
109 changes: 108 additions & 1 deletion test/bundler/bundler_compile.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Database } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
import { rmSync } from "fs";
import { rmSync, symlinkSync } from "fs";
import { bunEnv, bunExe, isWindows, tempDir } from "harness";
import { join } from "path";
import { BundlerTestInput, itBundled as itBundledBase } from "./expectBundled";
Expand Down Expand Up @@ -1008,6 +1008,62 @@ describe("bundler", () => {
},
compile: true,
});
// A package inside node_modules is resolved through its own package.json at runtime, even
// though the executable does not load the project's package.json by default.
itBundled("compile/DynamicRequirePackageJsonMainAndExports", {
files: {
"/entry.tsx": /* tsx */ `
const req = (x) => require(x);
const m = req('with-main');
const e = req('with-exports/feature');
console.log(JSON.stringify([m, e]));
module.exports = null;
`,
"/node_modules/with-main/package.json": JSON.stringify({ name: "with-main", main: "lib/main.js" }),
"/node_modules/with-main/lib/main.js": "throw new Error('Must be runtime import.')",
"/node_modules/with-exports/package.json": JSON.stringify({
name: "with-exports",
exports: { "./feature": "./lib/feature.js" },
}),
"/node_modules/with-exports/lib/feature.js": "throw new Error('Must be runtime import.')",
},
runtimeFiles: {
"/node_modules/with-main/package.json": JSON.stringify({ name: "with-main", main: "lib/main.js" }),
"/node_modules/with-main/lib/main.js": "module.exports = 4;",
"/node_modules/with-exports/package.json": JSON.stringify({
name: "with-exports",
exports: { "./feature": "./lib/feature.js" },
}),
"/node_modules/with-exports/lib/feature.js": "module.exports = 5;",
},
run: {
stdout: "[4,5]",
setCwd: true,
},
compile: true,
});
// A static import of an --external package is resolved at startup from the cwd's node_modules
// through the package's main field.
itBundled("compile/ExternalPackageWithMain", {
external: ["with-main"],
files: {
"/entry.tsx": /* tsx */ `
import value from "with-main";
console.log(value);
`,
"/node_modules/with-main/package.json": JSON.stringify({ name: "with-main", main: "lib/main.js" }),
"/node_modules/with-main/lib/main.js": "throw new Error('Must be runtime import.')",
},
runtimeFiles: {
"/node_modules/with-main/package.json": JSON.stringify({ name: "with-main", main: "lib/main.js" }),
"/node_modules/with-main/lib/main.js": "module.exports = 'external-main';",
},
run: {
stdout: "external-main",
setCwd: true,
},
compile: true,
});
itBundled("compile/DynamicImport", {
files: {
"/entry.tsx": /* tsx */ `
Expand Down Expand Up @@ -1545,6 +1601,57 @@ const server = serve({
}, 30_000);

// When compiling with 8+ entry points, the main entry point should still run correctly.
// A package that node_modules reaches by symlink (a workspace or `bun link`) has its own
// package.json read at runtime: its main, its exports, and its #imports from the real path.
test.skipIf(isWindows)("compile resolves a symlinked node_modules package through its package.json", async () => {
Comment thread
robobun marked this conversation as resolved.
Resolved
await using dir = tempDir("compile-linked-pkg", {
"app.js": `
const req = (x) => require(x);
console.log(JSON.stringify([req("linked-pkg"), req("linked-pkg/feature")]));
`,
"packages/linked-pkg/package.json": JSON.stringify({
name: "linked-pkg",
main: "lib/main.js",
exports: { ".": "./lib/main.js", "./feature": "./lib/feature.js" },
imports: { "#util": "./lib/util.js" },
}),
"packages/linked-pkg/lib/main.js": `module.exports = require("#util") + "-main";`,
"packages/linked-pkg/lib/feature.js": `module.exports = require("#util") + "-feature";`,
"packages/linked-pkg/lib/util.js": `module.exports = "util";`,
"node_modules/.keep": "",
});
symlinkSync(join(String(dir), "packages", "linked-pkg"), join(String(dir), "node_modules", "linked-pkg"));

await Bun.$`${bunExe()} build --compile app.js --outfile app`.cwd(dir).env(bunEnv).throws(true);

const result = await Bun.$`./app`.cwd(dir).env(bunEnv).nothrow();
expect(result.stderr.toString()).toBe("");
expect(result.stdout.toString().trim()).toBe('["util-main","util-feature"]');
expect(result.exitCode).toBe(0);
});

// A directory on NODE_PATH is not the project's config, so its package.json is read.
test("compile resolves a NODE_PATH package through its package.json main", async () => {
await using dir = tempDir("compile-node-path-pkg", {
"app.js": `
const req = (x) => require(x);
console.log(req("path-pkg"));
`,
"libs/path-pkg/package.json": JSON.stringify({ name: "path-pkg", main: "lib/main.js" }),
"libs/path-pkg/lib/main.js": `module.exports = "from-node-path";`,
});

await Bun.$`${bunExe()} build --compile app.js --outfile app`.cwd(dir).env(bunEnv).throws(true);

const result = await Bun.$`./app`
.cwd(dir)
.env({ ...bunEnv, NODE_PATH: join(String(dir), "libs") })
.nothrow();
expect(result.stderr.toString()).toBe("");
expect(result.stdout.toString().trim()).toBe("from-node-path");
expect(result.exitCode).toBe(0);
});

test("compile with 8+ entry points runs main entry correctly", async () => {
await using dir = tempDir("compile-many-entries", {
"app.js": `console.log("IT WORKS");`,
Comment thread
robobun marked this conversation as resolved.
Resolved
Expand Down
Loading
Loading