-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (72 loc) · 2.28 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
#!/usr/bin/env node
import inquirer from "inquirer";
import * as fs from "fs";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
const DIRECTORY = process.cwd();
const ENCODING = "utf8";
const PROJECT_REGEX = /^([\_\-\A-Za-z0-9])+$/;
const QUESTION1 = "template";
const QUESTION2 = "projectName";
const templates = ["parcel-app", "webpack-app"];
const __dirname = dirname(fileURLToPath(import.meta.url));
const srcPath = join(__dirname, "src");
const choices = fs
.readdirSync(srcPath)
.filter((item) => templates.includes(item));
const QUESTIONS = [
{
name: QUESTION1,
type: "list",
message: "Project template:",
choices,
},
{
name: QUESTION2,
type: "input",
message: "Project name:",
validate: function (input) {
if (PROJECT_REGEX.test(input)) return true;
else {
console.error("\nProject name error.");
return false;
}
},
},
];
const renderFiles = (templatePath, projectNamePath) => {
const filesToCreate = fs.readdirSync(templatePath);
for (let i = 0; i < filesToCreate.length; i++) {
let currentFile = filesToCreate[i];
const currentFilePath = join(templatePath, currentFile);
const currentFileStat = fs.statSync(currentFilePath);
currentFile = currentFile === "gitignore.txt" ? ".gitignore" : currentFile;
currentFile =
currentFile === "packagejson.txt" ? "package.json" : currentFile;
const writePath = join(DIRECTORY, projectNamePath, currentFile);
if (currentFileStat.isFile()) {
const fileContent = fs.readFileSync(currentFilePath, ENCODING);
fs.writeFileSync(
writePath,
currentFile === "package.json"
? fileContent.replace("cample-start", projectNamePath)
: fileContent,
ENCODING
);
}
if (currentFileStat.isDirectory()) {
fs.mkdirSync(writePath);
renderFiles(
join(templatePath, currentFile),
join(projectNamePath, currentFile)
);
}
}
};
inquirer.prompt(QUESTIONS).then((answers) => {
const projectName = answers[QUESTION2];
const projectNamePath = join(DIRECTORY, projectName);
fs.mkdirSync(projectNamePath);
renderFiles(join(__dirname, "src", answers[QUESTION1]), projectName);
console.log(`Project ${projectName} installed successfully!`);
});