oven-sh / bun

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

Define `process.platform` and `process.arch` when using `--compile` #2898

Closed paperdave closed 7 months ago

paperdave commented 1 year ago

What is the problem this feature would solve?

I want to combine Assets and FFI. Given this code block we should be able to eliminate it into just one line.

if (process.platform === "linux") {
  if (process.arch === "x64") {
    exports.libPath = require("./lib/libbhk.so");
  } else if (process.arch === "arm64") {
    exports.libPath = require("./lib/libbhk-arm64.so");
  } else {
    throw new Error("Unsupported architecture on linux: " + process.arch);
  }
} else if (process.platform === "darwin") {
  if (process.arch === "x64") {
    exports.libPath = require("./lib/libbhk.dylib");
  } else if(process.arch === "arm64") {
    exports.libPath = require("./lib/libbhk-arm64.dylib");
  } else {
    throw new Error("Unsupported architecture on mac: " + process.arch);
  }
} else if (process.platform === 'win32') {
  if (process.arch === "x64") {
    exports.libPath = require("./lib/libbhk.dll");
  } else {
    throw new Error("Unsupported architecture on windows: " + process.arch);
  }
}

When compiling, this would tree-shake to only including a single asset.

The bundled code on linux x64 would look like this

// ...
var require_libbhk = __commonJS((exports, module) => {
  module.exports = "/code/paperdave/bhk/zig-out/lib/libbhk.so";
});
var $libPath = require_libbhk();
// ...

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

Auto define the above variables dependant on the target bun build --compile is going to.

Also, it might be interesting if we defined some other things like a flag for if we are being bundled/compiled, and we could change behaviors. Though node_env production and custom defines are probably good enough for that.

What alternatives have you considered?

I'm doing this in BunHotKey right now (not compiling, just demoing the asset behaviors)

const build = await Bun.build({
  entrypoints: ["./src/index.ts"],
  target: "bun",
  external: Object.keys(pkg.dependencies),
  define: {
    "process.platform": JSON.stringify(process.platform),
    "process.arch": JSON.stringify(process.arch),
  },
  minify: {
    syntax: true,
  },
  outdir: "dist",
  naming: "index.js",
});
paperdave commented 7 months ago

Done