Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

38 optimize create process #40

Merged
merged 4 commits into from
Apr 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": [
"plugin:@sj-distributor/react/recommended"
]
}
17 changes: 16 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "create-react-boilerplates",
"version": "2.1.0",
"version": "2.1.1",
"type": "module",
"bin": {
"create-react-boilerplates": "index.js",
Expand Down Expand Up @@ -51,5 +51,20 @@
"minimist": "^1.2.8",
"prompts": "^2.4.2",
"unbuild": "^1.1.2"
},
"dependencies": {
"@sj-distributor/eslint-plugin-react": "^0.7.1",
"@typescript-eslint/eslint-plugin": "^5.59.1",
"@typescript-eslint/parser": "^5.59.1",
"eslint": "^8.39.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-react": "^7.32.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-simple-import-sort": "^10.0.0",
"eslint-plugin-unicorn": "^46.0.0",
"prettier": "^2.8.8",
"typescript": "^5.0.4"
}
}
16 changes: 16 additions & 0 deletions src/boilerplates.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { green, yellow } from "kolorist";

import { Boilerplate } from "./types";

export const boilerplates: Boilerplate[] = [
{
name: "react-recoil",
display: "TypeScript + Recoil",
color: yellow,
},
{
name: "react-ts",
display: "TypeScript",
color: green,
},
];
166 changes: 73 additions & 93 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,120 +1,99 @@
import spawn from 'cross-spawn';
import { red, reset } from 'kolorist';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import prompts from 'prompts';

import { frameworks, templates } from './templates';
import { Framework } from './types';
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

import spawn from "cross-spawn";
import { red, reset } from "kolorist";
import prompts from "prompts";

import { boilerplates } from "./boilerplates";
import {
argv,
cwd,
emptyDir,
formatTargetDir,
formatDir,
getProjectName,
isEmpty,
isValidPackageName,
pkgFromUserAgent,
setupReactSwc,
toValidPackageName,
write,
} from './utils';
} from "./utils";

const DEFAULT_TARGET_DIR = 'react-project';
const DEFAULT_TARGET_DIR = "react-project";

