UNPKG

2.84 kBPlain TextView Raw
1import { rootPath } from "../utils";
2import { readFileSync, writeFileSync, existsSync } from "fs";
3import { join } from "path";
4import * as globby from "globby";
5import * as mkdirp from "mkdirp";
6import * as rimraf from "rimraf";
7import * as sh from "shelljs";
8import chalk from "chalk";
9
10const writeFile = (fullpath: string, content) => {
11 const sections = fullpath.split("/");
12 sections.pop();
13 const path = sections.join("/");
14 mkdirp.sync(path);
15 writeFileSync(fullpath, content);
16};
17
18const copyTemplate = async (
19 name: string,
20 dirname: string,
21 { mode, d, force }
22) => {
23 const pkg = {
24 name,
25 version: "0.0.1",
26 private: true,
27 scripts: {
28 dev: "tp dev",
29 build: "tp build",
30 test: "tp test"
31 }
32 };
33 const paths: string[] = await globby(
34 join(__dirname, `../../templates/${mode}/**/*`)
35 );
36 const files = paths.map((path: string) => {
37 const splittedName = path.split(
38 join(__dirname, `../../templates/${mode}/`)
39 );
40 return {
41 name: splittedName[splittedName.length - 1],
42 content: readFileSync(path)
43 };
44 });
45
46 if (d) {
47 console.log(paths);
48 console.log(files);
49 }
50
51 if (!paths || !paths.length) {
52 console.log(chalk.red("Template not exists."));
53 process.exit(1);
54 return;
55 }
56
57 if (force) {
58 rimraf.sync(dirname);
59 }
60
61 if (existsSync(dirname)) {
62 console.log(chalk.red("Dirname already exists."));
63 console.log(
64 `use ${chalk.blue("--force")} to delete it and create a new one.`
65 );
66 process.exit(1);
67 return;
68 }
69
70 mkdirp.sync(dirname);
71
72 files.forEach(file => {
73 writeFile(join(rootPath, name, file.name), file.content);
74 });
75 writeFile(join(rootPath, name, "package.json"), JSON.stringify(pkg, null, 2));
76};
77
78const installPackages = (dirname: string, mode: string) => {
79 const hasYarn = sh.which("yarn");
80 const install = hasYarn ? "yarn add" : "npm install --save";
81 const devInstall = hasYarn ? "yarn add -D" : "npm install --save-dev";
82
83 const dependencies = ["@babel/runtime"];
84 const devDependencies = [
85 "typepack",
86 "@types/node",
87 "@types/jest",
88 "@babel/core",
89 "@babel/preset-env",
90 "@babel/plugin-transform-runtime"
91 ];
92
93 if (mode === "react") {
94 const reactDeps = ["react", "react-dom"];
95 const reactDevDeps = ["@types/react", "@types/react-dom"];
96 dependencies.push(...reactDeps);
97 devDependencies.push(...reactDevDeps);
98 }
99
100 sh.cd(dirname);
101 if (
102 sh.exec(`${install} ${dependencies.join(" ")}`).code !== 0 ||
103 sh.exec(`${devInstall} ${devDependencies.join(" ")}`).code !== 0
104 ) {
105 sh.echo("Error: failed to install needed modules");
106 sh.exit(1);
107 }
108};
109
110module.exports = async (name: string, opts) => {
111 const dirname = join(rootPath, name);
112 await copyTemplate(name, dirname, opts);
113 installPackages(dirname, opts.mode);
114};