UNPKG

weapp-vite

Version:

weapp-vite 一个现代化的小程序打包工具

83 lines (82 loc) 2.46 kB
import { t as createCompilerContext } from "./createContext-D9HCnUmH.mjs"; import path from "node:path"; import process from "node:process"; import chokidar from "chokidar"; //#region src/testArtifact.ts let pendingBuild = Promise.resolve(); function enqueueBuild(task) { const result = pendingBuild.then(task, task); pendingBuild = result.then(() => void 0, () => void 0); return result; } function resolveTestOutDir(cwd, outDir) { return path.resolve(cwd, outDir ?? ".weapp-vite/test-artifacts"); } async function buildTestArtifact(options = {}) { return await enqueueBuild(async () => { const cwd = path.resolve(options.cwd ?? process.cwd()); const outDir = resolveTestOutDir(cwd, options.outDir); const inlineConfig = { build: { emptyOutDir: true, outDir } }; const ctx = await createCompilerContext({ cwd, mode: options.mode ?? "test", isDev: false, configFile: options.configFile, inlineConfig, outputRoot: outDir, projectConfigPath: options.projectConfigPath, emitDefaultAutoImportOutputs: false, preloadAppEntry: false, syncSupportFiles: false }); await ctx.buildService.build({ skipNpm: options.skipNpm }); return { appConfigPath: path.join(ctx.configService.outDir, "app.json"), miniprogramRootPath: ctx.configService.outDir, projectPath: cwd, sourceRootPath: ctx.configService.absoluteSrcRoot }; }); } async function watchTestArtifact(options = {}) { let artifact = await buildTestArtifact(options); let closed = false; let scheduled; const rebuild = async () => { if (closed) throw new Error("The weapp-vite test artifact watcher has already closed."); artifact = await buildTestArtifact(options); await options.onRebuilt?.(artifact); return artifact; }; const scheduleRebuild = () => { if (closed || scheduled) return; scheduled = setTimeout(() => { scheduled = void 0; rebuild().catch((error) => options.onError?.(error)); }, 20); }; const watcher = chokidar.watch(artifact.sourceRootPath, { ignoreInitial: true, ignored: [artifact.miniprogramRootPath] }); watcher.on("add", scheduleRebuild); watcher.on("change", scheduleRebuild); watcher.on("unlink", scheduleRebuild); return { get artifact() { return artifact; }, async close() { if (closed) return; closed = true; if (scheduled) clearTimeout(scheduled); await watcher.close(); }, rebuild }; } //#endregion export { buildTestArtifact, watchTestArtifact };