forked from webpack/webpack-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
init-generator.ts
255 lines (221 loc) · 8.1 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
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 } from "./utils/webpackConfig";
import { WebpackOptions } from "./types";
import entryQuestions from "./utils/entry";
import langQuestionHandler, { LangType } from "./utils/languageSupport";
import styleQuestionHandler, { Loader, StylingType } from "./utils/styleSupport";
import tooltip from "./utils/tooltip";
import { generatePluginName } from "./utils/plugins";
/**
*
* 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;
};
};
private langType: string;
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: [],
webpackOptions: {
mode: this.isProd ? "'production'" : "'development'",
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()
);
if (this.isProd) {
this.configuration.config.topScope.push(
tooltip.terser(),
"const TerserPlugin = require('terser-webpack-plugin');",
"\n"
);
}
(this.configuration.config.webpackOptions.plugins as string[]).push("new webpack.ProgressPlugin()");
let optimizationConfig = getDefaultOptimization(this.isProd);
this.configuration.config.webpackOptions.optimization = optimizationConfig;
if (!this.isProd) {
this.configuration.config.webpackOptions.devServer = {
open: true
};
}
}
public async prompting() {
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 this.prompt([
Confirm("multiEntries", "Will your application have multiple bundles?", false)
]);
// TODO string | object
const entryOption: void | {} = await entryQuestions(self, multiEntries);
if (typeof entryOption === "string" && entryOption.length > 0) {
this.configuration.config.webpackOptions.entry = `${entryOption}`;
} else if (typeof entryOption === "object") {
this.configuration.config.webpackOptions.entry = entryOption;
}
const { outputDir } = await this.prompt([
Input("outputDir", "In which folder do you want to store your generated bundles?", "dist")
]);
// 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 && outputDir.length) {
this.configuration.config.webpackOptions.output.path = `path.resolve(__dirname, '${outputDir}')`;
}
const { langType } = await this.prompt([
List("langType", "Will you use one of the below JS solutions?", [LangType.ES6, LangType.Typescript, "No"])
]);
langQuestionHandler(this, langType);
this.langType = langType;
const { stylingType } = await this.prompt([
List("stylingType", "Will you use one of the below CSS solutions?", [
"No",
StylingType.CSS,
StylingType.SASS,
StylingType.LESS,
StylingType.PostCSS
])
]);
({ ExtractUseProps, regExpForStyles } = styleQuestionHandler(self, stylingType));
if (this.isProd) {
// Ask if the user wants to use extractPlugin
const { useExtractPlugin } = await this.prompt([
Input(
"useExtractPlugin",
"If you want to bundle your CSS files, what will you name the bundle? (press enter to skip)"
)
]);
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}()`);
}
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));
}
}
}