add react router

This commit is contained in:
Aman Varshney
2025-04-02 19:50:38 +05:30
parent 6325e647ce
commit dafefb8449
78 changed files with 2160 additions and 748 deletions

View File

@@ -9,7 +9,7 @@ export const PKG_ROOT = path.join(distPath, "../");
export const DEFAULT_CONFIG: ProjectConfig = {
projectName: "my-better-t-app",
frontend: ["web"],
frontend: ["tanstack-router"],
database: "sqlite",
orm: "drizzle",
auth: true,

View File

@@ -15,16 +15,17 @@ export async function setupAddons(
packageManager: ProjectPackageManager,
frontends: ProjectFrontend[],
) {
const hasWebFrontend = frontends.includes("web");
const hasWebFrontend =
frontends.includes("react-router") || frontends.includes("tanstack-router");
// if (addons.includes("docker")) {
// await setupDocker(projectDir);
// await setupDocker(projectDir);
// }
if (addons.includes("pwa") && hasWebFrontend) {
await setupPwa(projectDir);
await setupPwa(projectDir, frontends);
}
if (addons.includes("tauri") && hasWebFrontend) {
await setupTauri(projectDir, packageManager);
await setupTauri(projectDir, packageManager, frontends);
}
if (addons.includes("biome")) {
await setupBiome(projectDir);
@@ -34,6 +35,13 @@ export async function setupAddons(
}
}
export function getWebAppDir(
projectDir: string,
frontends: ProjectFrontend[],
): string {
return path.join(projectDir, "apps/web");
}
async function setupBiome(projectDir: string) {
const biomeTemplateDir = path.join(PKG_ROOT, "template/with-biome");
if (await fs.pathExists(biomeTemplateDir)) {
@@ -88,13 +96,13 @@ async function setupHusky(projectDir: string) {
}
}
async function setupPwa(projectDir: string) {
async function setupPwa(projectDir: string, frontends: ProjectFrontend[]) {
const pwaTemplateDir = path.join(PKG_ROOT, "template/with-pwa");
if (await fs.pathExists(pwaTemplateDir)) {
await fs.copy(pwaTemplateDir, projectDir, { overwrite: true });
}
const clientPackageDir = path.join(projectDir, "apps/web");
const clientPackageDir = getWebAppDir(projectDir, frontends);
if (!(await fs.pathExists(clientPackageDir))) {
return;
@@ -106,6 +114,64 @@ async function setupPwa(projectDir: string) {
projectDir: clientPackageDir,
});
const viteConfigPath = path.join(clientPackageDir, "vite.config.ts");
if (await fs.pathExists(viteConfigPath)) {
let viteConfig = await fs.readFile(viteConfigPath, "utf8");
if (!viteConfig.includes("vite-plugin-pwa")) {
const firstImportMatch = viteConfig.match(
/^import .* from ['"](.*)['"]/m,
);
if (firstImportMatch) {
viteConfig = viteConfig.replace(
firstImportMatch[0],
`import { VitePWA } from "vite-plugin-pwa";\n${firstImportMatch[0]}`,
);
} else {
viteConfig = `import { VitePWA } from "vite-plugin-pwa";\n${viteConfig}`;
}
}
const pwaPluginCode = `VitePWA({
registerType: "autoUpdate",
manifest: {
name: "My App",
short_name: "My App",
description: "My App",
theme_color: "#0c0c0c",
},
pwaAssets: {
disabled: false,
config: true,
},
devOptions: {
enabled: true,
},
})`;
if (!viteConfig.includes("VitePWA(")) {
if (frontends.includes("react-router")) {
viteConfig = viteConfig.replace(
/plugins: \[\s*tailwindcss\(\)/,
`plugins: [\n tailwindcss(),\n ${pwaPluginCode}`,
);
} else if (frontends.includes("tanstack-router")) {
viteConfig = viteConfig.replace(
/plugins: \[\s*tailwindcss\(\)/,
`plugins: [\n tailwindcss(),\n ${pwaPluginCode}`,
);
} else {
viteConfig = viteConfig.replace(
/plugins: \[/,
`plugins: [\n ${pwaPluginCode},`,
);
}
}
await fs.writeFile(viteConfigPath, viteConfig);
}
const clientPackageJsonPath = path.join(clientPackageDir, "package.json");
if (await fs.pathExists(clientPackageJsonPath)) {
const packageJson = await fs.readJson(clientPackageJsonPath);

View File

@@ -62,6 +62,7 @@ export async function createProject(options: ProjectConfig): Promise<string> {
options.backend,
options.orm,
options.database,
options.frontend,
);
await setupAuth(projectDir, options.auth);

View File

@@ -4,6 +4,7 @@ import type {
ProjectAddons,
ProjectConfig,
ProjectDatabase,
ProjectFrontend,
ProjectOrm,
ProjectRuntime,
} from "../types";
@@ -28,18 +29,25 @@ function generateReadmeContent(options: ProjectConfig): string {
addons = [],
orm = "drizzle",
runtime = "bun",
frontend = ["tanstack-router"],
} = options;
const hasReactRouter = frontend.includes("react-router");
const hasTanstackRouter = frontend.includes("tanstack-router");
const hasNative = frontend.includes("native");
const packageManagerRunCmd =
packageManager === "npm" ? "npm run" : packageManager;
const port = hasReactRouter ? "5173" : "3001";
return `# ${projectName}
This project was created with [Better-T-Stack](https://github.com/better-t-stack/Better-T-Stack), a modern TypeScript stack that combines React, TanStack Router, Hono, tRPC, and more.
This project was created with [Better-T-Stack](https://github.com/better-t-stack/Better-T-Stack), a modern TypeScript stack that combines React, ${hasTanstackRouter ? "TanStack Router" : "React Router"}, Hono, tRPC, and more.
## Features
${generateFeaturesList(database, auth, addons, orm, runtime)}
${generateFeaturesList(database, auth, addons, orm, runtime, frontend)}
## Getting Started
@@ -57,21 +65,31 @@ Then, run the development server:
${packageManagerRunCmd} dev
\`\`\`
Open [http://localhost:3001](http://localhost:3001) in your browser to see the web application.
${
hasTanstackRouter || hasReactRouter
? `Open [http://localhost:${port}](http://localhost:${port}) in your browser to see the web application.`
: ""
}
${hasNative ? "Use the Expo Go app to run the mobile application.\n" : ""}
The API is running at [http://localhost:3000](http://localhost:3000).
${
addons.includes("pwa") && hasReactRouter
? "\n## PWA Support with React Router v7\n\nThere is a known compatibility issue between VitePWA and React Router v7.\nSee: https://github.com/vite-pwa/vite-plugin-pwa/issues/809\n\nIf you encounter problems with the PWA functionality, you may need to manually modify\nthe service worker registration or consider waiting for a fix from VitePWA.\n"
: ""
}
## Project Structure
\`\`\`
${projectName}/
├── apps/
│ ├── web/ # Frontend application (React, TanStack Router)
│ └── server/ # Backend API (Hono, tRPC)
${hasTanstackRouter || hasReactRouter ? `│ ├── web/ # Frontend application (React, ${hasTanstackRouter ? "TanStack Router" : "React Router"})\n` : ""}${hasNative ? "│ ├── native/ # Mobile application (React Native, Expo)\n" : ""}│ └── server/ # Backend API (Hono, tRPC)
\`\`\`
## Available Scripts
${generateScriptsList(packageManagerRunCmd, database, orm, auth)}
${generateScriptsList(packageManagerRunCmd, database, orm, auth, hasNative)}
`;
}
@@ -81,16 +99,36 @@ function generateFeaturesList(
addons: ProjectAddons[],
orm: ProjectOrm,
runtime: ProjectRuntime,
frontend: ProjectFrontend[],
): string {
const hasTanstackRouter = frontend.includes("tanstack-router");
const hasReactRouter = frontend.includes("react-router");
const hasNative = frontend.includes("native");
const addonsList = [
"- **TypeScript** - For type safety and improved developer experience",
"- **TanStack Router** - File-based routing with full type safety",
];
if (hasTanstackRouter) {
addonsList.push(
"- **TanStack Router** - File-based routing with full type safety",
);
} else if (hasReactRouter) {
addonsList.push("- **React Router** - Declarative routing for React");
}
if (hasNative) {
addonsList.push("- **React Native** - Build mobile apps using React");
addonsList.push("- **Expo** - Tools for React Native development");
}
addonsList.push(
"- **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") {
addonsList.push(
@@ -172,6 +210,7 @@ function generateScriptsList(
database: ProjectDatabase,
orm: ProjectOrm,
auth: boolean,
hasNative: boolean,
): string {
let scripts = `- \`${packageManagerRunCmd} dev\`: Start both web and server in development mode
- \`${packageManagerRunCmd} build\`: Build both web and server
@@ -179,6 +218,11 @@ function generateScriptsList(
- \`${packageManagerRunCmd} dev:server\`: Start only the server
- \`${packageManagerRunCmd} check-types\`: Check TypeScript types across all apps`;
if (hasNative) {
scripts += `
- \`${packageManagerRunCmd} dev:native\`: Start the React Native/Expo development server`;
}
if (database !== "none") {
scripts += `
- \`${packageManagerRunCmd} db:push\`: Push schema changes to database

View File

@@ -17,7 +17,18 @@ export async function setupEnvironmentVariables(
}
if (!envContent.includes("CORS_ORIGIN")) {
envContent += "\nCORS_ORIGIN=http://localhost:3001";
const hasReactRouter = options.frontend.includes("react-router");
const hasTanStackRouter = options.frontend.includes("tanstack-router");
let corsOrigin = "http://localhost:3000";
if (hasReactRouter) {
corsOrigin = "http://localhost:5173";
} else if (hasTanStackRouter) {
corsOrigin = "http://localhost:3001";
}
envContent += `\nCORS_ORIGIN=${corsOrigin}`;
}
if (options.auth) {
@@ -55,20 +66,13 @@ export async function setupEnvironmentVariables(
await fs.writeFile(envPath, envContent.trim());
if (options.frontend.includes("web")) {
const hasReactRouter = options.frontend.includes("react-router");
const hasTanStackRouter = options.frontend.includes("tanstack-router");
if (hasReactRouter || hasTanStackRouter) {
const clientDir = path.join(projectDir, "apps/web");
const clientEnvPath = path.join(clientDir, ".env");
let clientEnvContent = "";
if (await fs.pathExists(clientEnvPath)) {
clientEnvContent = await fs.readFile(clientEnvPath, "utf8");
}
if (!clientEnvContent.includes("VITE_SERVER_URL")) {
clientEnvContent += "VITE_SERVER_URL=http://localhost:3000\n";
}
await fs.writeFile(clientEnvPath, clientEnvContent.trim());
await setupClientEnvFile(clientDir);
}
if (options.frontend.includes("native")) {
@@ -87,3 +91,18 @@ export async function setupEnvironmentVariables(
await fs.writeFile(nativeEnvPath, nativeEnvContent.trim());
}
}
async function setupClientEnvFile(clientDir: string) {
const clientEnvPath = path.join(clientDir, ".env");
let clientEnvContent = "";
if (await fs.pathExists(clientEnvPath)) {
clientEnvContent = await fs.readFile(clientEnvPath, "utf8");
}
if (!clientEnvContent.includes("VITE_SERVER_URL")) {
clientEnvContent += "VITE_SERVER_URL=http://localhost:3000\n";
}
await fs.writeFile(clientEnvPath, clientEnvContent.trim());
}

View File

@@ -10,13 +10,20 @@ export async function setupExamples(
orm: ProjectOrm,
auth: boolean,
backend: ProjectBackend,
frontend: ProjectFrontend[] = ["web"],
frontend: ProjectFrontend[] = ["tanstack-router"],
): Promise<void> {
const hasWebFrontend = frontend.includes("web");
const hasTanstackRouter = frontend.includes("tanstack-router");
const hasReactRouter = frontend.includes("react-router");
const hasWebFrontend = hasTanstackRouter || hasReactRouter;
const routerType = hasTanstackRouter
? "web-tanstack-router"
: "web-react-router";
const webAppExists = await fs.pathExists(path.join(projectDir, "apps/web"));
if (examples.includes("todo") && hasWebFrontend && webAppExists) {
await setupTodoExample(projectDir, orm, auth);
await setupTodoExample(projectDir, orm, auth, routerType);
} else {
await cleanupTodoFiles(projectDir, orm);
}
@@ -27,17 +34,31 @@ export async function setupExamples(
hasWebFrontend &&
webAppExists
) {
await setupAIExample(projectDir);
await setupAIExample(projectDir, routerType);
}
}
async function setupAIExample(projectDir: string): Promise<void> {
async function setupAIExample(
projectDir: string,
routerType: string,
): Promise<void> {
const aiExampleDir = path.join(PKG_ROOT, "template/examples/ai");
if (await fs.pathExists(aiExampleDir)) {
await fs.copy(aiExampleDir, projectDir);
const aiRouteSourcePath = path.join(
aiExampleDir,
`apps/${routerType}/src/routes/ai.tsx`,
);
const aiRouteTargetPath = path.join(
projectDir,
"apps/web/src/routes/ai.tsx",
);
await updateHeaderWithAILink(projectDir);
if (await fs.pathExists(aiRouteSourcePath)) {
await fs.copy(aiRouteSourcePath, aiRouteTargetPath, { overwrite: true });
}
await updateHeaderWithAILink(projectDir, routerType);
const clientDir = path.join(projectDir, "apps/web");
addPackageDependency({
@@ -66,27 +87,27 @@ async function updateServerIndexWithAIRoute(projectDir: string): Promise<void> {
const importSection = `import { streamText } from "ai";\nimport { google } from "@ai-sdk/google";\nimport { stream } from "hono/streaming";`;
const aiRouteHandler = `
app.post("/ai", async (c) => {
const body = await c.req.json();
const messages = body.messages || [];
app.post("/ai", async (c) => {
const body = await c.req.json();
const messages = body.messages || [];
const result = streamText({
model: google("gemini-2.0-flash-exp"),
messages,
});
const result = streamText({
model: google("gemini-2.0-flash-exp"),
messages,
});
c.header("X-Vercel-AI-Data-Stream", "v1");
c.header("Content-Type", "text/plain; charset=utf-8");
c.header("X-Vercel-AI-Data-Stream", "v1");
c.header("Content-Type", "text/plain; charset=utf-8");
return stream(c, (stream) => stream.pipe(result.toDataStream()));
});`;
return stream(c, (stream) => stream.pipe(result.toDataStream()));
});`;
if (indexContent.includes("import {")) {
const lastImportIndex = indexContent.lastIndexOf("import");
const endOfLastImport = indexContent.indexOf("\n", lastImportIndex);
indexContent = `${indexContent.substring(0, endOfLastImport + 1)}
${importSection}
${indexContent.substring(endOfLastImport + 1)}`;
${importSection}
${indexContent.substring(endOfLastImport + 1)}`;
} else {
indexContent = `${importSection}
@@ -118,7 +139,10 @@ ${aiRouteHandler}`;
}
}
async function updateHeaderWithAILink(projectDir: string): Promise<void> {
async function updateHeaderWithAILink(
projectDir: string,
routerType: string,
): Promise<void> {
const headerPath = path.join(
projectDir,
"apps/web/src/components/header.tsx",
@@ -127,24 +151,20 @@ async function updateHeaderWithAILink(projectDir: string): Promise<void> {
if (await fs.pathExists(headerPath)) {
let headerContent = await fs.readFile(headerPath, "utf8");
if (headerContent.includes('{ to: "/todos"')) {
headerContent = headerContent.replace(
/{ to: "\/todos", label: "Todos" },/,
`{ to: "/todos", label: "Todos" },\n { to: "/ai", label: "AI Chat" },`,
);
} else if (headerContent.includes('{ to: "/dashboard"')) {
headerContent = headerContent.replace(
/{ to: "\/dashboard", label: "Dashboard" },/,
`{ to: "/dashboard", label: "Dashboard" },\n { to: "/ai", label: "AI Chat" },`,
);
} else {
headerContent = headerContent.replace(
/const links = \[\s*{ to: "\/", label: "Home" },/,
`const links = [\n { to: "/", label: "Home" },\n { to: "/ai", label: "AI Chat" },`,
);
}
const linksPattern = /const links = \[\s*([^;]*?)\s*\];/s;
const linksMatch = headerContent.match(linksPattern);
await fs.writeFile(headerPath, headerContent);
if (linksMatch) {
const linksContent = linksMatch[1];
if (!linksContent.includes('"/ai"')) {
const updatedLinks = `const links = [\n ${linksContent}${
linksContent.trim().endsWith(",") ? "" : ","
}\n { to: "/ai", label: "AI Chat" },\n ];`;
headerContent = headerContent.replace(linksPattern, updatedLinks);
await fs.writeFile(headerPath, headerContent);
}
}
}
}
@@ -152,12 +172,25 @@ async function setupTodoExample(
projectDir: string,
orm: ProjectOrm,
auth: boolean,
routerType: string,
): Promise<void> {
const todoExampleDir = path.join(PKG_ROOT, "template/examples/todo");
if (await fs.pathExists(todoExampleDir)) {
const todoRouteDir = path.join(todoExampleDir, "apps/web/src/routes");
const targetRouteDir = path.join(projectDir, "apps/web/src/routes");
await fs.copy(todoRouteDir, targetRouteDir, { overwrite: true });
const todoRouteSourceDir = path.join(
todoExampleDir,
`apps/${routerType}/src/routes/todos.tsx`,
);
const todoRouteTargetPath = path.join(
projectDir,
"apps/web/src/routes/todos.tsx",
);
if (await fs.pathExists(todoRouteSourceDir)) {
await fs.copy(todoRouteSourceDir, todoRouteTargetPath, {
overwrite: true,
});
}
if (orm !== "none") {
const todoRouterSourceFile = path.join(
@@ -174,16 +207,51 @@ async function setupTodoExample(
overwrite: true,
});
}
await updateRouterIndexToIncludeTodo(projectDir);
}
await updateHeaderWithTodoLink(projectDir, auth);
await addTodoButtonToHomepage(projectDir);
await updateHeaderWithTodoLink(projectDir, routerType);
}
}
async function updateRouterIndexToIncludeTodo(
projectDir: string,
): Promise<void> {
const routerFile = path.join(projectDir, "apps/server/src/routers/index.ts");
if (await fs.pathExists(routerFile)) {
let routerContent = await fs.readFile(routerFile, "utf8");
if (!routerContent.includes("import { todoRouter }")) {
const lastImportIndex = routerContent.lastIndexOf("import");
const endOfImports = routerContent.indexOf("\n\n", lastImportIndex);
if (endOfImports !== -1) {
routerContent = `${routerContent.slice(0, endOfImports)}
import { todoRouter } from "./todo";${routerContent.slice(endOfImports)}`;
} else {
routerContent = `import { todoRouter } from "./todo";\n${routerContent}`;
}
const routerDefIndex = routerContent.indexOf(
"export const appRouter = router({",
);
if (routerDefIndex !== -1) {
const routerContentStart =
routerContent.indexOf("{", routerDefIndex) + 1;
routerContent = `${routerContent.slice(0, routerContentStart)}
todo: todoRouter,${routerContent.slice(routerContentStart)}`;
}
await fs.writeFile(routerFile, routerContent);
}
}
}
async function updateHeaderWithTodoLink(
projectDir: string,
auth: boolean,
routerType: string,
): Promise<void> {
const headerPath = path.join(
projectDir,
@@ -193,19 +261,20 @@ async function updateHeaderWithTodoLink(
if (await fs.pathExists(headerPath)) {
let headerContent = await fs.readFile(headerPath, "utf8");
if (auth) {
headerContent = headerContent.replace(
/const links = \[\s*{ to: "\/", label: "Home" },\s*{ to: "\/dashboard", label: "Dashboard" },/,
`const links = [\n { to: "/", label: "Home" },\n { to: "/dashboard", label: "Dashboard" },\n { to: "/todos", label: "Todos" },`,
);
} else {
headerContent = headerContent.replace(
/const links = \[\s*{ to: "\/", label: "Home" },/,
`const links = [\n { to: "/", label: "Home" },\n { to: "/todos", label: "Todos" },`,
);
}
const linksPattern = /const links = \[\s*([^;]*?)\s*\];/s;
const linksMatch = headerContent.match(linksPattern);
await fs.writeFile(headerPath, headerContent);
if (linksMatch) {
const linksContent = linksMatch[1];
if (!linksContent.includes('"/todos"')) {
const updatedLinks = `const links = [\n ${linksContent}${
linksContent.trim().endsWith(",") ? "" : ","
}\n { to: "/todos", label: "Todos" },\n ];`;
headerContent = headerContent.replace(linksPattern, updatedLinks);
await fs.writeFile(headerPath, headerContent);
}
}
}
}
@@ -255,25 +324,3 @@ async function updateRouterIndex(projectDir: string): Promise<void> {
await fs.writeFile(routerFile, routerContent);
}
}
async function addTodoButtonToHomepage(projectDir: string): Promise<void> {
const indexPath = path.join(projectDir, "apps/web/src/routes/index.tsx");
if (await fs.pathExists(indexPath)) {
let indexContent = await fs.readFile(indexPath, "utf8");
indexContent = indexContent.replace(
/<div id="buttons"><\/div>/,
`<div id="buttons" className="mt-4 flex flex-col gap-4 sm:flex-row sm:items-center">
<Button asChild>
<Link to="/todos" className="flex items-center">
View Todo Demo
<ArrowRight className="ml-1 h-4 w-4" />
</Link>
</Button>
</div>`,
);
await fs.writeFile(indexPath, indexContent);
}
}

View File

@@ -37,8 +37,14 @@ export function displayPostInstallInstructions(
const nativeInstructions = frontends?.includes("native")
? getNativeInstructions()
: "";
const pwaInstructions =
addons?.includes("pwa") && frontends?.includes("react-router")
? getPwaInstructions()
: "";
const hasWebFrontend = frontends?.includes("web");
const hasTanstackRouter = frontends?.includes("tanstack-router");
const hasReactRouter = frontends?.includes("react-router");
const hasWebFrontend = hasTanstackRouter || hasReactRouter;
const hasNativeFrontend = frontends?.includes("native");
const hasFrontend = hasWebFrontend || hasNativeFrontend;
@@ -49,10 +55,10 @@ ${!depsInstalled ? `${pc.cyan("2.")} ${packageManager} install\n` : ""}${pc.cyan
${pc.bold("Your project will be available at:")}
${
hasFrontend
? `${hasWebFrontend ? `${pc.cyan("•")} Frontend: http://localhost:3001\n` : ""}`
? `${hasWebFrontend ? `${pc.cyan("•")} Frontend: http://localhost:${hasReactRouter ? "5173" : "3001"}\n` : ""}`
: `${pc.yellow("NOTE:")} You are creating a backend-only app (no frontend selected)\n`
}${pc.cyan("•")} API: http://localhost:3000
${nativeInstructions ? `\n${nativeInstructions.trim()}` : ""}${databaseInstructions ? `\n${databaseInstructions.trim()}` : ""}${tauriInstructions ? `\n${tauriInstructions.trim()}` : ""}${lintingInstructions ? `\n${lintingInstructions.trim()}` : ""}`,
${nativeInstructions ? `\n${nativeInstructions.trim()}` : ""}${databaseInstructions ? `\n${databaseInstructions.trim()}` : ""}${tauriInstructions ? `\n${tauriInstructions.trim()}` : ""}${lintingInstructions ? `\n${lintingInstructions.trim()}` : ""}${pwaInstructions ? `\n${pwaInstructions.trim()}` : ""}`,
"Next steps",
);
}
@@ -105,5 +111,9 @@ function getDatabaseInstructions(
}
function getTauriInstructions(runCmd?: string): string {
return `${pc.bold("Desktop app with Tauri:")}\n${pc.cyan("•")} Start desktop app: ${`cd apps/web && ${runCmd} desktop:dev`}\n${pc.cyan("•")} Build desktop app: ${`cd apps/web && ${runCmd} desktop:build`}\n${pc.yellow("NOTE:")} Tauri requires Rust and platform-specific dependencies. See: ${"https://v2.tauri.app/start/prerequisites/"}\n\n`;
return `\n${pc.bold("Desktop app with Tauri:")}\n${pc.cyan("•")} Start desktop app: ${`cd apps/web && ${runCmd} desktop:dev`}\n${pc.cyan("•")} Build desktop app: ${`cd apps/web && ${runCmd} desktop:build`}\n${pc.yellow("NOTE:")} Tauri requires Rust and platform-specific dependencies.\nSee: ${"https://v2.tauri.app/start/prerequisites/"}\n\n`;
}
function getPwaInstructions(): string {
return `${pc.bold("PWA with React Router v7:")}\n${pc.yellow("NOTE:")} There is a known compatibility issue between VitePWA and React Router v7.\nSee: https://github.com/vite-pwa/vite-plugin-pwa/issues/809\n`;
}

View File

@@ -1,14 +1,15 @@
import path from "node:path";
import { log, spinner } from "@clack/prompts";
import { $, execa } from "execa";
import { execa } from "execa";
import fs from "fs-extra";
import pc from "picocolors";
import type { ProjectPackageManager } from "../types";
import type { ProjectFrontend, ProjectPackageManager } from "../types";
import { addPackageDependency } from "../utils/add-package-deps";
export async function setupTauri(
projectDir: string,
packageManager: ProjectPackageManager,
frontends: ProjectFrontend[],
): Promise<void> {
const s = spinner();
const clientPackageDir = path.join(projectDir, "apps/web");
@@ -60,13 +61,18 @@ export async function setupTauri(
args = ["@tauri-apps/cli@latest"];
}
const hasReactRouter = frontends.includes("react-router");
const devUrl = hasReactRouter
? "http://localhost:5173"
: "http://localhost:3001";
args = [
...args,
"init",
`--app-name=${path.basename(projectDir)}`,
`--window-title=${path.basename(projectDir)}`,
"--frontend-dist=dist",
"--dev-url=http://localhost:3001",
`--dev-url=${devUrl}`,
`--before-dev-command=${packageManager} run dev`,
`--before-build-command=${packageManager} run build`,
];

View File

@@ -8,31 +8,86 @@ import type {
ProjectOrm,
} from "../types";
/**
* Copy base template structure but exclude app-specific folders that will be added based on options
*/
export async function copyBaseTemplate(projectDir: string): Promise<void> {
const templateDir = path.join(PKG_ROOT, "template/base");
if (!(await fs.pathExists(templateDir))) {
throw new Error(`Template directory not found: ${templateDir}`);
}
await fs.copy(templateDir, projectDir);
await fs.ensureDir(projectDir);
const rootFiles = await fs.readdir(templateDir);
for (const file of rootFiles) {
const srcPath = path.join(templateDir, file);
const destPath = path.join(projectDir, file);
if (file === "apps") continue;
if (await fs.stat(srcPath).then((stat) => stat.isDirectory())) {
await fs.copy(srcPath, destPath);
} else {
await fs.copy(srcPath, destPath);
}
}
await fs.ensureDir(path.join(projectDir, "apps"));
const serverSrcDir = path.join(templateDir, "apps/server");
const serverDestDir = path.join(projectDir, "apps/server");
if (await fs.pathExists(serverSrcDir)) {
await fs.copy(serverSrcDir, serverDestDir);
}
}
export async function setupFrontendTemplates(
projectDir: string,
frontends: ProjectFrontend[],
): Promise<void> {
if (!frontends.includes("web")) {
const hasTanstackWeb = frontends.includes("tanstack-router");
const hasReactRouterWeb = frontends.includes("react-router");
const hasNative = frontends.includes("native");
if (hasTanstackWeb || hasReactRouterWeb) {
const webDir = path.join(projectDir, "apps/web");
if (await fs.pathExists(webDir)) {
await fs.remove(webDir);
await fs.ensureDir(webDir);
const webBaseDir = path.join(PKG_ROOT, "template/base/apps/web-base");
if (await fs.pathExists(webBaseDir)) {
await fs.copy(webBaseDir, webDir);
}
const frameworkName = hasTanstackWeb
? "web-tanstack-router"
: "web-react-router";
const webFrameworkDir = path.join(
PKG_ROOT,
`template/base/apps/${frameworkName}`,
);
if (await fs.pathExists(webFrameworkDir)) {
await fs.copy(webFrameworkDir, webDir, { overwrite: true });
}
const packageJsonPath = path.join(webDir, "package.json");
if (await fs.pathExists(packageJsonPath)) {
const packageJson = await fs.readJson(packageJsonPath);
packageJson.name = "web";
await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });
}
}
if (!frontends.includes("native")) {
const nativeDir = path.join(projectDir, "apps/native");
if (await fs.pathExists(nativeDir)) {
await fs.remove(nativeDir);
if (hasNative) {
const nativeSrcDir = path.join(PKG_ROOT, "template/base/apps/native");
const nativeDestDir = path.join(projectDir, "apps/native");
if (await fs.pathExists(nativeSrcDir)) {
await fs.copy(nativeSrcDir, nativeDestDir);
}
} else {
await fs.writeFile(
path.join(projectDir, ".npmrc"),
"node-linker=hoisted\n",
@@ -91,14 +146,43 @@ export async function setupAuthTemplate(
framework: ProjectBackend,
orm: ProjectOrm,
database: ProjectDatabase,
frontends: ProjectFrontend[],
): Promise<void> {
if (!auth) return;
const authTemplateDir = path.join(PKG_ROOT, "template/with-auth");
if (await fs.pathExists(authTemplateDir)) {
const clientAuthDir = path.join(authTemplateDir, "apps/web");
const projectClientDir = path.join(projectDir, "apps/web");
await fs.copy(clientAuthDir, projectClientDir, { overwrite: true });
const hasReactRouter = frontends.includes("react-router");
const hasTanStackRouter = frontends.includes("tanstack-router");
if (hasReactRouter || hasTanStackRouter) {
const webDir = path.join(projectDir, "apps/web");
const webBaseAuthDir = path.join(authTemplateDir, "apps/web-base");
if (await fs.pathExists(webBaseAuthDir)) {
await fs.copy(webBaseAuthDir, webDir, { overwrite: true });
}
if (hasReactRouter) {
const reactRouterAuthDir = path.join(
authTemplateDir,
"apps/web-react-router",
);
if (await fs.pathExists(reactRouterAuthDir)) {
await fs.copy(reactRouterAuthDir, webDir, { overwrite: true });
}
}
if (hasTanStackRouter) {
const tanstackAuthDir = path.join(
authTemplateDir,
"apps/web-tanstack-router",
);
if (await fs.pathExists(tanstackAuthDir)) {
await fs.copy(tanstackAuthDir, webDir, { overwrite: true });
}
}
}
const serverAuthDir = path.join(authTemplateDir, "apps/server/src");
const projectServerDir = path.join(projectDir, "apps/server/src");
@@ -141,25 +225,55 @@ export async function setupAuthTemplate(
);
}
}
if (frontends.includes("native")) {
const nativeAuthDir = path.join(authTemplateDir, "apps/native");
const projectNativeDir = path.join(projectDir, "apps/native");
if (await fs.pathExists(nativeAuthDir)) {
await fs.copy(nativeAuthDir, projectNativeDir, { overwrite: true });
}
}
}
}
export async function fixGitignoreFiles(projectDir: string): Promise<void> {
const gitignorePaths = [
path.join(projectDir, "_gitignore"),
path.join(projectDir, "apps/web/_gitignore"),
path.join(projectDir, "apps/native/_gitignore"),
path.join(projectDir, "apps/server/_gitignore"),
];
const gitignorePaths = await findGitignoreFiles(projectDir);
for (const gitignorePath of gitignorePaths) {
if (await fs.pathExists(gitignorePath)) {
const targetPath = path.join(path.dirname(gitignorePath), ".gitignore");
await fs.move(gitignorePath, targetPath);
await fs.move(gitignorePath, targetPath, { overwrite: true });
}
}
}
/**
* Find all _gitignore files in the project recursively
*/
async function findGitignoreFiles(dir: string): Promise<string[]> {
const gitignoreFiles: string[] = [];
const gitignorePath = path.join(dir, "_gitignore");
if (await fs.pathExists(gitignorePath)) {
gitignoreFiles.push(gitignorePath);
}
try {
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory() && entry.name !== "node_modules") {
const subDirPath = path.join(dir, entry.name);
const subDirFiles = await findGitignoreFiles(subDirPath);
gitignoreFiles.push(...subDirFiles);
}
}
} catch (error) {}
return gitignoreFiles;
}
function getOrmTemplateDir(orm: ProjectOrm, database: ProjectDatabase): string {
if (orm === "drizzle") {
return database === "sqlite"

View File

@@ -41,7 +41,10 @@ async function main() {
.option("--orm <type>", "ORM type (none, drizzle, prisma)")
.option("--auth", "Include authentication")
.option("--no-auth", "Exclude authentication")
.option("--frontend <types...>", "Frontend types (web, native, none)")
.option(
"--frontend <types...>",
"Frontend types (tanstack-router, react-router, native, none)",
)
.option(
"--addons <types...>",
"Additional addons (pwa, tauri, biome, husky, none)",
@@ -251,7 +254,9 @@ function validateOptions(options: CLIOptions): void {
if (
options.frontend &&
!options.frontend.includes("web") &&
!options.frontend.some((f) =>
["tanstack-router", "react-router"].includes(f),
) &&
!options.frontend.includes("none")
) {
cancel(
@@ -264,7 +269,12 @@ function validateOptions(options: CLIOptions): void {
}
if (options.frontend && options.frontend.length > 0) {
const validFrontends = ["web", "native", "none"];
const validFrontends = [
"tanstack-router",
"react-router",
"native",
"none",
];
const invalidFrontends = options.frontend.filter(
(frontend: string) => !validFrontends.includes(frontend),
);
@@ -278,6 +288,19 @@ function validateOptions(options: CLIOptions): void {
process.exit(1);
}
const webFrontends = options.frontend.filter(
(f) => f === "tanstack-router" || f === "react-router",
);
if (webFrontends.length > 1) {
cancel(
pc.red(
"Cannot select multiple web frameworks. Choose only one of: tanstack-router, react-router",
),
);
process.exit(1);
}
if (options.frontend.includes("none") && options.frontend.length > 1) {
cancel(pc.red(`Cannot combine 'none' with other frontend options.`));
process.exit(1);
@@ -316,7 +339,9 @@ function validateOptions(options: CLIOptions): void {
if (
hasWebSpecificAddons &&
options.frontend &&
!options.frontend.includes("web") &&
!options.frontend.some((f) =>
["tanstack-router", "react-router"].includes(f),
) &&
!options.frontend.includes("none")
) {
cancel(
@@ -336,13 +361,26 @@ function processFlags(
projectDirectory?: string,
): Partial<ProjectConfig> {
let frontend: ProjectFrontend[] | undefined = undefined;
if (options.frontend) {
if (options.frontend.includes("none")) {
frontend = [];
} else {
frontend = options.frontend.filter(
(f): f is ProjectFrontend => f === "web" || f === "native",
(f): f is ProjectFrontend =>
f === "tanstack-router" || f === "react-router" || f === "native",
);
const webFrontends = frontend.filter(
(f) => f === "tanstack-router" || f === "react-router",
);
if (webFrontends.length > 1) {
const firstWebFrontend = webFrontends[0];
frontend = frontend.filter(
(f) => f === "native" || f === firstWebFrontend,
);
}
}
}
@@ -371,7 +409,12 @@ function processFlags(
(ex): ex is ProjectExamples => ex === "todo" || ex === "ai",
);
if (frontend && frontend.length > 0 && !frontend.includes("web")) {
if (
frontend &&
frontend.length > 0 &&
!frontend.includes("tanstack-router") &&
!frontend.includes("react-router")
) {
examples = [];
log.warn(
pc.yellow("Examples require web frontend - ignoring examples flag"),
@@ -402,7 +445,12 @@ function processFlags(
addon === "husky",
);
if (frontend && frontend.length > 0 && !frontend.includes("web")) {
if (
frontend &&
frontend.length > 0 &&
!frontend.includes("tanstack-router") &&
!frontend.includes("react-router")
) {
addons = addons.filter((addon) => !["pwa", "tauri"].includes(addon));
if (addons.length !== options.addons.length) {
log.warn(

View File

@@ -9,7 +9,9 @@ export async function getAddonsChoice(
): Promise<ProjectAddons[]> {
if (Addons !== undefined) return Addons;
const hasWeb = frontends?.includes("web");
const hasWeb =
frontends?.includes("react-router") ||
frontends?.includes("tanstack-router");
const addonOptions = [
{

View File

@@ -11,7 +11,9 @@ export async function getAuthChoice(
if (!hasDatabase) return false;
const hasNative = frontends?.includes("native");
const hasWeb = frontends?.includes("web");
const hasWeb =
frontends?.includes("tanstack-router") ||
frontends?.includes("react-router");
if (hasNative) {
log.warn(

View File

@@ -18,7 +18,10 @@ export async function getExamplesChoice(
if (database === "none") return [];
const hasWebFrontend = frontends?.includes("web");
const hasWebFrontend =
frontends?.includes("react-router") ||
frontends?.includes("tanstack-router");
if (!hasWebFrontend) return [];
let response: ProjectExamples[] | symbol = [];

View File

@@ -1,4 +1,4 @@
import { cancel, isCancel, multiselect } from "@clack/prompts";
import { cancel, isCancel, multiselect, select } from "@clack/prompts";
import pc from "picocolors";
import { DEFAULT_CONFIG } from "../constants";
import type { ProjectFrontend } from "../types";
@@ -8,28 +8,66 @@ export async function getFrontendChoice(
): Promise<ProjectFrontend[]> {
if (frontendOptions !== undefined) return frontendOptions;
const response = await multiselect<ProjectFrontend>({
message: "Choose frontends",
const frontendTypes = await multiselect({
message: "Select platforms to develop for",
options: [
{
value: "web",
label: "Web App",
hint: "React + TanStack Router web application",
label: "Web",
hint: "React Web Application",
},
{
value: "native",
label: "Native App",
hint: "React Native + Expo application",
label: "Native",
hint: "Create a React Native/Expo app",
},
],
initialValues: DEFAULT_CONFIG.frontend,
required: false,
initialValues: DEFAULT_CONFIG.frontend.some(
(f) => f === "tanstack-router" || f === "react-router",
)
? ["web"]
: [],
});
if (isCancel(response)) {
if (isCancel(frontendTypes)) {
cancel(pc.red("Operation cancelled"));
process.exit(0);
}
return response;
const result: ProjectFrontend[] = [];
if (frontendTypes.includes("web")) {
const webFramework = await select<ProjectFrontend>({
message: "Choose frontend framework",
options: [
{
value: "tanstack-router",
label: "TanStack Router",
hint: "Modern and scalable routing for React Applications",
},
{
value: "react-router",
label: "React Router",
hint: "A userobsessed, standardsfocused, multistrategy router you can deploy anywhere.",
},
],
initialValue:
DEFAULT_CONFIG.frontend.find(
(f) => f === "tanstack-router" || f === "react-router",
) || "tanstack-router",
});
if (isCancel(webFramework)) {
cancel(pc.red("Operation cancelled"));
process.exit(0);
}
result.push(webFramework);
}
if (frontendTypes.includes("native")) {
result.push("native");
}
return result;
}

View File

@@ -5,7 +5,7 @@ export type ProjectAddons = "pwa" | "biome" | "tauri" | "husky";
export type ProjectBackend = "hono" | "elysia";
export type ProjectRuntime = "node" | "bun";
export type ProjectExamples = "todo" | "ai";
export type ProjectFrontend = "web" | "native";
export type ProjectFrontend = "react-router" | "tanstack-router" | "native";
export interface ProjectConfig {
projectName: string;