-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
85 lines (75 loc) · 2.1 KB
/
index.js
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
#!/usr/bin/env node
const fs = require("fs");
const path = require("path");
const { prompt } = require("enquirer");
const colors = require("ansi-colors");
async function init() {
// get template name from cmd arg
const { template } = await prompt({
type: "select",
name: "template",
message: "Pick a template",
// todo: fetch available templates dynamically
choices: ["react"],
});
// get dir name from cmd arg
const { directory } = await prompt({
type: "input",
name: "directory",
message: "Type your directory name",
initial: "es-react-project",
});
// copy template dir to target
const sourceDir = path.join(__dirname, "templates", template);
const targetDir = path.join(process.cwd(), directory);
copy(sourceDir, targetDir);
// change package.json project name
const pkg = require(path.resolve(targetDir, "package.json"));
pkg.name = directory
.trim()
.replace(/\s+/g, "-")
.replace(/^[._]/, "")
.replace(/[~)('!*]+/g, "-");
fs.writeFileSync(
path.resolve(targetDir, "package.json"),
JSON.stringify(pkg, null, 2)
);
// rename gitignore
fs.renameSync(
path.resolve(targetDir, "_gitignore"),
path.resolve(targetDir, ".gitignore")
);
// give instructions to user to install
const info = [
"\n",
colors.bold.green("✔ You have successfully created the project"),
"\n",
` You can get started by running:`,
colors.bold.blue(` cd ${directory}`),
colors.bold.blue(` npm install`),
` ${colors.bold.blue("npm run dev")} & ${colors.bold.blue(
"npm run serve"
)} simultaneously`,
"\n",
];
console.log(info.join("\n"));
}
function copy(src, dest) {
const stat = fs.statSync(src);
if (stat.isDirectory()) {
copyDir(src, dest);
} else {
fs.copyFileSync(src, dest);
}
}
function copyDir(srcDir, destDir) {
fs.mkdirSync(destDir, { recursive: true });
for (const file of fs.readdirSync(srcDir)) {
const srcFile = path.resolve(srcDir, file);
const destFile = path.resolve(destDir, file);
copy(srcFile, destFile);
}
}
init().catch((e) => {
console.error(e);
});