buildBase.js 3.99 KB
import fs from "node:fs";
import path from "node:path";
import URL from "node:url";

import commonjs from "@rollup/plugin-commonjs";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import postcss from "rollup-plugin-postcss";
import typescript from "rollup-plugin-typescript2";
import vue from "rollup-plugin-vue";

const __filename = URL.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

function discoverPackages() {
	const base = path.resolve(__dirname, "../packages");
	const result = [];
	// tools
	const toolsPath = path.resolve(base, "tools");
	if (fs.existsSync(path.resolve(toolsPath, "package.json"))) {
		result.push("tools");
	}
	// charts
	const chartsPath = path.resolve(base, "charts");
	if (fs.existsSync(path.resolve(chartsPath, "package.json"))) {
		result.push("charts");
	}
	// cli
	const cliPath = path.resolve(base, "cli");
	if (fs.existsSync(path.resolve(cliPath, "package.json"))) {
		result.push("cli");
	}
	// components/*
	const componentsPath = path.resolve(base, "components");
	if (fs.existsSync(componentsPath)) {
		const subs = fs.readdirSync(componentsPath, { withFileTypes: true });
		for (const dirent of subs) {
			if (dirent.isDirectory()) {
				const name = dirent.name;
				const pkgPath = path.resolve(componentsPath, name, "package.json");
				if (fs.existsSync(pkgPath)) {
					result.push(`components/${name}`);
				}
			}
		}
	}
	return result;
}

function getPackageRoots() {
	const pkgs = discoverPackages();
	return pkgs.map((pkg) => path.resolve(__dirname, `../packages`, pkg));
}

async function packageJson(root) {
	const pkgPath = path.resolve(root, "package.json");
	const content = await fs.promises.readFile(pkgPath, "utf8");
	return JSON.parse(content);
}

export async function getRollupConfig(root) {
	const config = await packageJson(root);
	const tsconfig = path.resolve(root, "tsconfig.json");
	const { name, formats = [ "esm", "cjs" ] } = config.buildOptions || {};
	const dist = path.resolve(root, "./dist");
	const entry = path.resolve(root, "./src/index.ts");
	if (!fs.existsSync(entry)) {
		return null;
	}
	const isVue = /components[\\/]+vue$/.test(root) || !!(config.peerDependencies && config.peerDependencies.vue);
	const basePlugins = [ nodeResolve(), commonjs(), postcss() ];
	const plugins = isVue
		? [
			vue({ compileTemplate: true }),
			typescript({
				tsconfig,
				tsconfigOverride: { compilerOptions: { outDir: dist } },
				check: false,
			}),
			...basePlugins,
		]
		: [
			typescript({
				tsconfig,
				tsconfigOverride: { compilerOptions: { outDir: dist } },
				check: false,
			}),
			...basePlugins,
		];

	const rollupOptions = {
		input: entry,
		external: isVue ? [ "vue" ] : [],
		plugins,
	};
	const output = [];
	for (const format of formats) {
		const outputItem = {
			format,
			file: path.resolve(dist, `index.${format}.js`),
			sourcemap: true,
			exports: "named",
			globals: isVue ? { vue: "Vue" } : {},
		};
		if (format === "iife") {
			outputItem.name = name || "VenusLib";
		}
		// 为 CLI 的 cjs 产物添加 shebang 以支持作为可执行脚本运行
		const isCli = /[\\/]packages[\\/]+cli$/.test(root);
		if (isCli && format === "cjs") {
			outputItem.banner = "#!/usr/bin/env node";
		}
		output.push(outputItem);
	}
	rollupOptions.output = output;

	rollupOptions.watch = {
		include: path.resolve(root, "src/**"),
		exclude: path.resolve(root, "node_modules/**"),
		clearScreen: false,
	};
	return rollupOptions;
}

export async function getRollupConfigs() {
	const pkgs = discoverPackages();
	const roots = getPackageRoots();
	const configs = await Promise.all(roots.map((root) => getRollupConfig(root)));
	const result = {};
	for (const [ i, pkg ] of pkgs.entries()) {
		const cfg = configs[i];
		if (!cfg) {
			console.warn(`跳过包: ${pkg},缺少入口文件 src/index.ts`);
			continue;
		}
		result[pkg] = cfg;
	}
	return result;
}

export function clearDist(name) {
	const dist = path.resolve(__dirname, `../packages`, name, `dist`);
	if (fs.existsSync(dist)) {
		fs.rmSync(dist, { recursive: true, force: true });
	}
}