Run it

Command line Guide

Add a preset to fw.config.json, build it with the bundle subcommand, and load one minified file that holds the runtime and those modules with their dependencies, nothing else.

Uses @awacloud/tool-fw-bundler (Apache-2.0) over @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

Production: one request instead of one per module, and fewer bytes than the nearest built-in preset (core, site, spa, pwa, … in fw.config.json). For a single module without the runtime, see fw-bundler/standalone.

Copy-paste steps

  1. npm install @awacloud/fw and npm install --save-dev @awacloud/tool-fw-bundler
  2. Copy node_modules/@awacloud/fw/src/ and fw.config.json into a folder of yours (say fw-build/), and add your preset under presets in the copied fw.config.json: "my-app": { "description": "…", "modules": ["dom", "b64", "storage"] }.
  3. bunx fw-bundler bundle my-app --pkg fw-build --no-sanity --no-log, then load fw-build/dist/build/fw.my-app.pure.min.js. Or copy main.js and run bun main.js node_modules/@awacloud/fw to see the same through the tool's runCli.

What it shows

  • A preset lists the modules the app names; the build pulls their dependencies in through the import graph. The meta file lists the preset's modules.
  • runCli([preset, '--pkg', dir, '--no-sanity', '--no-log']) from @awacloud/tool-fw-bundler/bundle, returning the exit code (0, or 1 for an unknown preset or a build error) without spawning a process.
  • bundle writes into <pkg>/dist/ and replaces what it builds there: point --pkg at a copy, never at node_modules/@awacloud/fw.
  • The outputs: fw.my-app.pure.min.js (its default export is fw, with fw.runtime already holding the preset's modules), the non-minified fw.my-app.pure.js, and fw.my-app.pure.meta.json with the sizes (minified, gzipped) and SHA-256 hashes.
  • --no-log matters. Without it, the bundle starts fw's logger on import: it replaces console for good (a non-configurable property) with a proxy that records every call in fw.log, and a production build (no --dev) does not print them. In a page that is a choice to make knowingly; in a script it silences the script.
  • A module outside the preset is absent: fw.runtime.resolve('gzip') throws. Add it to the preset and rebuild.
  • No build stamp: the same sources build to the same bytes, so the hash in the meta file can be pinned (Subresource Integrity, a release manifest).

Code

main.js

javascriptApache-2.070 lines

// SPDX-License-Identifier: Apache-2.0
// Run: bun main.js [fwPackageDir]   (under Node, install esbuild or rollup: its Node backends)
// Equivalent CLI: bunx fw-bundler bundle my-app --pkg <a copy of the fw package> --no-sanity --no-log
import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { runCli } from '@awacloud/tool-fw-bundler/bundle';

/** The app's preset: the modules it uses; their dependencies come with them. */
export const MY_APP = { description: 'Only what this app uses.', modules: ['dom', 'b64', 'storage'] };

/**
 * A fw-shaped package in `dir`: fw's `src/`, and its `fw.config.json` with the app's preset added.
 * `bundle` writes under `<pkg>/dist/`, so it builds a copy, never the installed package.
 * @param {string} fw the installed fw package @param {string} dir an empty directory
 */
export function preparePackage(fw, dir) {
    cpSync(join(fw, 'src'), join(dir, 'src'), { recursive: true });
    const config = JSON.parse(readFileSync(join(fw, 'fw.config.json'), 'utf8'));
    config.presets['my-app'] = MY_APP;
    writeFileSync(join(dir, 'fw.config.json'), JSON.stringify(config, null, 2));
}

/**
 * Build one preset. `--no-sanity`: without the separate sanity bundle. `--no-log`: without fw's logger,
 * which replaces `console` for good on import and, in a production build, records calls without printing.
 * @param {string} dir @param {string} [name]
 * @returns {Promise<number>} the tool's exit code (0 ok, 1 unknown preset or build error)
 */
export function buildPreset(dir, name = 'my-app') {
    return runCli([name, '--pkg', dir, '--no-sanity', '--no-log']);
}

/** The build: `fw.<preset>.pure.min.js` and its meta (modules, sizes, SHA-256). @param {string} dir */
export function readBuild(dir, name = 'my-app') {
    const base = join(dir, 'dist', 'build', `fw.${name}.pure`);
    return { file: `${base}.min.js`, meta: JSON.parse(readFileSync(`${base}.meta.json`, 'utf8')) };
}

/**
 * @param {string[]} argv
 * @returns {Promise<string[]>} report lines
 */
export async function main(argv = process.argv.slice(2)) {
    const [fw = 'node_modules/@awacloud/fw'] = argv;
    const dir = mkdtempSync(join(tmpdir(), 'awa-example-preset-'));
    try {
        preparePackage(fw, dir);
        const code = await buildPreset(dir);
        if (code !== 0) return [`bundle exited with ${code}`];
        const { file, meta } = readBuild(dir);
        // The bundle is the framework itself, cut to the preset: its default export is `fw`.
        const app = (await import(pathToFileURL(file).href)).default;
        const has = (/** @type {string} */ name) => {
            try { return !!app.runtime.resolve(name); } catch { return false; }
        };
        return [
            `fw.my-app.pure.min.js: ${meta.bytes.min} B, ${meta.bytes.minGz} B gzipped`,
            `b64 of "fw": ${app.runtime.resolve('b64').fromBytes(new TextEncoder().encode('fw'))}`,
            `storage in the bundle: ${has('storage')}; gzip: ${has('gzip')}`,
        ];
    } finally {
        rmSync(dir, { recursive: true, force: true }); // a real build keeps dist/build; this demo cleans up
    }
}

if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
    for (const line of await main()) console.log(line);
}