Replies: 3 comments 2 replies
-
You could try with a dynamic import like so: // use user-passed file
const givenPath = process.argv[2];
// dynamic import
// warning: configured like so it only runs files in the current project folder
// you should probably consider converting relative paths to absolute when importing
const { default: importedFn } = await import(`./${givenPath}`);
importedFn(); Compile your code: bun build ./index.ts --compile --outfile index Run JS/TS files that export a default function: export default function() {
console.log('Hello, world!');
} $ ./index example.ts
Hello, world! Warning While this might be a solution, you should always remember you're not actually creating a different process but you're importing and executing a function directly on your main process, so make sure to only run trusted code in this way. |
Beta Was this translation helpful? Give feedback.
-
@mnapoli look like: $ my-cli-containing-bun add -D dayjs try bundling Bun together, but resulting file size will be larger, $ bun build --compile --target=bun-linux-arm64 ./index.ts ./bun-linux-aarch64/bun --outfile my-cli-containing-bun entry file(index.ts): import { $, argv, embeddedFiles, file, readableStreamToText, spawn, write } from 'bun'
// check if additional parameters were passed, for example, running ./my-cli-containing-bun a.ts
if (argv.length > 2) {
// Write the asset file - the Bun CLI, into a directory within the current one, such as `.bin`
// and give bun executable permissions.
if (!await file('./.bin/bun').exists()) {
await write(file('./.bin/bun'), embeddedFiles[0])
await $`chmod 777 ./.bin/bun`
}
// as the Bun CLI to execute.
const { stdout } = await spawn(['./.bin/bun', ...argv.slice(2)])
console.log(await readableStreamToText(stdout))
}
else {
// other cases, proceed with normal code execution.
console.log('normal code...')
} of course, this is not the optimal solution. await $`bun a.ts` , but for a single executable file, this Bun is you can easily get the asset file via however, there is no documentation explaining how to get the embedded Bun CLI; otherwise, there would be no need to bundle the Bun CLI as an asset file. |
Beta Was this translation helpful? Give feedback.
-
Imagine I compile a CLI using Bun into a standalone executable (https://bun.sh/docs/bundler/executables).
Users install my binary by downloading it on their machine.
Then, I want my CLI to execute a JS file using the Bun runtime that is bundled in this executable.
E.g. instead of running:
it would look like this:
my-cli-containing-bun # this script runs "bun ./script.js" with "bun" being the engine from my CLI
Is that possible? If yes, how?
I would guess that I need to spawn a subprocess, but instead of spawning
bun run
I need to run the internal Bun engine…Beta Was this translation helpful? Give feedback.
All reactions