async function init() {
const argTargetDir = formatTargetDir(argv._[0]);
const argvTargetDir = formatDir(argv._[0]);

const argTemplate = argv.template || argv.t;
const argvTemplate = argv.template || argv.t;

let targetDir = argTargetDir || DEFAULT_TARGET_DIR;
let targetDir = argvTargetDir || DEFAULT_TARGET_DIR;

let result: prompts.Answers<
'projectName' | 'overwrite' | 'packageName' | 'framework' | 'boilerplate'
"projectName" | "overwrite" | "packageName" | "boilerplate"
>;

try {
result = await prompts(
[
{
type: argTargetDir ? null : 'text',
name: 'projectName',
message: reset('Project name:'),
type: argvTargetDir ? null : "text",
name: "projectName",
message: reset("Project name:"),
initial: DEFAULT_TARGET_DIR,
onState: state => {
targetDir = formatTargetDir(state.value) || DEFAULT_TARGET_DIR;
onState: (state) => {
targetDir = formatDir(state.value) || DEFAULT_TARGET_DIR;
},
},
{
type: () =>
!fs.existsSync(targetDir) || isEmpty(targetDir) ? null : 'confirm',
name: 'overwrite',
!fs.existsSync(targetDir) || isEmpty(targetDir) ? null : "confirm",
name: "overwrite",
message: () =>
(targetDir === '.'
? 'Current directory'
(targetDir === "."
? "Current directory"
: `Target directory "${targetDir}"`) +
` is not empty. Remove existing files and continue?`,
},
{
type: (_, { overwrite }: { overwrite?: boolean }) => {
if (overwrite === false) {
throw new Error(red('✖') + ' Operation cancelled');
throw new Error(red("✖") + " Operation cancelled");
}

return null;
},
name: 'overwriteChecker',
name: "overwriteChecker",
},
{
type: () => (isValidPackageName(getProjectName(targetDir)) ? null : 'text'),
name: 'packageName',
message: reset('Package name:'),
type: () =>
isValidPackageName(getProjectName(targetDir)) ? null : "text",
name: "packageName",
message: reset("Package name:"),
initial: () => toValidPackageName(getProjectName(targetDir)),
validate: dir =>
isValidPackageName(dir) || 'Invalid package.json name',
validate: (dir) =>
isValidPackageName(dir) || "Invalid package.json name",
},
{
type:
argTemplate && templates.includes(argTemplate) ? null : 'select',
name: 'framework',
message:
typeof argTemplate === 'string' && !templates.includes(argTemplate)
? reset(
`"${argTemplate}" isn't a valid template. Please choose from below: `,
)
: reset('Select a framework:'),
initial: 0,
choices: frameworks.map(item => {
const frameworkColor = item.color;
type: "select",
name: "boilerplate",
message: reset("Select a boilerplate:"),
choices: boilerplates.map((item) => {
const variantColor = item.color;

return {
title: frameworkColor(item.display || item.name),
value: item,
title: variantColor(item.display || item.name),
value: item.name,
};
}),
},
{
type: (framework: Framework) =>
framework && framework.boilerplate ? 'select' : null,
name: 'boilerplate',
message: reset('Select a boilerplate:'),
choices: (framework: Framework) =>
framework.boilerplate.map(item => {
const variantColor = item.color;

return {
title: variantColor(item.display || item.name),
value: item.name,
};
}),
},
],
{
onCancel: () => {
throw new Error(red('✖') + ' Operation cancelled');
throw new Error(red("✖") + " Operation cancelled");
},
},
}
);
} catch (cancelled: any) {
console.log(cancelled.message);
Expand All @@ -123,7 +102,7 @@ async function init() {
}

// user choice associated with prompts
const { framework, overwrite, packageName, boilerplate } = result;
const { overwrite, packageName, boilerplate } = result;

const root = path.join(cwd, targetDir);

Expand All @@ -134,50 +113,51 @@ async function init() {
}

// determine template
let template: string = boilerplate || framework?.name || argTemplate;
let template: string = boilerplate || argvTemplate;

let isReactSwc = false;

if (template.includes('-swc')) {
if (template.includes("-swc")) {
isReactSwc = true;
template = template.replace('-swc', '');
template = template.replace("-swc", "");
}

const pkgInfo = pkgFromUserAgent(process.env.npm_config_user_agent);

const pkgManager = pkgInfo ? pkgInfo.name : 'npm';
const pkgManager = pkgInfo ? pkgInfo.name : "npm";

const isYarn1 = pkgManager === 'yarn' && pkgInfo?.version.startsWith('1.');
const isYarn1 = pkgManager === "yarn" && pkgInfo?.version.startsWith("1.");

const { customCommand } =
frameworks.flatMap(f => f.boilerplate).find(v => v.name === template) ?? {};
const { customCommand } = boilerplates.find((v) => v.name === template) ?? {};

if (customCommand) {
const fullCustomCommand = customCommand
.replace(/^npm create/, `${pkgManager} create`)
// Only Yarn 1.x doesn't support `@version` in the `create` command
.replace('@latest', () => (isYarn1 ? '' : '@latest'))
.replace("@latest", () => (isYarn1 ? "" : "@latest"))
.replace(/^npm exec/, () => {
// Prefer `pnpm dlx` or `yarn dlx`
if (pkgManager === 'pnpm') {
return 'pnpm dlx';
if (pkgManager === "pnpm") {
return "pnpm dlx";
}
if (pkgManager === 'yarn' && !isYarn1) {
return 'yarn dlx';
if (pkgManager === "yarn" && !isYarn1) {
return "yarn dlx";
}

// Use `npm exec` in all other cases,
// including Yarn 1.x and other custom npm clients.
return 'npm exec';
return "npm exec";
});

const [command, ...args] = fullCustomCommand.split(' ');
const [command, ...args] = fullCustomCommand.split(" ");

// we replace TARGET_DIR here because targetDir may include a space
const replacedArgs = args.map(arg => arg.replace('TARGET_DIR', targetDir));
const replacedArgs = args.map((arg) =>
arg.replace("TARGET_DIR", targetDir)
);

const { status } = spawn.sync(command, replacedArgs, {
stdio: 'inherit',
stdio: "inherit",
});

process.exit(status ?? 0);
Expand All @@ -187,26 +167,26 @@ async function init() {

const templateDir = path.resolve(
fileURLToPath(import.meta.url),
'../../templates/',
`template-${template}`,
"../../templates/",
`template-${template}`
);

const files = fs.readdirSync(templateDir);

for (const file of files.filter(f => f !== 'package.json')) {
for (const file of files.filter((f) => f !== "package.json")) {
write(root, templateDir, file);
}

const pkg = JSON.parse(
fs.readFileSync(path.join(templateDir, `package.json`), 'utf-8'),
fs.readFileSync(path.join(templateDir, `package.json`), "utf-8")
);

pkg.name = packageName || getProjectName(targetDir);

write(root, templateDir, 'package.json', JSON.stringify(pkg, null, 2) + '\n');
write(root, templateDir, "package.json", JSON.stringify(pkg, null, 2) + "\n");

if (isReactSwc) {
setupReactSwc(root, template.endsWith('-ts'));
setupReactSwc(root, template.endsWith("-ts"));
}

const cdProjectName = path.relative(cwd, root);
Expand All @@ -216,15 +196,15 @@ async function init() {
if (root !== cwd) {
console.log(
` cd ${
cdProjectName.includes(' ') ? `"${cdProjectName}"` : cdProjectName
}`,
cdProjectName.includes(" ") ? `"${cdProjectName}"` : cdProjectName
}`
);
}

switch (pkgManager) {
case 'yarn':
console.log(' yarn');
console.log(' yarn dev');
case "yarn":
console.log(" yarn");
console.log(" yarn dev");
break;
default:
console.log(` ${pkgManager} install`);
Expand All @@ -233,6 +213,6 @@ async function init() {
}
}

init().catch(e => {
init().catch((e) => {
console.error(e);
});
26 changes: 0 additions & 26 deletions src/templates.ts

This file was deleted.

Loading