@simplysm/sd-cli 7.0.26 → 7.0.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,426 @@
1
+ import { INpmConfig, ISdCliPackageBuildResult, ISdCliServerPackageConfig } from "../commons";
2
+ import { EventEmitter } from "events";
3
+ import { FsUtil, Logger, PathUtil } from "@simplysm/sd-core-node";
4
+ import webpack from "webpack";
5
+ import path from "path";
6
+ import ts from "typescript";
7
+ import { SdCliBuildResultUtil } from "../utils/SdCliBuildResultUtil";
8
+ import { NamedChunksPlugin } from "@angular-devkit/build-angular/src/webpack/plugins/named-chunks-plugin";
9
+ import {
10
+ AnyComponentStyleBudgetChecker,
11
+ CommonJsUsageWarnPlugin,
12
+ DedupeModuleResolvePlugin,
13
+ SuppressExtractedTextChunksWebpackPlugin
14
+ } from "@angular-devkit/build-angular/src/webpack/plugins";
15
+ import CopyWebpackPlugin from "copy-webpack-plugin";
16
+ import MiniCssExtractPlugin from "mini-css-extract-plugin";
17
+ import { AngularWebpackPlugin } from "@ngtools/webpack";
18
+ import { IndexHtmlWebpackPlugin } from "@angular-devkit/build-angular/src/webpack/plugins/index-html-webpack-plugin";
19
+ import { createHash } from "crypto";
20
+ import { SassWorkerImplementation } from "@angular-devkit/build-angular/src/sass/sass-service";
21
+ import { HmrLoader } from "@angular-devkit/build-angular/src/webpack/plugins/hmr/hmr-loader";
22
+ import wdm from "webpack-dev-middleware";
23
+ import whm from "webpack-hot-middleware";
24
+ import { NextHandleFunction } from "connect";
25
+
26
+ export class SdCliClientBuilder extends EventEmitter {
27
+ private readonly _logger = Logger.get(["simplysm", "sd-cli", this.constructor.name]);
28
+
29
+ private readonly _tsconfigFilePath: string;
30
+ private readonly _parsedTsconfig: ts.ParsedCommandLine;
31
+ private readonly _npmConfigMap = new Map<string, INpmConfig>();
32
+
33
+ public constructor(private readonly _rootPath: string,
34
+ private readonly _config: ISdCliServerPackageConfig,
35
+ private readonly _workspaceRootPath: string) {
36
+ super();
37
+
38
+ // tsconfig
39
+ this._tsconfigFilePath = path.resolve(this._rootPath, "tsconfig-build.json");
40
+ const tsconfig = FsUtil.readJson(this._tsconfigFilePath);
41
+ this._parsedTsconfig = ts.parseJsonConfigFileContent(tsconfig, ts.sys, this._rootPath);
42
+ }
43
+
44
+ public override on(event: "change", listener: () => void): this;
45
+ public override on(event: "complete", listener: (results: ISdCliPackageBuildResult[]) => void): this;
46
+ public override on(event: string | symbol, listener: (...args: any[]) => void): this {
47
+ return super.on(event, listener);
48
+ }
49
+
50
+ public async watchAsync(): Promise<NextHandleFunction[]> {
51
+ // DIST 비우기
52
+ await FsUtil.removeAsync(this._parsedTsconfig.options.outDir!);
53
+
54
+ // 빌드 준비
55
+ const webpackConfig = this._getWebpackCommonConfig(true);
56
+ const compiler = webpack(webpackConfig);
57
+ return await new Promise<NextHandleFunction[]>((resolve, reject) => {
58
+ compiler.hooks.watchRun.tapAsync(this.constructor.name, (args, callback) => {
59
+ this.emit("change");
60
+ callback();
61
+
62
+ this._logger.debug("Webpack 빌드 수행...");
63
+ });
64
+
65
+ compiler.hooks.failed.tap(this.constructor.name, (err) => {
66
+ reject(err);
67
+ return;
68
+ });
69
+
70
+ compiler.hooks.done.tap(this.constructor.name, (stats) => {
71
+ // 결과 반환
72
+ const results = SdCliBuildResultUtil.convertFromWebpackStats(stats);
73
+ this.emit("complete", results);
74
+
75
+ // 마무리
76
+ this._logger.debug("Webpack 빌드 완료");
77
+ resolve([devMiddleware, hotMiddleware]);
78
+ });
79
+
80
+ const devMiddleware = wdm(compiler, {
81
+ publicPath: webpackConfig.output!.publicPath as string,
82
+ index: "index.html",
83
+ stats: false
84
+ });
85
+
86
+ const hotMiddleware = whm(compiler, {
87
+ path: `${webpackConfig.output!.publicPath as string}__webpack_hmr`,
88
+ log: false
89
+ });
90
+ });
91
+ }
92
+
93
+ public async buildAsync(): Promise<ISdCliPackageBuildResult[]> {
94
+ // DIST 비우기
95
+ await FsUtil.removeAsync(this._parsedTsconfig.options.outDir!);
96
+
97
+ // 빌드
98
+ this._logger.debug("Webpack 빌드 수행...");
99
+ const webpackConfig = this._getWebpackCommonConfig(false);
100
+ const compiler = webpack(webpackConfig);
101
+ const buildResults = await new Promise<ISdCliPackageBuildResult[]>((resolve, reject) => {
102
+ compiler.run((err, stats) => {
103
+ if (err != null || stats == null) {
104
+ reject(err);
105
+ return;
106
+ }
107
+
108
+ // 결과 반환
109
+ const results = SdCliBuildResultUtil.convertFromWebpackStats(stats);
110
+ resolve(results);
111
+ });
112
+ });
113
+
114
+ // 마무리
115
+ this._logger.debug("Webpack 빌드 완료");
116
+ return buildResults;
117
+ }
118
+
119
+ private _getWebpackCommonConfig(watch: boolean): webpack.Configuration {
120
+ console.log(watch);
121
+
122
+ const npmConfig = this._getNpmConfig(this._rootPath)!;
123
+ const pkgVersion = npmConfig.version;
124
+
125
+ const pkgKey = npmConfig.name.split("/").last()!;
126
+ const publicPath = `/${pkgKey}/`;
127
+
128
+ const cacheBasePath = path.resolve(this._rootPath, ".angular");
129
+ const cachePath = path.resolve(cacheBasePath, pkgVersion);
130
+
131
+ const distPath = this._parsedTsconfig.options.outDir;
132
+
133
+ const sassImplementation = new SassWorkerImplementation();
134
+
135
+ return {
136
+ plugins: [
137
+ new NamedChunksPlugin(),
138
+ new DedupeModuleResolvePlugin(),
139
+ /*new webpack.ProgressPlugin({
140
+ handler: (per: number, msg: string, ...args: string[]) => {
141
+ const phaseText = msg ? ` - phase: ${msg}` : "";
142
+ const argsText = args.length > 0 ? ` - args: [${args.join(", ")}]` : "";
143
+ this._logger.debug(`Webpack 빌드 수행중...(${Math.round(per * 100)}%)${phaseText}${argsText}`);
144
+ }
145
+ }),*/
146
+ new CommonJsUsageWarnPlugin(),
147
+ new CopyWebpackPlugin({
148
+ patterns: [
149
+ ...["favicon.ico", "assets/", "manifest.webmanifest"].map((item) => ({
150
+ context: this._rootPath,
151
+ to: item,
152
+ from: `src/${item}`,
153
+ noErrorOnMissing: true,
154
+ force: true,
155
+ globOptions: {
156
+ dot: true,
157
+ followSymbolicLinks: false,
158
+ ignore: [
159
+ ".gitkeep",
160
+ "**/.DS_Store",
161
+ "**/Thumbs.db"
162
+ ].map((i) => PathUtil.posix(this._rootPath, i))
163
+ },
164
+ priority: 0
165
+ }))
166
+ ]
167
+ }),
168
+ new webpack.SourceMapDevToolPlugin({
169
+ filename: "[file].map",
170
+ include: [/js$/, /css$/],
171
+ sourceRoot: "webpack:///",
172
+ moduleFilenameTemplate: "[resource-path]",
173
+ append: undefined,
174
+ }),
175
+ new AngularWebpackPlugin({
176
+ tsconfig: this._tsconfigFilePath,
177
+ compilerOptions: {
178
+ sourceMap: true,
179
+ declaration: false,
180
+ declarationMap: false,
181
+ preserveSymlinks: false
182
+ },
183
+ jitMode: false,
184
+ emitNgModuleScope: true,
185
+ inlineStyleFileExtension: "scss"
186
+ }),
187
+ new AnyComponentStyleBudgetChecker([]),
188
+ {
189
+ apply: (compiler: webpack.Compiler) => {
190
+ compiler.hooks.shutdown.tap("sass-worker", () => {
191
+ sassImplementation.close();
192
+ });
193
+ }
194
+ },
195
+ new MiniCssExtractPlugin({ filename: "[name].css" }),
196
+ new SuppressExtractedTextChunksWebpackPlugin(),
197
+ // NgBuildAnalyticsPlugin,
198
+ new IndexHtmlWebpackPlugin({
199
+ indexPath: path.resolve(this._rootPath, "src/index.html"),
200
+ outputPath: "index.html",
201
+ baseHref: publicPath,
202
+ entrypoints: [
203
+ ["runtime", true],
204
+ ["polyfills", true],
205
+ ["styles", false],
206
+ ["vendor", true],
207
+ ["main", true]
208
+ ],
209
+ deployUrl: undefined,
210
+ sri: false,
211
+ cache: {
212
+ enabled: true,
213
+ basePath: cacheBasePath,
214
+ path: cachePath
215
+ },
216
+ postTransform: undefined,
217
+ optimization: {
218
+ scripts: false,
219
+ styles: { minify: false, inlineCritical: false },
220
+ fonts: { inline: false }
221
+ },
222
+ crossOrigin: "none",
223
+ lang: undefined
224
+ }),
225
+ new webpack.HotModuleReplacementPlugin()
226
+ ] as any[],
227
+ module: {
228
+ strictExportPresence: true,
229
+ parser: { javascript: { url: false, worker: false } },
230
+ rules: [
231
+ {
232
+ test: /\.?(svg|html)$/,
233
+ resourceQuery: /\?ngResource/,
234
+ type: "asset/source"
235
+ },
236
+ {
237
+ test: /[/\\]rxjs[/\\]add[/\\].+\.js$/,
238
+ sideEffects: true,
239
+ },
240
+ {
241
+ test: /\.[cm]?[tj]sx?$/,
242
+ resolve: { fullySpecified: false },
243
+ exclude: [/[/\\](?:core-js|@babel|tslib|web-animations-js|web-streams-polyfill)[/\\]/],
244
+ use: [
245
+ {
246
+ loader: "@angular-devkit/build-angular/src/babel/webpack-loader",
247
+ options: {
248
+ cacheDirectory: path.resolve(cachePath, "babel-webpack"),
249
+ scriptTarget: ts.ScriptTarget.ES2017,
250
+ aot: true,
251
+ optimize: false,
252
+ instrumentCode: undefined
253
+ }
254
+ }
255
+ ],
256
+ },
257
+ {
258
+ test: /\.[cm]?jsx?$/,
259
+ enforce: "pre",
260
+ loader: "source-map-loader",
261
+ options: {
262
+ filterSourceMappingUrl: (_mapUri: string, resourcePath: string) => {
263
+ return !resourcePath.includes("node_modules") || (/@simplysm[\\/]sd/).test(resourcePath);
264
+ }
265
+ }
266
+ },
267
+ {
268
+ test: /\.[cm]?tsx?$/,
269
+ loader: "@ngtools/webpack",
270
+ exclude: [/[/\\](?:css-loader|mini-css-extract-plugin|webpack-dev-server|webpack)[/\\]/],
271
+ },
272
+ {
273
+ test: /\.css$/i,
274
+ type: "asset/source"
275
+ },
276
+ {
277
+ test: /\.scss$/i,
278
+ rules: [
279
+ {
280
+ oneOf: [
281
+ {
282
+ use: [
283
+ {
284
+ loader: MiniCssExtractPlugin.loader
285
+ },
286
+ {
287
+ loader: "css-loader",
288
+ options: { url: false, sourceMap: true }
289
+ }
290
+ ],
291
+ include: path.resolve(this._rootPath, "src/styles.scss"),
292
+ resourceQuery: { not: [/\?ngResource/] }
293
+ },
294
+ {
295
+ type: "asset/source"
296
+ }
297
+ ]
298
+ },
299
+ {
300
+ use: [
301
+ {
302
+ loader: "resource-url-loader",
303
+ options: { sourceMap: true }
304
+ },
305
+ {
306
+ loader: "sass-loader",
307
+ options: {
308
+ implementation: sassImplementation,
309
+ sourceMap: true,
310
+ sassOptions: {
311
+ fiber: false,
312
+ precision: 8,
313
+ includePaths: [],
314
+ outputStyle: "expanded",
315
+ quietDeps: true,
316
+ verbose: undefined
317
+ }
318
+ }
319
+ }
320
+ ]
321
+ }
322
+ ]
323
+ },
324
+ {
325
+ loader: HmrLoader,
326
+ include: [path.resolve(this._rootPath, "src/main.ts")]
327
+ }
328
+ ]
329
+ },
330
+ mode: "development",
331
+ devtool: false,
332
+ target: ["web", "es2015"],
333
+ profile: false,
334
+ resolve: {
335
+ roots: [this._rootPath],
336
+ extensions: [".ts", ".tsx", ".mjs", ".js"],
337
+ symlinks: true,
338
+ modules: [this._workspaceRootPath, "node_modules"],
339
+ mainFields: ["es2015", "browser", "module", "main"],
340
+ conditionNames: ["es2015", "..."]
341
+ },
342
+ resolveLoader: {
343
+ symlinks: true
344
+ },
345
+ context: this._workspaceRootPath,
346
+ entry: {
347
+ main: [
348
+ `webpack-hot-middleware/client?path=${publicPath}__webpack_hmr&timeout=20000&reload=true&overlay=true`,
349
+ path.resolve(this._rootPath, "src/main.ts")
350
+ ],
351
+ polyfills: [path.resolve(this._rootPath, "src/polyfills.ts")],
352
+ styles: [path.resolve(this._rootPath, "src/styles.scss")]
353
+ },
354
+ output: {
355
+ uniqueName: pkgKey,
356
+ hashFunction: "xxhash64",
357
+ clean: true,
358
+ path: distPath,
359
+ publicPath,
360
+ filename: "[name].js",
361
+ chunkFilename: "[name].js",
362
+ libraryTarget: undefined,
363
+ crossOriginLoading: false,
364
+ trustedTypes: "angular#bundler",
365
+ scriptType: "module",
366
+ },
367
+ watch: false,
368
+ watchOptions: { poll: undefined, ignored: undefined },
369
+ performance: { hints: false },
370
+ ignoreWarnings: [
371
+ /Failed to parse source map from/,
372
+ /Add postcss as project dependency/,
373
+ /"@charset" must be the first rule in the file/,
374
+ ],
375
+ experiments: { backCompat: false, syncWebAssembly: true, asyncWebAssembly: true },
376
+ infrastructureLogging: { level: "error" },
377
+ stats: "errors-warnings",
378
+ cache: {
379
+ type: "filesystem",
380
+ profile: undefined,
381
+ cacheDirectory: path.resolve(cachePath, "angular-webpack"),
382
+ maxMemoryGenerations: 1,
383
+ name: createHash("sha1").update(pkgVersion).digest("hex")
384
+ },
385
+ optimization: {
386
+ minimizer: [],
387
+ moduleIds: "deterministic",
388
+ chunkIds: "named",
389
+ emitOnErrors: false,
390
+ runtimeChunk: "single",
391
+ splitChunks: {
392
+ maxAsyncRequests: Infinity,
393
+ cacheGroups: {
394
+ default: {
395
+ chunks: "async",
396
+ minChunks: 2,
397
+ priority: 10
398
+ },
399
+ common: {
400
+ name: "common",
401
+ chunks: "async",
402
+ minChunks: 2,
403
+ enforce: true,
404
+ priority: 5
405
+ },
406
+ vendors: false,
407
+ defaultVendors: {
408
+ name: "vendor",
409
+ chunks: (chunk) => chunk.name === "main",
410
+ enforce: true,
411
+ test: /[\\/]node_modules[\\/]/
412
+ }
413
+ }
414
+ }
415
+ },
416
+ node: false
417
+ };
418
+ }
419
+
420
+ private _getNpmConfig(pkgPath: string): INpmConfig | undefined {
421
+ if (!this._npmConfigMap.has(pkgPath)) {
422
+ this._npmConfigMap.set(pkgPath, FsUtil.readJson(path.resolve(pkgPath, "package.json")));
423
+ }
424
+ return this._npmConfigMap.get(pkgPath);
425
+ }
426
+ }