Add runtime selection feature between Bun and Node.js

This commit is contained in:
Aman Varshney
2025-03-26 01:40:39 +05:30
parent 45cd2fc113
commit 88afd53a4d
22 changed files with 10432 additions and 224 deletions

View File

@@ -12,10 +12,13 @@ export const DEFAULT_CONFIG: ProjectConfig = {
orm: "drizzle",
auth: true,
addons: [],
examples: [],
git: true,
packageManager: "npm",
noInstall: false,
examples: ["todo"],
turso: false,
backendFramework: "hono",
runtime: "bun",
};
export const dependencyVersionMap = {
@@ -39,6 +42,12 @@ export const dependencyVersionMap = {
husky: "^9.1.7",
"lint-staged": "^15.5.0",
"@hono/node-server": "^1.14.0",
tsx: "^4.19.2",
"@types/node": "^22.13.11",
"@types/bun": "^1.2.6",
} as const;
export type AvailableDependencies = keyof typeof dependencyVersionMap;

View File

@@ -11,6 +11,7 @@ import { setupEnvironmentVariables } from "./env-setup";
import { setupExamples } from "./examples-setup";
import { displayPostInstallInstructions } from "./post-installation";
import { initializeGit, updatePackageConfigurations } from "./project-config";
import { setupRuntime } from "./runtime-setup";
import {
copyBaseTemplate,
fixGitignoreFiles,
@@ -38,6 +39,8 @@ export async function createProject(options: ProjectConfig): Promise<string> {
options.auth,
);
await setupRuntime(projectDir, options.runtime);
await setupExamples(
projectDir,
options.examples,
@@ -73,6 +76,7 @@ export async function createProject(options: ProjectConfig): Promise<string> {
!options.noInstall,
options.orm,
options.addons,
options.runtime,
);
return projectDir;

View File

@@ -1,6 +1,12 @@
import path from "node:path";
import fs from "fs-extra";
import type { ProjectConfig, ProjectDatabase, ProjectOrm } from "../types";
import type {
ProjectAddons,
ProjectConfig,
ProjectDatabase,
ProjectOrm,
Runtime,
} from "../types";
export async function createReadme(projectDir: string, options: ProjectConfig) {
const readmePath = path.join(projectDir, "README.md");
@@ -21,6 +27,7 @@ function generateReadmeContent(options: ProjectConfig): string {
auth,
addons = [],
orm = "drizzle",
runtime = "bun",
} = options;
const packageManagerRunCmd =
@@ -32,7 +39,7 @@ This project was created with [Better-T-Stack](https://github.com/better-t-stack
## Features
${generateFeaturesList(database, auth, addons, orm)}
${generateFeaturesList(database, auth, addons, orm, runtime)}
## Getting Started
@@ -71,38 +78,46 @@ ${generateScriptsList(packageManagerRunCmd, database, orm, auth)}
function generateFeaturesList(
database: ProjectDatabase,
auth: boolean,
features: string[],
addons: ProjectAddons[],
orm: ProjectOrm,
runtime: Runtime,
): string {
const featuresList = [
const addonsList = [
"- **TypeScript** - For type safety and improved developer experience",
"- **TanStack Router** - File-based routing with full type safety",
"- **TailwindCSS** - Utility-first CSS for rapid UI development",
"- **shadcn/ui** - Reusable UI components",
"- **Hono** - Lightweight, performant server framework",
"- **tRPC** - End-to-end type-safe APIs",
`- **${runtime === "bun" ? "Bun" : "Node.js"}** - Runtime environment`,
];
if (database !== "none") {
featuresList.push(
addonsList.push(
`- **${orm === "drizzle" ? "Drizzle" : "Prisma"}** - TypeScript-first ORM`,
`- **${database === "sqlite" ? "SQLite/Turso" : "PostgreSQL"}** - Database engine`,
);
}
if (auth) {
featuresList.push(
addonsList.push(
"- **Authentication** - Email & password authentication with Better Auth",
);
}
for (const feature of features) {
if (feature === "docker") {
featuresList.push("- **Docker** - Containerized deployment");
for (const addon of addons) {
if (addon === "pwa") {
addonsList.push("- **PWA** - Progressive Web App support");
} else if (addon === "tauri") {
addonsList.push("- **Tauri** - Build native desktop applications");
} else if (addon === "biome") {
addonsList.push("- **Biome** - Linting and formatting");
} else if (addon === "husky") {
addonsList.push("- **Husky** - Git hooks for code quality");
}
}
return featuresList.join("\n");
return addonsList.join("\n");
}
function generateDatabaseSetup(

View File

@@ -5,6 +5,7 @@ import type {
ProjectAddons,
ProjectDatabase,
ProjectOrm,
Runtime,
} from "../types";
export function displayPostInstallInstructions(
@@ -14,6 +15,7 @@ export function displayPostInstallInstructions(
depsInstalled: boolean,
orm?: ProjectOrm,
addons?: ProjectAddons[],
runtime?: Runtime,
) {
const runCmd = packageManager === "npm" ? "npm run" : packageManager;
const cdCmd = `cd ${projectName}`;
@@ -21,7 +23,9 @@ export function displayPostInstallInstructions(
addons?.includes("husky") || addons?.includes("biome");
const databaseInstructions =
database !== "none" ? getDatabaseInstructions(database, orm, runCmd) : "";
database !== "none"
? getDatabaseInstructions(database, orm, runCmd, runtime)
: "";
const tauriInstructions = addons?.includes("tauri")
? getTauriInstructions(runCmd)
: "";
@@ -49,6 +53,7 @@ function getDatabaseInstructions(
database: ProjectDatabase,
orm?: ProjectOrm,
runCmd?: string,
runtime?: Runtime,
): string {
const instructions = [];
@@ -59,6 +64,13 @@ function getDatabaseInstructions(
`${pc.dim("Learn more at: https://www.prisma.io/docs/orm/overview/databases/turso")}`,
);
}
if (runtime === "bun") {
instructions.push(
`${pc.yellow("NOTE:")} Prisma with Bun may require additional configuration. If you encounter errors, follow the guidance provided in the error messages`,
);
}
instructions.push(
`${pc.cyan("•")} Apply schema: ${pc.dim(`${runCmd} db:push`)}`,
);

View File

@@ -0,0 +1,94 @@
import path from "node:path";
import fs from "fs-extra";
import type { Runtime } from "../types";
import { addPackageDependency } from "../utils/add-package-deps";
export async function setupRuntime(
projectDir: string,
runtime: Runtime,
): Promise<void> {
const serverDir = path.join(projectDir, "apps/server");
const serverIndexPath = path.join(serverDir, "src/index.ts");
const indexContent = await fs.readFile(serverIndexPath, "utf-8");
if (runtime === "bun") {
await setupBunRuntime(serverDir, serverIndexPath, indexContent);
} else if (runtime === "node") {
await setupNodeRuntime(serverDir, serverIndexPath, indexContent);
}
}
async function setupBunRuntime(
serverDir: string,
serverIndexPath: string,
indexContent: string,
): Promise<void> {
const packageJsonPath = path.join(serverDir, "package.json");
const packageJson = await fs.readJson(packageJsonPath);
packageJson.scripts = {
...packageJson.scripts,
dev: "bun run --hot src/index.ts",
start: "bun run dist/src/index.js",
};
await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });
addPackageDependency({
devDependencies: ["@types/bun"],
projectDir: serverDir,
});
if (!indexContent.includes("export default app")) {
const updatedContent = `${indexContent}\n\nexport default app;\n`;
await fs.writeFile(serverIndexPath, updatedContent);
}
}
async function setupNodeRuntime(
serverDir: string,
serverIndexPath: string,
indexContent: string,
): Promise<void> {
addPackageDependency({
dependencies: ["@hono/node-server"],
devDependencies: ["tsx", "@types/node"],
projectDir: serverDir,
});
const packageJsonPath = path.join(serverDir, "package.json");
const packageJson = await fs.readJson(packageJsonPath);
packageJson.scripts = {
...packageJson.scripts,
dev: "tsx watch src/index.ts",
start: "node dist/src/index.js",
};
await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });
const importLine = 'import { serve } from "@hono/node-server";\n';
const serverCode = `
serve(
{
fetch: app.fetch,
port: 3000,
},
(info) => {
console.log(\`Server is running on http://localhost:\${info.port}\`);
},
);\n`;
if (!indexContent.includes("@hono/node-server")) {
const importEndIndex = indexContent.lastIndexOf("import");
const importSection = indexContent.substring(0, importEndIndex);
const restOfFile = indexContent.substring(importEndIndex);
const updatedContent = importSection + importLine + restOfFile + serverCode;
await fs.writeFile(serverIndexPath, updatedContent);
} else if (!indexContent.includes("serve(")) {
const updatedContent = indexContent + serverCode;
await fs.writeFile(serverIndexPath, updatedContent);
}
}

View File

@@ -5,7 +5,12 @@ import { DEFAULT_CONFIG } from "./constants";
import { createProject } from "./helpers/create-project";
import { installDependencies } from "./helpers/install-dependencies";
import { gatherConfig } from "./prompts/config-prompts";
import type { ProjectAddons, ProjectConfig, ProjectExamples } from "./types";
import type {
ProjectAddons,
ProjectConfig,
ProjectExamples,
Runtime,
} from "./types";
import { displayConfig } from "./utils/display-config";
import { generateReproducibleCommand } from "./utils/generate-reproducible-command";
import { getLatestCLIVersion } from "./utils/get-latest-cli-version";
@@ -50,6 +55,8 @@ async function main() {
.option("--no-install", "Skip installing dependencies")
.option("--turso", "Set up Turso for SQLite database")
.option("--no-turso", "Skip Turso setup for SQLite database")
.option("--hono", "Use Hono backend framework")
.option("--runtime <runtime>", "Specify runtime (bun or node)")
.parse();
const s = spinner();
@@ -70,11 +77,13 @@ async function main() {
...(options.prisma && { orm: "prisma" }),
...("auth" in options && { auth: options.auth }),
...(options.npm && { packageManager: "npm" }),
...(options.pnpm && { packageManager: " pnpm" }),
...(options.pnpm && { packageManager: "pnpm" }),
...(options.bun && { packageManager: "bun" }),
...("git" in options && { git: options.git }),
...("install" in options && { noInstall: !options.install }),
...("turso" in options && { turso: options.turso }),
...(options.hono && { backendFramework: "hono" }),
...(options.runtime && { runtime: options.runtime as Runtime }),
...((options.pwa ||
options.tauri ||
options.biome ||
@@ -144,6 +153,12 @@ async function main() {
: flagConfig.database === "sqlite"
? DEFAULT_CONFIG.turso
: false,
backendFramework: options.hono
? "hono"
: DEFAULT_CONFIG.backendFramework,
runtime: options.runtime
? (options.runtime as Runtime)
: DEFAULT_CONFIG.runtime,
}
: await gatherConfig(flagConfig);

View File

@@ -0,0 +1,30 @@
// import { cancel, isCancel, select } from "@clack/prompts";
// import pc from "picocolors";
import type { BackendFramework } from "../types";
export async function getBackendFrameworkChoice(
backendFramework?: BackendFramework,
): Promise<BackendFramework> {
if (backendFramework !== undefined) return backendFramework;
return "hono";
// const response = await select<BackendFramework>({
// message: "Which backend framework would you like to use?",
// options: [
// {
// value: "hono",
// label: "Hono",
// hint: "Lightweight, ultrafast web framework",
// },
// ],
// initialValue: "hono",
// });
// if (isCancel(response)) {
// cancel(pc.red("Operation cancelled"));
// process.exit(0);
// }
// return response;
}

View File

@@ -1,15 +1,18 @@
import { cancel, group } from "@clack/prompts";
import pc from "picocolors";
import type {
BackendFramework,
PackageManager,
ProjectAddons,
ProjectConfig,
ProjectDatabase,
ProjectExamples,
ProjectOrm,
Runtime,
} from "../types";
import { getAddonsChoice } from "./addons";
import { getAuthChoice } from "./auth";
import { getBackendFrameworkChoice } from "./backend-framework";
import { getDatabaseChoice } from "./database";
import { getExamplesChoice } from "./examples";
import { getGitChoice } from "./git";
@@ -17,9 +20,10 @@ import { getNoInstallChoice } from "./install";
import { getORMChoice } from "./orm";
import { getPackageManagerChoice } from "./package-manager";
import { getProjectName } from "./project-name";
import { getRuntimeChoice } from "./runtime";
import { getTursoSetupChoice } from "./turso";
interface PromptGroupResults {
type PromptGroupResults = {
projectName: string;
database: ProjectDatabase;
orm: ProjectOrm;
@@ -30,7 +34,9 @@ interface PromptGroupResults {
packageManager: PackageManager;
noInstall: boolean;
turso: boolean;
}
backendFramework: BackendFramework;
runtime: Runtime;
};
export async function gatherConfig(
flags: Partial<ProjectConfig>,
@@ -40,6 +46,8 @@ export async function gatherConfig(
projectName: async () => {
return getProjectName(flags.projectName);
},
runtime: () => getRuntimeChoice(flags.runtime),
backendFramework: () => getBackendFrameworkChoice(flags.backendFramework),
database: () => getDatabaseChoice(flags.database),
orm: ({ results }) =>
getORMChoice(flags.orm, results.database !== "none"),
@@ -75,5 +83,7 @@ export async function gatherConfig(
packageManager: result.packageManager,
noInstall: result.noInstall,
turso: result.turso,
backendFramework: result.backendFramework,
runtime: result.runtime,
};
}

View File

@@ -1,6 +1,6 @@
import { cancel, isCancel, select } from "@clack/prompts";
import pc from "picocolors";
import type { PackageManager } from "../types";
import type { PackageManager, Runtime } from "../types";
import { getUserPkgManager } from "../utils/get-package-manager";
export async function getPackageManagerChoice(

View File

@@ -0,0 +1,31 @@
import { cancel, isCancel, select } from "@clack/prompts";
import pc from "picocolors";
import type { Runtime } from "../types";
export async function getRuntimeChoice(runtime?: Runtime): Promise<Runtime> {
if (runtime !== undefined) return runtime;
const response = await select<Runtime>({
message: "Which runtime would you like to use?",
options: [
{
value: "bun",
label: "Bun",
hint: "Fast all-in-one JavaScript runtime",
},
{
value: "node",
label: "Node.js",
hint: "Traditional Node.js runtime",
},
],
initialValue: "bun",
});
if (isCancel(response)) {
cancel(pc.red("Operation cancelled"));
process.exit(0);
}
return response;
}

View File

@@ -3,6 +3,8 @@ export type ProjectOrm = "drizzle" | "prisma" | "none";
export type PackageManager = "npm" | "pnpm" | "bun";
export type ProjectAddons = "pwa" | "tauri" | "biome" | "husky";
export type ProjectExamples = "todo";
export type BackendFramework = "hono";
export type Runtime = "bun" | "node";
export interface ProjectConfig {
projectName: string;
@@ -15,4 +17,6 @@ export interface ProjectConfig {
packageManager: PackageManager;
noInstall?: boolean;
turso?: boolean;
backendFramework: BackendFramework;
runtime: Runtime;
}

View File

@@ -16,6 +16,9 @@ export function displayConfig(config: Partial<ProjectConfig>) {
if (config.auth !== undefined) {
configDisplay.push(`${pc.blue("Authentication:")} ${config.auth}`);
}
if (config.runtime) {
configDisplay.push(`${pc.blue("Runtime:")} ${config.runtime}`);
}
if (config.addons?.length) {
configDisplay.push(`${pc.blue("Addons:")} ${config.addons.join(", ")}`);
}

View File

@@ -63,6 +63,10 @@ export function generateReproducibleCommand(config: ProjectConfig): string {
}
}
if (config.runtime) {
flags.push(`--runtime ${config.runtime}`);
}
const baseCommand = "npx create-better-t-stack";
const projectName = config.projectName ? ` ${config.projectName}` : "";
const flagString = flags.length > 0 ? ` ${flags.join(" ")}` : "";