-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBuildProcess.ts
289 lines (250 loc) · 9.93 KB
/
BuildProcess.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
import * as fs from "fs";
import * as path from "path";
import chalk from "chalk";
import { Configuration as InternalConfiguration, DefinePlugin, webpack } from "webpack";
import { Configuration as DevServerConfiguration } from "webpack-dev-server";
import WebpackDevServer from "webpack-dev-server";
import CopyWebpackPlugin from "copy-webpack-plugin";
import HtmlWebpackPlugin from "html-webpack-plugin";
import TerserPlugin from "terser-webpack-plugin";
import Dotenv from "dotenv-webpack";
// local imports
import Configuration from "../Configuration";
// output directory
const OUTPUT_DIRECTORY_NAME = "dist";
// find the nearest (parent) `node_modules` cache of a directory.
function findNearestNodeModules(startDir: string): string {
let dir = startDir;
while (dir !== path.parse(dir).root) {
const possibleNodeModules = path.join(dir, "node_modules");
if (fs.existsSync(possibleNodeModules) && fs.statSync(possibleNodeModules).isDirectory()) {
return possibleNodeModules;
}
dir = path.dirname(dir);
}
return "";
}
export class BuildProcess {
constructor(private directory: string, private release: boolean) {
//
}
build(): void {
this.ensureProjectIsValid();
// vars
const { directory } = this;
// read Webpack configuration
const configuration = Configuration.directory(directory);
// create internal configuration
const internal_config = this.createInternalConfiguration(configuration);
// output directory
const output_directory = path.join(directory, OUTPUT_DIRECTORY_NAME);
// clean
if (fs.existsSync(output_directory) && fs.statSync(output_directory).isDirectory()) {
fs.rmSync(output_directory, {
recursive: true,
force: true,
});
}
// invoke internal Webpack instance
webpack(internal_config, (err, stats) => {
let errors_found = false;
if (err) {
errors_found = true;
console.error(err.stack || err);
if ((err as any).details) {
console.error((err as any).details);
}
return;
}
if (stats) {
if (stats.hasErrors()) {
console.error(stats.toString({ all: false, errors: true, colors: true }));
errors_found = true;
}
if (stats.hasWarnings()) {
console.warn(stats.toString({ all: false, warnings: true, colors: true }));
}
}
if (!errors_found) {
console.log(chalk.green("Successfuly built project."));
}
});
}
run(): void {
this.ensureProjectIsValid();
// vars
const { directory } = this;
// read Webpack configuration
const configuration = Configuration.directory(directory);
// create internal configuration
const internal_config = this.createInternalConfiguration(configuration);
// internal Webpack instance
const compiler = webpack(internal_config);
// server
const server = new WebpackDevServer(internal_config.devServer, compiler);
// run server
const run_server = async () => {
await server.start();
};
run_server();
}
private ensureProjectIsValid(): void {
// Ensure NPM project validity
const manifest_path = path.resolve(this.directory, "package.json");
if (!(fs.existsSync(manifest_path) && fs.statSync(manifest_path).isFile())) {
console.error(chalk.red("Error:") + " " + "Directory must be a NPM project.");
process.exit(1);
}
}
private createInternalConfiguration(
configuration: Configuration
): InternalConfiguration & { devServer: DevServerConfiguration } {
// vars
const { directory, release } = this;
// detect entry point
const entry = this.detectEntryPoint(configuration);
// entry document
const entry_document = configuration.document || "./src/index.html";
// output directory
const output_directory = path.join(directory, OUTPUT_DIRECTORY_NAME);
// nearest `node_modules` cache
const nearest_node_modules = findNearestNodeModules(__dirname);
return {
entry,
context: directory,
...(release ? {} : {
devtool: "inline-source-map",
}),
mode: release ? "production" : "development",
output: {
filename: "js/[name].bundle.js",
path: output_directory,
publicPath: "",
},
resolve: {
// Add `.ts` and `.tsx` as a resolvable extension.
extensions: [".ts", ".tsx", ".js"],
// Add support for TypeScripts fully qualified ESM imports.
extensionAlias: {
".js": [".js", ".ts"],
".cjs": [".cjs", ".cts"],
".mjs": [".mjs", ".mts"]
}
},
devServer: {
static: {
directory: output_directory,
},
hot: true,
port: 9000,
},
module: {
rules: [
// all files with a `.ts`, `.cts`, `.mts` or `.tsx` extension will be handled by `ts-loader`
{
test: /\.([cm]?ts|tsx)$/,
loader: path.resolve(nearest_node_modules, "ts-loader"),
options: {
allowTsInNodeModules: true,
transpileOnly: true,
},
},
// media files
{
test: /\.(png|jpe?g|gif|svg|webp|mp4|mp3|woff2?|eot|ttf|otf)$/i,
type: "asset",
parser: {
dataUrlCondition: {
maxSize: 16 * 1024, // 16kb threshold
},
},
},
// .css files
{
test: /\.css$/i,
use: [
path.resolve(nearest_node_modules, "style-loader"),
path.resolve(nearest_node_modules, "css-loader"),
],
},
// .scss, .sass files
{
test: /\.s[ac]ss$/i,
use: [
path.resolve(nearest_node_modules, "style-loader"),
path.resolve(nearest_node_modules, "css-loader"),
path.resolve(nearest_node_modules, "sass-loader"),
],
},
// .json files
{
test: /\.(geo)?json$/i,
type: "json",
},
],
},
optimization: {
minimizer: [
new TerserPlugin({
extractComments: false,
terserOptions: {
compress: {
drop_console: true,
},
}
}),
],
splitChunks: {
chunks: "all",
},
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(directory, entry_document),
inject: true,
minify: false
}),
new CopyWebpackPlugin({
patterns: [
{
from: path.resolve(directory, "static"),
to: output_directory,
noErrorOnMissing: true,
},
],
}),
new Dotenv({
prefix: "import.meta.env.",
silent: true,
}),
new DefinePlugin({
"process.env.NODE_ENV": JSON.stringify(release ? "production" : "development"),
"process.platform": JSON.stringify(process.platform),
"process.env.IS_PREACT": JSON.stringify("true"),
"process.env.NODE_DEBUG": JSON.stringify((!release).toString()),
}),
],
};
}
private detectEntryPoint(configuration: Configuration): string {
// vars
const { directory } = this;
// detect entry point
let entry = configuration.entry;
if (!entry) {
entry = "./src/index.tsx";
if (!(
fs.existsSync(path.resolve(directory, entry)) &&
fs.statSync(path.resolve(directory, entry)).isFile())) {
entry = "./src/index.ts";
if (!(
fs.existsSync(path.resolve(directory, entry)) &&
fs.statSync(path.resolve(directory, entry)).isFile())) {
console.error(chalk.red("Error:") + " " + `Could not find TypeScript entry point: tried "src/index.tsx" and "src/index.ts"`);
process.exit(1);
}
}
}
return entry;
}
}