-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
ยท495 lines (428 loc) ยท 14.9 KB
/
index.js
File metadata and controls
executable file
ยท495 lines (428 loc) ยท 14.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
#!/usr/bin/env node
const { execSync } = require('child_process');
const chalk = require('chalk');
const fs = require('fs');
const path = require('path');
const commander = require('commander');
const ora = require('ora');
const packageJson = require('./package.json');
const fsExtra = require('fs-extra');
const inquirer = require('inquirer');
const { spawn } = require('child_process');
const os = require('os');
const program = new commander.Command(packageJson.name)
.version(packageJson.version)
.arguments('<project-directory>')
.usage(`${chalk.green('<project-directory>')}`)
.option('-v, --verbose', 'Run with verbose logging') // <-- Add this line
.action((projectDirectory, options) => {
// <-- Update the action to take options
createApp(projectDirectory, options);
})
.parse(process.argv);
function createApp(projectDirectory, options) {
console.clear(); // Clears the console before anything else
const root = path.resolve(projectDirectory);
const verboseFlag = options.verbose ? '--verbose' : '';
const stdioOption = verboseFlag === '--verbose' ? 'inherit' : 'ignore';
// Check if the directory already exists
if (fs.existsSync(root)) {
console.clear();
console.log(chalk.red.bold('โ Error: Directory already exists!'));
console.log(
chalk.yellow(`\nThe directory ${chalk.blue(root)} already exists.`)
);
console.log(
chalk.cyan(
'Please choose a different project name or delete the existing directory.'
)
);
return; // Exit the function if the directory exists
}
const appName = path.basename(root);
console.log(`๐ Creating a new React app in ${chalk.green(root)}...`);
fs.mkdirSync(root);
process.chdir(root);
const spinner = ora(
'โณ Installing packages. This might take a couple of minutes.'
).start();
execSync(`npx create-react-app . --template typescript ${verboseFlag}`, {
stdio: stdioOption,
});
spinner.succeed('๐ฆ Packages installed successfully.');
installDependencies(verboseFlag, stdioOption);
installDevDependencies(verboseFlag, stdioOption);
setupAntd();
setupSass();
setupTesting(stdioOption);
setupHusky(stdioOption);
setupCommitlint(stdioOption);
setupRedux();
createAtomicStructure();
updatePackageJson();
copyPreConfiguredFiles(root); // Copy pre-configured files like prettier-commit.js
deletePreCommitHook(); // Delete the .husky/pre-commit hook
runGitCommands(stdioOption); // Run git add . and git commit -m "feat: happy coding"
runPrettierCommit(stdioOption); // Run npm run prettier:commit
printCommandSummary(); // Print the command summary
console.log(chalk.green('๐ All done! Happy coding.'));
// Ask the user where they want to open the project
askUserWhereToOpen(root);
}
function askUserWhereToOpen(directory) {
inquirer
.prompt([
{
type: 'list',
name: 'openIn',
message: 'Where would you like to open the project?',
choices: ['Terminal', 'VSCode', 'Neovim', 'None'],
},
])
.then((answers) => {
switch (answers.openIn) {
case 'Terminal':
openInTerminal(directory);
break;
case 'VSCode':
openInVSCode(directory);
break;
case 'Neovim':
openInNeovim(directory);
break;
default:
console.log(
chalk.yellow(
'Project setup complete. You can manually open the project if needed.'
)
);
}
});
}
function openInTerminal(directory) {
const platform = os.platform();
if (platform === 'darwin') {
// macOS
spawn('open', ['-a', 'Terminal', directory]);
} else if (platform === 'win32') {
// Windows
spawn('cmd.exe', ['/c', 'start', 'cmd.exe', '/K', `cd /d ${directory}`], {
shell: true,
});
} else if (platform === 'linux') {
// Linux
spawn('gnome-terminal', ['--working-directory=' + directory]);
} else {
console.log(
chalk.red(
'Unsupported platform. Please manually navigate to the directory.'
)
);
}
}
function openInVSCode(directory, stdioOption) {
spawn('code', [directory], { stdio: 'inherit' });
}
function openInNeovim(directory) {
spawn('nvim', [directory], { stdio: 'inherit' });
}
function printCommandSummary() {
console.log(chalk.yellow('\n๐ Project Setup Summary:'));
console.log(chalk.cyan('\nAvailable Commands:'));
console.log(chalk.green('1. ๐ npm run dev'));
console.log(
chalk.white(
' Starts the development server with Vite.'
)
);
console.log(chalk.green('\n2. ๐ ๏ธ npm run build'));
console.log(
chalk.white(
' Builds the project for production using Vite.'
)
);
console.log(chalk.green('\n3. ๐งช npm test'));
console.log(
chalk.white(
' Placeholder for running tests. Currently, it does not run any tests but can be customized to run Jest or other test suites.'
)
);
console.log(chalk.green('\n4. ๐งช npm run test:dev'));
console.log(
chalk.white(
' Runs tests in watch mode using React Scripts. Suitable for a test-driven development approach.'
)
);
console.log(chalk.green('\n5. ๐จ npm run pretty-quick'));
console.log(
chalk.white(
' Formats all staged files using Prettier. Ensures that code is consistently formatted before committing.'
)
);
console.log(chalk.green('\n6. ๐ npm run lint:prettier'));
console.log(
chalk.white(
' Checks the format of the entire codebase using a custom script. It can be used to ensure that all files adhere to Prettierโs formatting rules.'
)
);
console.log(chalk.green('\n7. โจ npm run prettier'));
console.log(
chalk.white(
' Formats the entire codebase using Prettier based on the configuration in .prettierrc.'
)
);
console.log(chalk.green('\n8. โจ npm run prettier:commit'));
console.log(
chalk.white(
' Applies Prettier formatting to staged files before committing. Ensures that committed code is properly formatted.'
)
);
console.log(chalk.green('\n9. ๐จ npm run eject'));
console.log(
chalk.white(
' Ejects the project from Create React App. This command exposes the underlying configuration files for full control but cannot be undone.'
)
);
console.log(chalk.green('\n10. ๐ก๏ธ npm run prepare'));
console.log(
chalk.white(
' Installs Husky hooks. This script is automatically run after dependencies are installed, setting up Git hooks for the project.'
)
);
console.log(
chalk.yellow(
'\n๐ Your project is ready! Use the above commands to start working on your new React app.'
)
);
}
function runPrettierCommit(stdioOption) {
const spinner = ora('๐จ Running prettier:commit script...').start();
try {
execSync('npm run prettier:commit', { stdio: stdioOption });
spinner.succeed('โ
Prettier commit script executed successfully.');
} catch (error) {
spinner.fail('โ Failed to run prettier:commit script.');
console.error(error);
}
}
function runGitCommands(stdioOption) {
const spinner = ora('๐ง Running Git commands...').start();
try {
execSync('git add .', { stdio: stdioOption });
execSync('git commit -m "feat: happy coding"', { stdio: stdioOption });
spinner.succeed('โ
Git commands executed successfully.');
} catch (error) {
spinner.fail('โ Failed to execute Git commands.');
console.error(error);
}
}
function deletePreCommitHook() {
const spinner = ora('๐๏ธ Deleting .husky/pre-commit hook...').start();
const preCommitPath = path.resolve('.husky', 'pre-commit');
if (fs.existsSync(preCommitPath)) {
fs.unlinkSync(preCommitPath);
spinner.succeed('๐๏ธ .husky/pre-commit hook deleted.');
} else {
spinner.warn('โ ๏ธ .husky/pre-commit hook not found.');
}
}
function updatePackageJson() {
const spinner = ora(
'๐ Updating package.json with custom scripts...'
).start();
const packageJsonPath = path.resolve('package.json');
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
packageJson.scripts = {
dev: 'vite',
build: 'vite build',
preview: 'vite preview',
test: 'echo "Error: no test specified" && exit 0',
'pretty-quick': 'pretty-quick',
'lint:prettier': 'node check-format.js',
prettier: 'prettier --write . --config .prettierrc',
'prettier:commit': 'node prettier-commit.js',
prepare: 'husky install',
};
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
spinner.succeed('๐ package.json updated with custom scripts.');
}
function copyPreConfiguredFiles(destinationPath) {
const spinner = ora('๐ Copying pre-configured files...').start();
const filesToCopy = [
{
src: path.resolve(__dirname, 'pre-files/check-format.js'),
dest: path.join(destinationPath, 'check-format.js'),
},
{
src: path.resolve(__dirname, 'pre-files/commit-msg-linter.js'),
dest: path.join(destinationPath, '.husky/commit-msg-linter.js'),
},
{
src: path.resolve(__dirname, 'pre-files/lint-check.js'),
dest: path.join(destinationPath, '.husky/lint-check.js'),
},
{
src: path.resolve(__dirname, 'pre-files/prettier-commit.js'),
dest: path.join(destinationPath, 'prettier-commit.js'),
},
{
src: path.resolve(__dirname, 'pre-files/vite.config.js'),
dest: path.join(destinationPath, 'vite.config.js'),
},
{
src: path.resolve(__dirname, 'pre-files/.babelrc'),
dest: path.join(destinationPath, '.babelrc'),
},
{
src: path.resolve(__dirname, 'pre-files/.eslintrc.js'),
dest: path.join(destinationPath, '.eslintrc.js'),
},
{
src: path.resolve(__dirname, 'pre-files/.prettierrc'),
dest: path.join(destinationPath, '.prettierrc'),
},
// Add more files here if needed
];
filesToCopy.forEach((file) => {
fs.copyFileSync(file.src, file.dest);
});
// Recursively copy all files from pre-files/src/* to destinationPath/src/
const srcPath = path.resolve(__dirname, 'pre-files/src');
const destPath = path.join(destinationPath, 'src');
fsExtra.copySync(srcPath, destPath);
spinner.succeed('๐ Pre-configured files copied.');
}
function installDependencies(verboseFlag, stdioOption) {
const spinner = ora('๐ Installing additional dependencies...').start();
execSync(
`npm install @reduxjs/toolkit @testing-library/jest-dom @testing-library/react @testing-library/user-event @types/jest @types/node @types/react @types/react-dom ajv antd jest playwright react react-dom react-redux redux sass typescript web-vitals ${verboseFlag}`,
{ stdio: stdioOption }
);
spinner.succeed('โ
Additional dependencies installed.');
}
function installDevDependencies(verboseFlag, stdioOption) {
const spinner = ora('๐ Installing additional dev dependencies...').start();
execSync(
`npm install --save-dev @babel/plugin-proposal-private-property-in-object ora prettier @commitlint/cli @commitlint/config-conventional dotenv husky pretty-quick vite @vitejs/plugin-react ${verboseFlag}`,
{ stdio: stdioOption }
);
spinner.succeed('โ
Additional dev dependencies installed.');
}
function setupAntd() {
const spinner = ora('๐จ Setting up Ant Design...').start();
const indexCssPath = path.resolve('src', 'index.css');
const indexCss = fs.readFileSync(indexCssPath, 'utf8');
fs.writeFileSync(indexCssPath, `@import '~antd/dist/antd.css';\n${indexCss}`);
spinner.succeed('๐จ Ant Design set up.');
}
function setupSass() {
const spinner = ora('๐จ Setting up SASS...').start();
const appCssPath = path.resolve('src', 'App.css');
fs.renameSync(appCssPath, appCssPath.replace('.css', '.scss'));
spinner.succeed('๐จ SASS set up.');
}
function setupTesting(stdioOption) {
const spinner = ora('๐งช Setting up Playwright and Jest...').start();
try {
execSync('npx playwright install', { stdio: stdioOption });
spinner.succeed('๐งช Playwright and Jest set up.');
} catch (error) {
spinner.fail('โ Failed to set up Playwright and Jest.');
console.error(error);
}
}
function setupHusky(stdioOption) {
const spinner = ora('๐ถ Setting up Husky...').start();
execSync('npx husky-init && npm install', {
stdio: stdioOption,
});
execSync('npx husky add .husky/pre-commit "npm test"', {
stdio: stdioOption,
});
spinner.succeed('๐ถ Husky set up.');
}
function setupCommitlint(stdioOption) {
const spinner = ora('๐ Setting up Commitlint...').start();
const commitMsg = `#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
node ./.husky/commit-msg-linter.js "$1"`;
const commitLintMsgLinter = `module.exports = {
extends: ['@commitlint/config-conventional'],
};`;
const prePush = `#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
node .husky/lint-check.js`;
execSync('npm install @commitlint/{config-conventional,cli} --save-dev', {
stdio: stdioOption,
});
execSync('touch .husky/commit-msg', { stdio: stdioOption });
execSync('touch .husky/pre-push', { stdio: stdioOption });
execSync('chmod +x .husky/commit-msg', { stdio: stdioOption });
execSync('chmod +x .husky/pre-push', { stdio: stdioOption });
fs.writeFileSync(path.resolve('.husky/commit-msg'), commitMsg);
fs.writeFileSync(path.resolve('commitlint.config.js'), commitLintMsgLinter);
fs.writeFileSync(path.resolve('.husky/pre-push'), prePush);
spinner.succeed('๐ Commitlint set up.');
}
function setupRedux() {
const spinner = ora('๐ ๏ธ Setting up Redux...').start();
const reduxStructure = [
'src/store',
'src/store/slices',
'src/store/middleware',
'src/store/selectors',
];
reduxStructure.forEach((dir) => {
fs.mkdirSync(dir, { recursive: true });
});
const storeIndex = `
import { configureStore } from โ@reduxjs/toolkitโ;
const store = configureStore({
reducer: {
// Add your reducers here
},
middleware: (getDefaultMiddleware) => getDefaultMiddleware(),
});
export default store;
`;
fs.writeFileSync(path.resolve('src/store/index.ts'), storeIndex);
const appTsxPath = path.resolve('src/App.tsx');
let appTsx = fs.readFileSync(appTsxPath, 'utf8');
appTsx = `
import React from 'react';
import { Provider } from 'react-redux';
import store from './store';
const App: React.FC = () => {
return (
<Provider store={store}>
${appTsx}
</Provider>
);
};
export default App;
`;
fs.writeFileSync(appTsxPath, appTsx);
spinner.succeed('๐ ๏ธ Redux set up.');
}
function createAtomicStructure() {
const spinner = ora('๐๏ธ Creating atomic design structureโฆ').start();
const atomicStructure = [
'src/components/atoms',
'src/components/molecules',
'src/components/organisms',
'src/components/templates',
'src/components/pages',
];
atomicStructure.forEach((dir) => {
fs.mkdirSync(dir, { recursive: true });
});
spinner.succeed('๐๏ธ Atomic design structure created.');
}
if (!program.args.length) {
program.help();
}
module.exports = {
printCommandSummary,
installDependencies,
// Export other functions as needed
};