Awesome!
There are ways to import ZON file in Bun, and two of them has 0 performance overhead, so they will work as fast as normal like declaring JS Object inline.
Here are steps in case of your use case:
- Add a .d.ts file so that you don’t get type error.
# zon.d.ts
declare module '*.zon' {
const content: Record<string, any>;
export default content;
}
- Add the bun loader so that import is handled automatically by bun at bundle time. I or someone can publish this bun loader as npm package and it would be even simpler.
# zon.loader.ts
import { plugin } from 'bun';
await plugin({
name: 'ZON',
async setup(build) {
const { ZON } = await import('zzon');
build.onLoad({ filter: /\.(zon)$/ }, async (args) => {
const text = await Bun.file(args.path).text();
const zon = ZON.parse(text) as Record<string, any>;
return {
loader: 'object',
exports: {
default: zon,
},
};
});
},
});
- Define the loader in bunfig.toml
preload = ["./zon.loader.ts"]
- And you just import ZON file and they will be converted to JS Obj and inclined during bundle time.
import data from './../data.zon'; // see zon.loader.ts which describes how to load the file
console.log(data);
Here are all available methods in case you are interested. An older version of the guide is on the repo as well. zzon/example/bun at main · nurulhudaapon/zzon · GitHub
ZON in Bun
There are three ways to use ZON in Bun:
First cd into the example/bun
directory:
cd example/bun
Install the dependencies:
bun install
Using Bun’s loader (Recommended)
Parsing happens at bundle time so 0 performance overhead
No extra files or code to parse
Files: zon.loader.ts, zon.d.ts, loader/index.ts
bun run loader/index.ts
Using Bun’s Macro
Parsing happens at bundle time so 0 performance overhead
Extra files and code is required
Files: macro/index.ts
bun run macro/index.ts
Using Bun’s default text loader
Parsing happens at runtime so performance overhead
Extra code is required to parse the file
Files: import/index.ts
cd import && bun run index.ts