-
-
Notifications
You must be signed in to change notification settings - Fork 591
/
init-generator.ts
84 lines (68 loc) · 2.66 KB
/
init-generator.ts
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
import { readFileSync, writeFileSync } from "fs";
import { CustomGenerator, InitGeneratorOptions, CustomGeneratorOptions } from "./types";
import { getInstaller, getTemplate } from "./utils/helpers";
import * as Question from "./utils/scaffold-utils";
import handlers from "./handlers";
export default class InitGenerator<
T extends InitGeneratorOptions = InitGeneratorOptions,
Z extends CustomGeneratorOptions<T> = CustomGeneratorOptions<T>,
> extends CustomGenerator<InitGeneratorOptions> {
public configurationPath: string | undefined;
public constructor(args: string | string[], opts: Z) {
super(args, opts);
this.dependencies = ["webpack", "webpack-cli"];
this.supportedTemplates = Object.keys(handlers);
}
public async prompting(): Promise<void> {
this.template = await getTemplate.call(this);
await handlers[this.template as keyof typeof handlers].questions(this, Question);
// Handle installation of prettier
try {
// eslint-disable-next-line node/no-extraneous-require
require.resolve("prettier");
} catch (err) {
const { installPrettier } = await Question.Confirm(
this,
"installPrettier",
"Do you like to install prettier to format generated configuration?",
true,
false,
);
if (installPrettier) {
this.dependencies.push("prettier");
}
}
}
public async installPlugins(): Promise<void> {
this.packageManager = await getInstaller.call(this);
const opts: {
dev?: boolean;
"save-dev"?: boolean;
} = this.packageManager === "yarn" ? { dev: true } : { "save-dev": true };
this.scheduleInstallTask(this.packageManager, this.dependencies, opts, {
cwd: this.generationPath,
});
}
public writing(): void {
this.cli.logger.log(`${this.cli.colors.blue("ℹ INFO ")} Initialising project...`);
this.configurationPath = this.destinationPath("webpack.config.js");
handlers[this.template as keyof typeof handlers].generate(this);
}
public end(): void {
// Prettify configuration file if possible
try {
// eslint-disable-next-line node/no-extraneous-require, @typescript-eslint/no-var-requires
const prettier = require("prettier");
const source = readFileSync(this.configurationPath as string, { encoding: "utf8" });
const formattedSource = prettier.format(source, { parser: "babel" });
writeFileSync(this.configurationPath as string, formattedSource);
} catch (err) {
this.cli.logger.log(
`${this.cli.colors.yellow(
`⚠ Generated configuration may not be properly formatted as prettier is not installed.`,
)}`,
);
return;
}
}
}