Bundle an fw app into one file
Bundle an app and only the fw modules it uses into one minified file that needs no import map.
Apache-2.0Command line
Package: @awacloud/fw
Run it
Command line Guide
Bundle an app's entry and only the fw modules it uses into one minified ES
module, with Bun's own bundler and no plugin: the page then loads one file,
with no import map and no /vendor/ tree to serve.
Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.
When to use it
You already ship your app through a bundler, or want one request instead of one per module. fw needs nothing special for that: import its modules by subpath, register them on a runtime, and any bundler follows the imports and keeps only what is reached. The no-build path of the other examples (an import map onto fw's sources) stays the simplest during development.
Copy-paste steps
npm install @awacloud/fw- Copy
app.jsandmain.jsnext to each other and runbun main.js dist: it writesdist/app.jsand prints its size and a check of what it does. - Load it from your page with
<script type="module" src="dist/app.js"></script>. - With Vite, esbuild or rollup, build the same
app.jsunchanged (for examplevite buildwithapp.jsas the input): the imports are plain package subpaths. fw's bundler plugins (@awacloud/fw/vite,@awacloud/fw/esbuild,@awacloud/fw/rollup,@awacloud/fw/bun) are only needed for its ready-made presets.
What it shows
app.jsimportsModuleRuntimefrom@awacloud/fw/core/runtime.jsand two descriptors by subpath, thenregisterAllDeep([hex, crc32]): the bundle holds those modules and the runtime, not the whole framework (some 8 kB minified here).Bun.build({ entrypoints, outdir, target: 'browser', format: 'esm', minify: true })resolves the@awacloud/fw/…specifiers fromnode_modules; no bare specifier is left in the output, which is why the page needs no import map.- A failed build reports the bundler's own messages.
- The entry stays quiet when imported outside a page (a test, a worker) and
fills
#outinside one.
Code
main.js
// SPDX-License-Identifier: Apache-2.0
// Run: bun main.js [outDir] (Bun only: it calls Bun.build). Builds app.js and prints what came out.
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { basename, join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
/** The app's entry: plain fw subpath imports, nothing bundler-specific. */
export const ENTRY = fileURLToPath(new URL('./app.js', import.meta.url));
/**
* Bundle the entry and every fw module it reaches into one minified ES
* module for browsers: a page loads it with one `<script type="module">`,
* no import map, no `/vendor/` tree.
* @param {string} outdir
* @param {string} [entry]
* @returns {Promise<{ file: string, bytes: number, bareSpecifiers: number }>}
*/
export async function bundle(outdir, entry = ENTRY) {
let result;
try {
result = await Bun.build({ entrypoints: [entry], outdir, target: 'browser', format: 'esm', minify: true });
} catch (error) {
result = { success: false, logs: /** @type {any} */ (error)?.errors ?? [error], outputs: [] };
}
const why = result.logs.map(String).join('; ');
if (!result.success) throw new AggregateError(result.logs, `Bun.build failed: ${why}`);
const [output] = result.outputs;
const code = await Bun.file(output.path).text();
return { file: output.path, bytes: output.size, bareSpecifiers: (code.match(/@awacloud\//g) ?? []).length };
}
/**
* @param {string[]} argv `[outDir]`; without one, a scratch directory is used and removed
* @returns {Promise<string[]>} report lines
*/
export async function main(argv = process.argv.slice(2)) {
const scratch = argv[0] ? null : mkdtempSync(join(tmpdir(), 'awa-example-bundle-'));
try {
const built = await bundle(argv[0] ?? /** @type {string} */ (scratch));
const app = await import(pathToFileURL(built.file).href);
const { hex, crc32 } = app.describe('Hello');
return [
`bundle: ${basename(built.file)}, ${built.bytes} bytes, minified`,
`bare @awacloud specifiers left: ${built.bareSpecifiers}`,
`describe("Hello"): hex ${hex}, crc32 ${crc32}`,
];
} finally {
if (scratch) rmSync(scratch, { recursive: true, force: true });
}
}
if (import.meta.main) for (const line of await main()) console.log(line);app.js
// SPDX-License-Identifier: Apache-2.0
// The app entry a bundler starts from. fw comes in by subpath, each module
// registered on the app's own runtime, so the bundle holds only what is used.
import { ModuleRuntime } from '@awacloud/fw/core/runtime.js';
import { hex } from '@awacloud/fw/io/codec/hex.js';
import { crc32 } from '@awacloud/fw/io/calc/crc32.js';
const runtime = new ModuleRuntime().registerAllDeep([hex, crc32]);
const HEX = runtime.resolve('hex');
const Crc32 = runtime.resolve('crc32');
const encoder = new TextEncoder();
/**
* @param {string} text
* @returns {{ hex: string, crc32: string }} the UTF-8 bytes in hex and their CRC-32
*/
export function describe(text) {
const bytes = encoder.encode(text);
const crc = new Crc32();
crc.append(bytes);
return { hex: HEX.fromBytes(bytes), crc32: crc.get().toString(16).padStart(8, '0') };
}
// In a page, show it; imported elsewhere (a test, a worker), stay quiet.
if (typeof document !== 'undefined' && document.getElementById('out')) {
/** @type {HTMLElement} */ (document.getElementById('out')).textContent = JSON.stringify(describe('Hello'));
}