-
-
Notifications
You must be signed in to change notification settings - Fork 622
/
Copy pathinit-generator.ts
277 lines (242 loc) · 8.11 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import chalk from "chalk";
import * as logSymbols from "log-symbols";
import * as Generator from "yeoman-generator";
import * as path from "path";
import { getPackageManager } from "@webpack-cli/utils/package-manager";
import { Confirm, Input, List } from "@webpack-cli/webpack-scaffold";
import {
getDefaultOptimization,
LangType,
langQuestionHandler,
tooltip,
generatePluginName,
Loader,
StylingType,
styleQuestionHandler,
entryQuestions
} from "./utils";
import { WebpackOptions } from "./types";
/**
*
* Generator for initializing a webpack config
*
* @class InitGenerator
* @extends Generator
* @returns {Void} After execution, transforms are triggered
*
*/
export default class InitGenerator extends Generator {
public usingDefaults: boolean;
public autoGenerateConfig: boolean;
private isProd: boolean;
private dependencies: string[];
private configuration: {
config: {
configName?: string;
topScope?: string[];
webpackOptions?: WebpackOptions;
};
};
private langType: string;
public constructor(args, opts) {
super(args, opts);
this.usingDefaults = false;
this.autoGenerateConfig = opts.autoSetDefaults ? true : false;
this.dependencies = ["webpack", "webpack-cli", "babel-plugin-syntax-dynamic-import"];
this.configuration = {
config: {
configName: "config",
topScope: [],
webpackOptions: {
mode: "'production'",
entry: undefined,
output: undefined,
plugins: [],
module: {
rules: []
}
}
}
};
// add splitChunks options for transparency
// defaults coming from: https://webpack.js.org/plugins/split-chunks-plugin/#optimization-splitchunks
this.configuration.config.topScope.push(
"const path = require('path');",
"const webpack = require('webpack');",
"\n",
tooltip.splitChunks()
);
(this.configuration.config.webpackOptions.plugins as string[]).push("new webpack.ProgressPlugin()");
}
public async prompting(): Promise<void | {}> {
const done: () => {} = this.async();
const self: this = this;
let regExpForStyles: string;
let ExtractUseProps: Loader[];
process.stdout.write(
`\n${logSymbols.info}${chalk.blue(" INFO ")} ` +
`For more information and a detailed description of each question, have a look at: ` +
`${chalk.bold.green("https://github.com/webpack/webpack-cli/blob/master/INIT.md")}\n`
);
process.stdout.write(
`${logSymbols.info}${chalk.blue(" INFO ")} ` +
`Alternatively, run "webpack(-cli) --help" for usage info\n\n`
);
const { multiEntries } = await Confirm(
self,
"multiEntries",
"Will your application have multiple bundles?",
false,
this.autoGenerateConfig
);
// TODO string | object
const entryOption: void | {} = await entryQuestions(self, multiEntries, this.autoGenerateConfig);
if (typeof entryOption === "string") {
if (entryOption.length === 0) {
this.usingDefaults = true;
} else if (entryOption.length > 0) {
this.usingDefaults = entryOption && entryOption === "'./src/index.js'" ? true : false;
if (!this.usingDefaults) {
this.configuration.config.webpackOptions.entry = `${entryOption}`;
}
}
} else if (typeof entryOption === "object") {
this.configuration.config.webpackOptions.entry = entryOption;
}
let { outputDir } = Input(
self,
"outputDir",
"In which folder do you want to store your generated bundles?",
"dist",
this.autoGenerateConfig
);
this.usingDefaults = !outputDir || outputDir === "'dist'" ? true : false;
if (!this.usingDefaults) {
this.configuration.config.webpackOptions.output = {
chunkFilename: "'[name].[chunkhash].js'",
filename: "'[name].[chunkhash].js'",
path: `path.resolve(__dirname, '${outputDir}')`
};
} else {
this.configuration.config.webpackOptions.output = {
filename: "'bundle.js'",
path: `path.resolve(__dirname, '${outputDir}')`
};
}
const { langType } = await List(
self,
"langType",
"Will you use one of the below JS solutions?",
[LangType.ES6, LangType.Typescript, "No"],
LangType.ES6,
this.autoGenerateConfig
);
langQuestionHandler(this, langType);
this.langType = langType;
const { stylingType } = await List(
self,
"stylingType",
"Will you use one of the below CSS solutions?",
["No", StylingType.CSS, StylingType.SASS, StylingType.LESS, StylingType.PostCSS],
"No",
this.autoGenerateConfig
);
({ ExtractUseProps, regExpForStyles } = styleQuestionHandler(self, stylingType));
if (this.isProd) {
// Ask if the user wants to use extractPlugin
const { useExtractPlugin } = await Input(
self,
"useExtractPlugin",
"If you want to bundle your CSS files, what will you name the bundle? (press enter to skip)",
"null",
this.autoGenerateConfig
);
if (regExpForStyles) {
if (this.isProd) {
const cssBundleName: string = useExtractPlugin;
this.dependencies.push("mini-css-extract-plugin");
this.configuration.config.topScope.push(
tooltip.cssPlugin(),
"const MiniCssExtractPlugin = require('mini-css-extract-plugin');",
"\n"
);
if (cssBundleName.length !== 0) {
(this.configuration.config.webpackOptions.plugins as string[]).push(
// TODO: use [contenthash] after it is supported
`new MiniCssExtractPlugin({ filename:'${cssBundleName}.[chunkhash].css' })`
);
} else {
(this.configuration.config.webpackOptions.plugins as string[]).push(
"new MiniCssExtractPlugin({ filename:'style.css' })"
);
}
ExtractUseProps.unshift({
loader: "MiniCssExtractPlugin.loader"
});
}
this.configuration.config.webpackOptions.module.rules.push({
test: regExpForStyles,
use: ExtractUseProps
});
}
}
if (!this.isProd) {
this.dependencies.push("html-webpack-plugin");
const htmlWebpackDependency = "html-webpack-plugin";
const htmlwebpackPlugin = generatePluginName(htmlWebpackDependency);
(this.configuration.config.topScope as string[]).push(
`const ${htmlwebpackPlugin} = require('${htmlWebpackDependency}')`,
"\n",
tooltip.html()
);
(this.configuration.config.webpackOptions.plugins as string[]).push(`new ${htmlwebpackPlugin}()`);
}
if (!this.usingDefaults) {
this.dependencies.push("webpack-dev-server");
this.configuration.config.webpackOptions.devServer = {
open: true
};
} else {
this.dependencies.push("terser-webpack-plugin");
this.configuration.config.topScope.push(
tooltip.terser(),
"const TerserPlugin = require('terser-webpack-plugin');",
"\n"
);
}
this.configuration.config.webpackOptions.optimization = getDefaultOptimization(this.usingDefaults);
this.configuration.config.webpackOptions.mode = this.usingDefaults ? "'development'" : "'production'";
done();
}
public installPlugins(): void {
const packager = getPackageManager();
const opts: {
dev?: boolean;
"save-dev"?: boolean;
} = packager === "yarn" ? { dev: true } : { "save-dev": true };
this.scheduleInstallTask(packager, this.dependencies, opts);
}
public writing(): void {
this.config.set("configuration", this.configuration);
const packageJsonTemplatePath = "./templates/package.json.js";
this.fs.extendJSON(this.destinationPath("package.json"), require(packageJsonTemplatePath)(this.isProd));
const generateEntryFile = (entryPath: string, name: string): void => {
entryPath = entryPath.replace(/'/g, "");
this.fs.copyTpl(path.resolve(__dirname, "./templates/index.js"), this.destinationPath(entryPath), { name });
};
// Generate entry file/files
const entry = this.configuration.config.webpackOptions.entry;
if (typeof entry === "string") {
generateEntryFile(entry, "your main file!");
} else if (typeof entry === "object") {
Object.keys(entry).forEach((name: string): void => generateEntryFile(entry[name], `${name} main file!`));
}
// Generate README
this.fs.copyTpl(path.resolve(__dirname, "./templates/README.md"), this.destinationPath("README.md"), {});
// Genrate tsconfig
if (this.langType === LangType.Typescript) {
const tsConfigTemplatePath = "./templates/tsconfig.json.js";
this.fs.extendJSON(this.destinationPath("tsconfig.json"), require(tsConfigTemplatePath));
}
}
}