/
init-generator.ts
312 lines (286 loc) · 8.29 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import chalk from "chalk";
import * as logSymbols from "log-symbols";
import * as Generator from "yeoman-generator";
import * as Inquirer from "inquirer";
import * as path from "path";
import { getPackageManager } from "@webpack-cli/utils/package-manager";
import { Confirm, Input, List } from "@webpack-cli/webpack-scaffold";
import { WebpackOptions } from "./types";
import entryQuestions from "./utils/entry";
import langQuestionHandler from "./utils/language";
import styleQuestionHandler, { ILoader, StylingType } from "./utils/style";
import tooltip from "./utils/tooltip";
/**
*
* 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;
private isProd: boolean;
private dependencies: string[];
private configuration: {
config: {
configName?: string;
topScope?: string[];
webpackOptions?: WebpackOptions;
};
};
public constructor(args, opts) {
super(args, opts);
this.usingDefaults = false,
this.isProd = this.usingDefaults ? true : false;
this.dependencies = [
"webpack",
"webpack-cli",
"babel-plugin-syntax-dynamic-import",
];
if (this.isProd) {
this.dependencies.push("terser-webpack-plugin");
} else {
this.dependencies.push("webpack-dev-server");
}
this.configuration = {
config: {
configName: this.isProd ? "prod" : "config",
topScope: [],
// TODO migrate tslint
// tslint:disable: object-literal-sort-keys
webpackOptions: {
mode: this.isProd ? "'production'" : "'development'",
entry: undefined,
output: undefined,
plugins: [],
module: {
rules: [],
},
},
// tslint:enable: object-literal-sort-keys
},
};
// 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(),
);
if (this.isProd) {
this.configuration.config.topScope.push(
tooltip.terser(),
"const TerserPlugin = require('terser-webpack-plugin');",
"\n",
);
}
this.configuration.config.webpackOptions.plugins.push(
"new webpack.ProgressPlugin()",
);
let optimizationObj;
if (!this.isProd) {
optimizationObj = {
splitChunks: {
chunks: "'all'",
},
};
} else {
optimizationObj = {
minimizer: [
"new TerserPlugin()",
],
splitChunks: {
cacheGroups: {
vendors: {
priority: -10,
test: "/[\\\\/]node_modules[\\\\/]/",
},
},
chunks: "'async'",
minChunks: 1,
minSize: 30000,
// for production name is recommended to be off
name: !this.isProd,
},
};
}
this.configuration.config.webpackOptions.optimization = optimizationObj;
if (!this.isProd) {
this.configuration.config.webpackOptions.devServer = {
open: true,
};
}
}
// eslint-disable-next-line
public prompting(): any {
const done: () => {} = this.async();
const self: this = this;
let regExpForStyles: string;
let ExtractUseProps: ILoader[];
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`,
);
return this.prompt([
Confirm("multiEntries", "Will your application have multiple bundles?", false),
])
.then((multiEntriesAnswer: {
multiEntries: boolean,
}) =>
entryQuestions(self, multiEntriesAnswer.multiEntries),
)
.then((entryOption: object | string) => {
if (typeof entryOption === "string" && entryOption.length > 0) {
this.configuration.config.webpackOptions.entry = `${entryOption}`;
} else if (typeof entryOption === "object") {
this.configuration.config.webpackOptions.entry = entryOption;
}
})
.then(() =>
this.prompt([
Input(
"outputDir",
"In which folder do you want to store your generated bundles?",
"dist",
),
]),
)
.then((outputDirAnswer: {
outputDir: string;
}) => {
// As entry is not required anymore and we dont set it to be an empty string or """""
// it can be undefined so falsy check is enough (vs entry.length);
if (
!this.configuration.config.webpackOptions.entry &&
!this.usingDefaults
) {
this.configuration.config.webpackOptions.output = {
chunkFilename: "'[name].[chunkhash].js'",
filename: "'[name].[chunkhash].js'",
};
} else if (!this.usingDefaults) {
this.configuration.config.webpackOptions.output = {
filename: "'[name].[chunkhash].js'",
};
}
if (!this.usingDefaults && outputDirAnswer.outputDir.length) {
this.configuration.config.webpackOptions.output.path =
`path.resolve(__dirname, '${outputDirAnswer.outputDir}')`;
}
})
.then(() =>
this.prompt([
List("langType", "Will you use one of the below JS solutions?", [
"ES6",
"Typescript",
"No",
]),
]),
)
.then((langTypeAnswer: {
langType: boolean;
}) => {
langQuestionHandler(this, langTypeAnswer.langType);
})
.then(() =>
this.prompt([
List("stylingType", "Will you use one of the below CSS solutions?", [
"No",
StylingType.CSS,
StylingType.SASS,
StylingType.LESS,
StylingType.PostCSS,
]),
]))
.then((stylingTypeAnswer: {
stylingType: string;
}) =>
({ ExtractUseProps, regExpForStyles } = styleQuestionHandler(self, stylingTypeAnswer.stylingType)),
)
.then((): Promise<Inquirer.Answers> => {
if (this.isProd) {
// Ask if the user wants to use extractPlugin
return this.prompt([
Input(
"useExtractPlugin",
"If you want to bundle your CSS files, what will you name the bundle? (press enter to skip)",
),
]);
}
})
.then((useExtractPluginAnswer: {
useExtractPlugin: string;
}) => {
if (regExpForStyles) {
if (this.isProd) {
const cssBundleName: string = useExtractPluginAnswer.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.push(
// TODO: use [contenthash] after it is supported
`new MiniCssExtractPlugin({ filename:'${cssBundleName}.[chunkhash].css' })`,
);
} else {
this.configuration.config.webpackOptions.plugins.push(
"new MiniCssExtractPlugin({ filename:'style.css' })",
);
}
ExtractUseProps.unshift({
loader: "MiniCssExtractPlugin.loader",
});
}
this.configuration.config.webpackOptions.module.rules.push(
{
test: regExpForStyles,
use: ExtractUseProps,
},
);
}
done();
});
}
public installPlugins() {
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 entry = this.configuration.config.webpackOptions.entry;
const generateEntryFile = (entryPath: string, name: string) => {
entryPath = entryPath.replace(/'/g, "");
this.fs.copyTpl(
path.resolve(__dirname, "./templates/index.js"),
this.destinationPath(entryPath),
{ name },
);
};
if ( typeof entry === "string" ) {
generateEntryFile(entry, "your main file!");
} else if (typeof entry === "object") {
Object.keys(entry).forEach((name) =>
generateEntryFile(entry[name], `${name} main file!`),
);
}
}
}