Skip to content

Instantly share code, notes, and snippets.

@FND
Last active November 24, 2023 06:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FND/41738bdc6b358b07bf39f4fdb387a04e to your computer and use it in GitHub Desktop.
Save FND/41738bdc6b358b07bf39f4fdb387a04e to your computer and use it in GitHub Desktop.
sharing code between bundles, explicitly
/node_modules
/package-lock.json
/dist

sharing code between bundles, explicitly

here the core bundle includes and exposes utilities, which are imported and invoked by an auxiliary bundle

overview

Getting Started

  • ensure Node is installed

  • npm install downloads dependencies

  • npm start builds and executes bundles

#!/usr/bin/env node
import * as esbuild from "esbuild";
import { fileURLToPath } from "node:url";
import path from "node:path";
let ROOT_DIR = path.dirname(fileURLToPath(import.meta.url));
await build({
entryPoints: [
path.resolve(ROOT_DIR, "./index.core.js"),
path.resolve(ROOT_DIR, "./index.aux.js")
],
bundle: true,
format: "esm",
target: "es2022",
external: ["./index.*.js"],
outdir: path.resolve(ROOT_DIR, "./dist")
});
async function build(config) {
let { watch, serve, ...settings } = config;
if (watch || serve) {
let context = await esbuild.context(settings);
await Promise.all[
serve && context.serve(),
watch && context.watch()
];
} else {
await esbuild.build(settings);
}
}
export function distance(dx, dy) {
return Math.sqrt(dx ** 2 + dy ** 2);
}
import { distance } from "./geo.js";
import { log, STATE } from "./index.core.js";
log("AUX", STATE, "hello world");
log("AUX", "Δ", distance(5, 7));
import { log } from "./util.js";
export { log };
export let [STATE] = crypto.randomUUID().split("-");
log("CORE", STATE, "hello world");
setTimeout(async () => {
log("CORE", STATE, "loading aux");
await import("./index.aux.js");
}, 1000);
{
"scripts": {
"start": "./build.js && node ./dist/index.core.js"
},
"type": "module",
"devDependencies": {
"esbuild": "^0.19.7"
}
}
export function log(prefix, ...msg) {
console.log(`[${prefix}]`.padEnd(6, " "), ...msg);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment