-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·374 lines (301 loc) · 11.9 KB
/
Copy pathindex.js
File metadata and controls
executable file
·374 lines (301 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
#!/usr/bin/env node
import inquirer from "inquirer";
import { execa } from "execa";
import fs from "fs";
import path from "path";
import chalk from "chalk";
import ora from "ora";
const jokes = [
"Why do programmers prefer dark mode? Because light attracts bugs!",
"Why did the developer go broke? Because he used up all his cache!",
"Why do programmers always mix up Christmas and Halloween? Because Oct 31 == Dec 25!",
"Why was the JavaScript developer sad? Because he didn't Node how to Express himself!",
"Why did the React component feel lost? Because it didn't know its state in life!",
];
function getRandomJoke() {
return jokes[Math.floor(Math.random() * jokes.length)];
}
async function runCommand(command, args, cwd) {
try {
await execa(command, args, { stdio: "inherit", cwd });
} catch (error) {
console.error(chalk.red(`❌ Error running ${command} ${args.join(" ")}:`), error.message);
process.exit(1);
}
}
async function createProject() {
console.log(chalk.bold.cyan("\n🚀 Welcome to the Ultimate Vite React CLI! Let's build something awesome!\n"));
console.log(chalk.yellow(getRandomJoke()));
console.log("\n");
const { projectName, useTypeScript } = await inquirer.prompt([
{ type: "input", name: "projectName", message: "Enter project name:", default: "my-vite-app" },
{ type: "confirm", name: "useTypeScript", message: "Do you want to use TypeScript?", default: true },
]);
const projectPath = path.join(process.cwd(), projectName);
const spinner = ora("Creating Vite React project...").start();
await runCommand("npm", [
"create",
"vite@latest",
projectName,
"--",
"--template",
useTypeScript ? "react-ts" : "react",
]);
const fileExtension = useTypeScript ? "tsx" : "jsx";
spinner.succeed("Vite React project created successfully!");
process.chdir(projectPath);
spinner.start("Installing dependencies...");
await runCommand("npm", ["install"]);
spinner.succeed("Dependencies installed successfully!");
spinner.start("Installing commonly used libraries...");
await runCommand("npm", ["install", "axios", "react-router-dom", "date-fns", "lodash"]);
spinner.succeed("Common libraries installed successfully!");
const { installTailwind } = await inquirer.prompt([
{ type: "confirm", name: "installTailwind", message: "Do you want to install Tailwind CSS?", default: true },
]);
if (installTailwind) {
spinner.start("Installing and configuring Tailwind CSS...");
await runCommand("npm", ["install", "tailwindcss", "@tailwindcss/vite"]);
const tailwindConfig = `/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}`;
fs.writeFileSync("tailwind.config.js", tailwindConfig);
const cssContent = `
@import "tailwindcss";
@tailwind base;
@tailwind components;
@tailwind utilities;`;
fs.writeFileSync("src/index.css", cssContent);
// Update Vite config
const viteConfig = `import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react(),
tailwindcss(),
],
})`;
fs.writeFileSync("vite.config.js", viteConfig);
spinner.succeed("Tailwind CSS installed and configured successfully!");
} else {
console.log(chalk.red("\n😱 Oh no! You're choosing to die by a thousand inline styles. May the CSS gods have mercy on your soul!"));
}
const { componentLibrary } = await inquirer.prompt([
{
type: "list",
name: "componentLibrary",
message: "Choose a component library:",
choices: ["Ant Design 5", "MUI", "None"],
},
]);
if (componentLibrary === "Ant Design 5") {
spinner.start("Installing Ant Design...");
await runCommand("npm", ["install", "antd"]);
spinner.succeed("Ant Design installed successfully!");
} else if (componentLibrary === "MUI") {
spinner.start("Installing MUI...");
await runCommand("npm", ["install", "@mui/material", "@emotion/react", "@emotion/styled"]);
spinner.succeed("MUI installed successfully!");
}
const { installRedux } = await inquirer.prompt([
{ type: "confirm", name: "installRedux", message: "Do you want to install Redux Toolkit?", default: true },
]);
if (installRedux) {
spinner.start("Installing and configuring Redux Toolkit...");
await runCommand("npm", ["install", "@reduxjs/toolkit", "react-redux"]);
const storeContent = `import { configureStore } from "@reduxjs/toolkit";
import exampleSlice from "./exampleSlice";
export const store = configureStore({
reducer: { example: exampleSlice },
});`;
const sliceContent = `import { createSlice } from "@reduxjs/toolkit";
const initialState = { value: 0 };
const exampleSlice = createSlice({
name: "example",
initialState,
reducers: {
increment: (state) => { state.value += 1; },
decrement: (state) => { state.value -= 1; },
},
});
export const { increment, decrement } = exampleSlice.actions;
export default exampleSlice.reducer;`;
fs.mkdirSync("src/store", { recursive: true });
fs.writeFileSync(useTypeScript ? "src/store/store.ts" : "src/store/store.js", storeContent);
fs.writeFileSync(useTypeScript ? "src/store/exampleSlice.ts" : "src/store/exampleSlice.js", sliceContent);
spinner.succeed("Redux Toolkit installed and configured successfully!");
}
const { projectType } = await inquirer.prompt([
{
type: "list",
name: "projectType",
message: "What type of project are you building?",
choices: ["Small", "Large"],
},
]);
if (projectType === "Large") {
const { dataFetchingLibrary } = await inquirer.prompt([
{
type: "list",
name: "dataFetchingLibrary",
message: "Choose a data fetching library:",
choices: ["React Query", "SWR", "None"],
},
]);
if (dataFetchingLibrary === "React Query") {
spinner.start("Installing and configuring React Query...");
await runCommand("npm", ["install", "@tanstack/react-query"]);
await runCommand("npm", ["install", "-D", "@tanstack/eslint-plugin-query"]);
const hookContent = `import { useQuery } from "@tanstack/react-query";
export function useFetchData(queryKey, fetchData) {
return useQuery(queryKey, fetchData);
}`;
fs.mkdirSync("src/hooks", { recursive: true });
fs.writeFileSync(useTypeScript ? "src/hooks/useFetchData.ts" : "src/hooks/useFetchData.js", hookContent);
spinner.succeed("React Query installed and configured successfully!");
} else if (dataFetchingLibrary === "SWR") {
spinner.start("Installing and configuring SWR...");
await runCommand("npm", ["install", "swr"]);
const hookContent = `import useSWR from "swr";
export function useFetchData(url) {
const { data, error } = useSWR(url);
return { data, error };
}`;
fs.mkdirSync("src/hooks", { recursive: true });
fs.writeFileSync(useTypeScript ? "src/hooks/useFetchData.ts" : "src/hooks/useFetchData.js", hookContent);
spinner.succeed("SWR installed and configured successfully!");
}
}
spinner.start("Setting up folder structure and React Router...");
fs.mkdirSync("src/components", { recursive: true });
fs.mkdirSync("src/pages", { recursive: true });
fs.mkdirSync("src/layouts", { recursive: true });
fs.mkdirSync("src/hooks", { recursive: true });
fs.mkdirSync("src/utils", { recursive: true });
// Create layout components
const headerContent = `export default function Header() {
return (
<header className="bg-gray-800 text-white p-4">
<h1 className="text-2xl">My Awesome App</h1>
</header>
);
}`;
fs.writeFileSync(`src/components/Header.${fileExtension}`, headerContent);
const sideMenuContent = `import { Link } from 'react-router-dom';
export default function SideMenu() {
return (
<nav className="bg-gray-200 p-4 h-full">
<ul>
<li><Link to="/" className="block py-2">Home</Link></li>
<li><Link to="/about" className="block py-2">About</Link></li>
<li><Link to="/dashboard" className="block py-2">Dashboard</Link></li>
</ul>
</nav>
);
}`;
fs.writeFileSync(`src/components/SideMenu.${fileExtension}`, sideMenuContent);
const layoutContent = `import Header from '../components/Header';
import SideMenu from '../components/SideMenu';
export default function Layout({ children }) {
return (
<div className="flex flex-col min-h-screen">
<Header />
<div className="flex flex-1">
<SideMenu />
<main className="flex-1 p-4">
{children}
</main>
</div>
</div>
);
}`;
fs.writeFileSync(`src/layouts/Layout.${fileExtension}`, layoutContent);
// Create pages
const homePageContent = `export default function HomePage() {
return <h1 className="text-2xl">Welcome to the Home Page</h1>;
}`;
fs.writeFileSync(`src/pages/HomePage.${fileExtension}`, homePageContent);
const aboutPageContent = `export default function AboutPage() {
return <h1 className="text-2xl">About Us</h1>;
}`;
fs.writeFileSync(`src/pages/AboutPage.${fileExtension}`, aboutPageContent);
const dashboardPageContent = `export default function DashboardPage() {
return <h1 className="text-2xl">Dashboard (Protected Route)</h1>;
}`;
fs.writeFileSync(`src/pages/DashboardPage.${fileExtension}`, dashboardPageContent);
// Create PrivateRoute component
const privateRouteContent = `import { Navigate } from 'react-router-dom';
// This is a dummy authentication check. In a real app, you'd use a proper auth system.
const isAuthenticated = () => {
return localStorage.getItem('token') !== null;
};
export default function PrivateRoute({ children }) {
return isAuthenticated() ? children : <Navigate to="/login" replace />;
}`;
fs.writeFileSync(`src/components/PrivateRoute.${fileExtension}`, privateRouteContent);
// Set up React Router with layout
const appContent = `import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Layout from './layouts/Layout';
import HomePage from './pages/HomePage';
import AboutPage from './pages/AboutPage';
import DashboardPage from './pages/DashboardPage';
import PrivateRoute from './components/PrivateRoute';
function App() {
return (
<Router>
<Layout>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
<Route
path="/dashboard"
element={
<PrivateRoute>
<DashboardPage />
</PrivateRoute>
}
/>
</Routes>
</Layout>
</Router>
);
}
export default App;`;
fs.writeFileSync(`${useTypeScript ? "src/App.tsx" : "src/App.jsx"}`, appContent);
spinner.succeed("Folder structure, layout, and React Router set up successfully!");
console.log(chalk.green.bold("\n✨ Setup complete! Your awesome project is ready to go!"));
console.log(chalk.cyan("\nProject structure:"));
console.log(chalk.yellow(`
src/
├── components/
│ ├── Header.${fileExtension}
│ ├── SideMenu.${fileExtension}
│ └── PrivateRoute.${fileExtension}
├── layouts/
│ └── Layout.${fileExtension}
├── pages/
│ ├── HomePage.${fileExtension}
│ ├── AboutPage.${fileExtension}
│ └── DashboardPage.${fileExtension}
├── hooks/
├── utils/
├── App.${fileExtension}
└── index.css
`));
console.log(chalk.green.bold("\n✨ Setup complete! Your awesome project is ready to go!"));
console.log(chalk.cyan("\nRun the following commands to start your project:"));
console.log(chalk.yellow(`\n📂 cd ${projectName}`));
console.log(chalk.yellow("🚀 npm run dev"));
console.log(chalk.magenta("\nHappy coding! Remember: " + getRandomJoke()));
// fs.writeFileSync(useTypeScript ? "src/App.tsx" : "src/App.jsx", appContent);
}
createProject();