@dr.pogodin/react-utils 1.50.0 → 1.50.1

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.
Files changed (2) hide show
  1. package/bin/build.js +346 -0
  2. package/package.json +1 -1
package/bin/build.js ADDED
@@ -0,0 +1,346 @@
1
+ #!/usr/bin/env node
2
+
3
+ /* eslint-disable no-console, import/no-extraneous-dependencies */
4
+ //* global console, process */
5
+ import "core-js/modules/es.iterator.constructor.js";
6
+ import "core-js/modules/es.iterator.for-each.js";
7
+ import "core-js/modules/es.iterator.map.js";
8
+ import "core-js/modules/es.json.stringify.js";
9
+ import childProcess from 'node:child_process';
10
+ import fs from 'node:fs';
11
+ import { createRequire } from 'node:module';
12
+ import path from 'node:path';
13
+ import { mapValues, merge } from 'lodash-es';
14
+
15
+ // TODO: Disabled, because ESLint still does not support "exports" declarations
16
+ // in "package.json", and "rimraf" does not declare fallback entrance.
17
+ // See: https://github.com/import-js/eslint-plugin-import/issues/1810
18
+ // and update, once that issue is resolved.
19
+ import { rimraf } from 'rimraf';
20
+ import withWebpackBuild from 'webpack';
21
+
22
+ // TODO: Double-check, do we need it still? Can we do something better?
23
+ // To support TS configs for Webpack.
24
+ // @ts-expect-error "No types for this module exist yet"
25
+ import register from '@babel/register/experimental-worker.js';
26
+ import { program } from '@commander-js/extra-typings';
27
+ const validBuildTypes = ['app-development', 'app-production', 'library'];
28
+ /**
29
+ * Auxiliary wrapper around the command execution in a child process.
30
+ *
31
+ * TODO: Move to a server-side unitility module.
32
+ * TODO: The same code is duplicated in one of the tests.
33
+ *
34
+ * @param command - Command to execute;
35
+ * @param options - See https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
36
+ * @return Resolves to { error, stdout, stderr }.
37
+ */
38
+ async function exec(command, options = {}) {
39
+ return await new Promise(resolve => {
40
+ const child = childProcess.exec(command, options, (error, stdout, stderr) => {
41
+ resolve({
42
+ error,
43
+ stderr,
44
+ stdout
45
+ });
46
+ });
47
+ child.stderr?.pipe(process.stderr);
48
+ child.stdout?.pipe(process.stdout);
49
+ });
50
+ }
51
+
52
+ /* Command-line config. */
53
+ const args = program.description('Application / library build script').requiredOption('-t, --build-type <type>', `build type: ${validBuildTypes.map(type => `"${type}"`).join(', ')}`).option('-c, --copy-files <regex>', 'copy files matching the pattern into the build folder').option('-i, --in-dir <path>', 'input folder for the build', 'src').option('-o, --out-dir <path>', 'output folder for the build', 'build').option('-w, --watch', 'build, watch, and rebuild on source changes').option('--webpack-config <path>', 'path to the webpack config', 'webpack.config.ts').parse(process.argv).opts();
54
+ if (program.args.length) {
55
+ const details = program.args.map(x => `\t${x}`).join('\n');
56
+ program.error(`Unrecognized arguments:\n${details}`);
57
+ }
58
+
59
+ /**
60
+ * Asserts the given string is a valid build type.
61
+ */
62
+ function assertBuildType(buildType) {
63
+ if (!validBuildTypes.includes(buildType)) {
64
+ throw Error('Unknown build type');
65
+ }
66
+ }
67
+
68
+ /* Resolves the target build directory. */
69
+ const cwd = process.cwd();
70
+ const buildDir = path.resolve(cwd, args.outDir);
71
+ const sourceDir = path.resolve(cwd, args.inDir);
72
+
73
+ /* Prepares output directory: cleans existing files, creates the folders. */
74
+ rimraf.sync(buildDir);
75
+ fs.mkdirSync(buildDir, {
76
+ recursive: true
77
+ });
78
+
79
+ /**
80
+ * The build of TypeScript types for TS code modules.
81
+ *
82
+ * For now, it relies on the standard names of configuration files.
83
+ */
84
+ async function buildCodeTypes() {
85
+ console.log('Building code types...');
86
+ await exec(`${cwd}/node_modules/.bin/tsc --project tsconfig.types.json`);
87
+ await exec(`${cwd}/node_modules/.bin/tsc-alias -p tsconfig.types.json`);
88
+ }
89
+
90
+ /**
91
+ * The build of TypeScript types for SCSS modules.
92
+ *
93
+ * As of now, all configuration comes from the "typed-scss-modules.config.ts"
94
+ * file, and we just assume it exists, and has a valid config, matching other
95
+ * configurations passed into this script, or selected automatically.
96
+ */
97
+ async function buildScssTypes() {
98
+ console.log('Building SCSS types...');
99
+ await exec(`${cwd}/node_modules/.bin/typed-scss-modules .`);
100
+ }
101
+ let isRequireUpgraded = false;
102
+ const webpackOutDir = `${buildDir}/web-public`;
103
+
104
+ /**
105
+ * Creates a new Webpack compiler.
106
+ */
107
+ function newWebpackCompiler() {
108
+ if (!isRequireUpgraded) {
109
+ isRequireUpgraded = true;
110
+
111
+ // TODO: We don't have types for this function, see a related comment
112
+ // earlier.
113
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call
114
+ register({
115
+ envName: 'production',
116
+ extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],
117
+ root: process.cwd()
118
+ });
119
+ }
120
+ const require = createRequire(import.meta.url);
121
+
122
+ // TODO: Search harder, perhaps such types are already declared by Webpack?
123
+
124
+ // TODO: Can we actually assert the input is a correct Webpack configuration?
125
+ // eslint-disable-next-line import/no-dynamic-require
126
+ const configFile = require(path.resolve(cwd, args.webpackConfig));
127
+ const configOrFactory = 'default' in configFile ? configFile.default : configFile;
128
+ if (!args.buildType) throw Error('Build type must be specified for Webpack build');
129
+ assertBuildType(args.buildType);
130
+ let webpackEnv;
131
+ switch (args.buildType) {
132
+ case 'app-development':
133
+ webpackEnv = 'development';
134
+ break;
135
+ case 'app-production':
136
+ webpackEnv = 'production';
137
+ break;
138
+ case 'library':
139
+ default:
140
+ throw Error('Unexpected build type');
141
+ }
142
+ const config = typeof configOrFactory === 'function' ? configOrFactory(webpackEnv) : configOrFactory;
143
+ merge(config, {
144
+ output: {
145
+ path: webpackOutDir
146
+ }
147
+ });
148
+ const webpackCompiler = withWebpackBuild(config);
149
+
150
+ // TODO: Do we need to connect it some other way to
151
+ // output progress with Webpack@5?
152
+ // webpackCompiler.apply(new webpack.ProgressPlugin());
153
+
154
+ return webpackCompiler;
155
+ }
156
+
157
+ /**
158
+ * The handler of Webpack compilation results, written according to Webpack docs
159
+ * https://webpack.js.org/api/node/#error-handling
160
+ * @param error
161
+ * @param stats
162
+ */
163
+ function handleWebpackCompilationResults(error, stats) {
164
+ assertBuildType(args.buildType);
165
+ if (error) {
166
+ console.error(error.stack ?? error);
167
+ if (error.message) console.error(error.message);
168
+ process.exitCode = 1;
169
+ return;
170
+ }
171
+ const info = stats?.toJson();
172
+ if (stats?.hasErrors()) {
173
+ console.error('Error defailts:', info?.errors);
174
+ process.exitCode = 1;
175
+ return;
176
+ }
177
+ if (stats?.hasWarnings()) console.warn(info?.warnings);
178
+ console.log(stats?.toString({
179
+ colors: true
180
+ }));
181
+
182
+ // Here we emit the mapping of named chunk groups, needed at runtime
183
+ // for SSR and code-splitting.
184
+ const chunks = mapValues(stats?.toJson({
185
+ all: false,
186
+ chunkGroups: true
187
+ }).namedChunkGroups, item => item.assets?.map(({
188
+ name
189
+ }) => name));
190
+ fs.writeFileSync(`${webpackOutDir}/__chunk_groups__.json`, JSON.stringify(chunks, null, 2));
191
+ }
192
+
193
+ /**
194
+ * Builds the app bundle for web.
195
+ */
196
+ function buildWebBundle() {
197
+ const webpackCompiler = newWebpackCompiler();
198
+ webpackCompiler.run(handleWebpackCompilationResults);
199
+ webpackCompiler.close(() => undefined);
200
+ }
201
+ /**
202
+ * Runs Babel compilation.
203
+ * @param buildType - Build type; one of the BUILD_TYPES values.
204
+ * @param configPath - Optional. Path to the config file.
205
+ * If relative, it will be resolved relative to the current working directory.
206
+ * If absent, Babel will try to locate the default config file its usual way.
207
+ * @param extensions - Optional. Array of extensions
208
+ * to transform, each starting with the leading dot (e.g. '.ts'). If absent,
209
+ * Babel will use its default set of extensions.
210
+ * @param keepFileExtensions - Optional. If set, Babel will
211
+ * keep the original extensions for the transformed files; otherwise the will
212
+ * be turned into '.js' files.
213
+ * @param outDir - Output folder.
214
+ * @param srcDir - Source folder.
215
+ * @param watch - Optional. If set, Babel will be run in watch
216
+ * mode.
217
+ */
218
+ async function runBabel({
219
+ buildType,
220
+ configPath,
221
+ copyFiles,
222
+ extensions,
223
+ keepFileExtensions,
224
+ outDir,
225
+ srcDir,
226
+ watch
227
+ }) {
228
+ let command = `${cwd}/node_modules/.bin/babel ${srcDir} --out-dir ${outDir} --source-maps`;
229
+ if (buildType === 'production') command += ' --minified';
230
+ if (configPath) {
231
+ const url = path.resolve(cwd, configPath);
232
+ command += ` --config-file ${url}`;
233
+ }
234
+ if (copyFiles) command += ' --copy-files';
235
+ command += ` -x ${extensions.join(',')}`;
236
+ if (keepFileExtensions) command += ' --keep-file-extension';
237
+ if (watch) command += ' --watch';
238
+ await exec(command, {
239
+ env: {
240
+ ...process.env,
241
+ BABEL_ENV: buildType
242
+ }
243
+ });
244
+ }
245
+
246
+ /**
247
+ * Builds the "intermediate" library code with Babel. Essentially, it compiles
248
+ * out TypeScript, and produces JavaScript code which should be further compiled
249
+ * with Babel for server-side use, or bundled with Webpack for client-side
250
+ * execution. Any non-TS assets in the source are copied over to the build
251
+ * folder, conserving their location relative to the source / build folder root.
252
+ * @param watch
253
+ */
254
+ async function buildLibIntermediates(watch) {
255
+ if (!watch) console.log('Building library intermediates...');
256
+ await runBabel({
257
+ buildType: 'production',
258
+ configPath: './babel.libweb.config.js',
259
+ copyFiles: true,
260
+ extensions: ['.js', '.jsx', '.ts', '.tsx'],
261
+ outDir: `${buildDir}/web`,
262
+ srcDir: sourceDir,
263
+ watch
264
+ });
265
+ }
266
+ /**
267
+ * Builds with Babel the library code for server-side environment.
268
+ */
269
+ async function buildWithBabelForServerSide({
270
+ buildType,
271
+ configPath,
272
+ outDir,
273
+ srcDir
274
+ }) {
275
+ console.log(`Building with Babel for server-side environment in "${buildType}" mode...`);
276
+ await runBabel({
277
+ buildType,
278
+ configPath,
279
+ extensions: ['.js', '.jsx', '.ts', '.tsx'],
280
+ outDir,
281
+ srcDir
282
+ });
283
+ await runBabel({
284
+ buildType,
285
+ configPath,
286
+ extensions: ['.svg'],
287
+ keepFileExtensions: true,
288
+ outDir,
289
+ srcDir
290
+ });
291
+ }
292
+
293
+ /**
294
+ * Copies the files matching the pattern into the build folder.
295
+ */
296
+ function copyFromFolder(from, to, regex) {
297
+ console.log('Copying files...');
298
+ fs.readdirSync(from, {
299
+ withFileTypes: true
300
+ }).forEach(item => {
301
+ if (item.isDirectory()) {
302
+ copyFromFolder(`${from}/${item.name}`, `${to}/${item.name}`, regex);
303
+ } else if (item.isFile() && item.name.match(regex)) {
304
+ fs.mkdirSync(to, {
305
+ recursive: true
306
+ });
307
+ fs.copyFileSync(`${from}/${item.name}`, `${to}/${item.name}`);
308
+ }
309
+ });
310
+ }
311
+ void (async () => {
312
+ assertBuildType(args.buildType);
313
+ await buildScssTypes();
314
+ if (args.buildType === 'library') {
315
+ await buildCodeTypes();
316
+ await buildLibIntermediates();
317
+ await buildWithBabelForServerSide({
318
+ buildType: 'development',
319
+ configPath: 'babel.module.config.js',
320
+ outDir: `${buildDir}/development`,
321
+ srcDir: `${buildDir}/web`
322
+ });
323
+ await buildWithBabelForServerSide({
324
+ buildType: 'production',
325
+ configPath: 'babel.module.config.js',
326
+ outDir: `${buildDir}/production`,
327
+ srcDir: `${buildDir}/web`
328
+ });
329
+ }
330
+ if (args.buildType === 'app-development' || args.buildType === 'app-production') {
331
+ await buildWithBabelForServerSide({
332
+ buildType: 'development',
333
+ outDir: buildDir,
334
+ srcDir: sourceDir
335
+ });
336
+ buildWebBundle();
337
+ }
338
+ if (args.copyFiles) {
339
+ const regex = new RegExp(args.copyFiles);
340
+ copyFromFolder(sourceDir, buildDir, regex);
341
+ }
342
+ if (args.watch) {
343
+ console.log('Enabling the watch mode...');
344
+ if (args.buildType === 'library') await buildLibIntermediates(true);
345
+ }
346
+ })();
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.50.0",
2
+ "version": "1.50.1",
3
3
  "bin": {
4
4
  "react-utils-build": "bin/build.js",
5
5
  "react-utils-setup": "bin/setup.js"