示例工程 49-handrolled-vite-config

49-handrolled-vite-config/demo-02-externalization/external.ts

typescript · 1.7 KB

import { builtinModules } from "node:module";

type ModuleRef = {
  name: string;
  bytes: number;
};

const BUILTINS = new Set([
  ...builtinModules,
  ...builtinModules.map((name) => `node:${name}`),
]);

function isExternal(name: string): boolean {
  if (name === "electron") return true;
  if (BUILTINS.has(name)) return true;
  return false;
}

function bundle(modules: ModuleRef[]): {
  bundledBytes: number;
  external: string[];
  inlined: string[];
} {
  let bundledBytes = 0;
  const external: string[] = [];
  const inlined: string[] = [];
  for (const module of modules) {
    if (isExternal(module.name)) {
      external.push(module.name);
    } else {
      inlined.push(module.name);
      bundledBytes += module.bytes;
    }
  }
  return { bundledBytes, external, inlined };
}

const mainModules: ModuleRef[] = [
  { name: "electron", bytes: 900_000 },
  { name: "node:fs", bytes: 120_000 },
  { name: "node:path", bytes: 80_000 },
  { name: "./shared/ipc.ts", bytes: 2_400 },
  { name: "./main/window.ts", bytes: 6_800 },
];

const rendererModules: ModuleRef[] = [
  { name: "./src/App.ts", bytes: 12_000 },
  { name: "./src/styles/app.css", bytes: 6_700 },
];

const main = bundle(mainModules);
const renderer = bundle(rendererModules);

const ok =
  main.external.includes("electron") &&
  main.external.includes("node:fs") &&
  main.external.includes("node:path") &&
  main.inlined.length === 2 &&
  main.bundledBytes === 9_200 &&
  renderer.external.length === 0 &&
  renderer.inlined.length === 2 &&
  isExternal("electron") &&
  isExternal("fs") &&
  isExternal("node:fs") &&
  !isExternal("./local.ts");

console.log(
  JSON.stringify({
    evt: "smoke",
    ok,
    main,
    renderer,
    electronIfBundled: mainModules[0]?.bytes,
  }),
);