@asd14/vblocks 4.1.0 → 5.1.0

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.
package/README.md CHANGED
@@ -411,10 +411,11 @@ npm install
411
411
  Start the development server.
412
412
 
413
413
  - Runs at `http://localhost:8080`, or the next free port
414
+ - Listens on this machine only, `--host 0.0.0.0` exposes it to the network
414
415
  - Opens the page in the browser
415
416
 
416
417
  ```text
417
- vblocks serve [--mode <mode>] [--prefix <directory>] [--analyze] [<webpack option>...]
418
+ vblocks serve [--mode <mode>] [--prefix <directory>] [--analyze] [--log-level <level>] [<webpack option>...]
418
419
  ```
419
420
 
420
421
  - `--mode <mode>`\
@@ -424,6 +425,9 @@ vblocks serve [--mode <mode>] [--prefix <directory>] [--analyze] [<webpack optio
424
425
  The [app folder](#vocabulary), which must exist (default: the current folder)
425
426
  - `--analyze`\
426
427
  Run the bundle analyzer, on a free port
428
+ - `--log-level <level>`\
429
+ How much Webpack, its dev server and npm print: `error`, `warn`, `info` or
430
+ `verbose` (default: `warn`)
427
431
  - `<webpack option>`\
428
432
  Any other [`webpack serve`](https://webpack.js.org/api/cli/) option. VBlocks
429
433
  passes it to Webpack unchanged
@@ -450,7 +454,7 @@ build:
450
454
  total over 20 KB (10 KB in `development`)
451
455
 
452
456
  ```text
453
- vblocks build [--mode <mode>] [--prefix <directory>] [--single-file] [<webpack option>...]
457
+ vblocks build [--mode <mode>] [--prefix <directory>] [--single-file] [--log-level <level>] [<webpack option>...]
454
458
  ```
455
459
 
456
460
  - `--mode <mode>`\
@@ -465,6 +469,9 @@ vblocks build [--mode <mode>] [--prefix <directory>] [--single-file] [<webpack o
465
469
  - The build leaves `robots.txt` out
466
470
  - Keep the route in the URL hash. On `file://`, `history.pushState` to another
467
471
  path throws
472
+ - `--log-level <level>`\
473
+ How much Webpack, its dev server and npm print: `error`, `warn`, `info` or
474
+ `verbose` (default: `warn`)
468
475
  - `<webpack option>`\
469
476
  Any other [`webpack build`](https://webpack.js.org/api/cli/) option, eg.
470
477
  `--stats errors-only`. VBlocks passes it to Webpack unchanged
package/bin/vblocks.sh CHANGED
@@ -8,9 +8,9 @@ set -eu
8
8
  # SYNOPSIS
9
9
  # vblocks init <directory> [--template <name>] [--only <app|plumbing>]
10
10
  # vblocks serve [--mode <mode>] [--prefix <directory>] [--analyze]
11
- # [<webpack option>...]
11
+ # [--log-level <level>] [<webpack option>...]
12
12
  # vblocks build [--mode <mode>] [--prefix <directory>] [--single-file]
13
- # [<webpack option>...]
13
+ # [--log-level <level>] [<webpack option>...]
14
14
  # vblocks eject <webpack|postcss|swc>
15
15
  # vblocks -h | --help
16
16
  #
@@ -45,6 +45,9 @@ set -eu
45
45
  # --single-file build: one standalone dist/index.html, every
46
46
  # asset inlined
47
47
  # --analyze serve: run the bundle analyzer, on a free port
48
+ # --log-level <level> serve, build: how much Webpack, its dev server and
49
+ # npm print: error, warn, info or verbose (default:
50
+ # warn)
48
51
  # -h, --help Print this help
49
52
  #
50
53
  # ENVIRONMENT
@@ -83,6 +86,7 @@ INIT_DIR="" # init <directory>
83
86
  TEMPLATE="plain" # init --template
84
87
  PARTS="plumbing app" # init --only, "plumbing" or "app"
85
88
  PREFIX="" # serve/build --prefix, the app folder
89
+ LOG_LEVEL="warn" # serve/build --log-level, error, warn, info or verbose
86
90
  EJECT_CONFIG="" # eject <config>
87
91
 
88
92
  # ╭───
@@ -275,13 +279,13 @@ snapshot_folder() {
275
279
  done
276
280
  }
277
281
 
278
- # print_changes <before-snapshot> <after-snapshot> <app-subdir>
282
+ # print_snapshot_diff <before-snapshot> <after-snapshot> <app-subdir>
279
283
  #
280
284
  # Print "add", "update" or "drop" for each file that differs between two
281
285
  # snapshots of the project folder. A path inside <app-subdir> prints as
282
286
  # $APP_DIR/..., the rest as $PROJECT_DIR/... <app-subdir> is "." when the app
283
287
  # is the project folder, empty when there is no app.
284
- print_changes() {
288
+ print_snapshot_diff() {
285
289
  # Every snapshot line has a tab. The AFTER line has none, so it marks where
286
290
  # the second snapshot starts
287
291
  {
@@ -377,9 +381,17 @@ run_webpack() {
377
381
  webpack_favicon_file=$(pick_file \
378
382
  "$webpack_app_dir/src/public/favicon.svg" "$VB_DIR/src/public/favicon.svg")
379
383
 
384
+ # npm echoes every npx call at notice, the level between warn and info
385
+ case "$LOG_LEVEL" in
386
+ info) webpack_npm_level="notice" ;;
387
+ *) webpack_npm_level=$LOG_LEVEL ;;
388
+ esac
389
+
380
390
  webpack_status=0
381
- npx webpack "$webpack_action" --config "$webpack_config" \
391
+ npx --loglevel="$webpack_npm_level" webpack "$webpack_action" \
392
+ --config "$webpack_config" \
382
393
  --env "entryDir=$webpack_app_dir" \
394
+ --env "logLevel=$LOG_LEVEL" \
383
395
  --env "robotsPath=$webpack_robots_file" \
384
396
  --env "faviconPath=$webpack_favicon_file" \
385
397
  "$@" || webpack_status=$?
@@ -494,6 +506,15 @@ case "$COMMAND" in
494
506
  shift
495
507
  ARG_COUNT=$((ARG_COUNT - 1))
496
508
  ;;
509
+ --log-level)
510
+ [ "$ARG_COUNT" -eq 0 ] && fail 2 "--log-level needs a level"
511
+ case "$1" in
512
+ error | warn | info | verbose) LOG_LEVEL=$1 ;;
513
+ *) fail 2 "Unknown level \"$1\", use error, warn, info or verbose" ;;
514
+ esac
515
+ shift
516
+ ARG_COUNT=$((ARG_COUNT - 1))
517
+ ;;
497
518
  --single-file)
498
519
  [ "$COMMAND" = "build" ] || fail 2 "--single-file works only with build"
499
520
  # The Webpack config does the work. An ejected config supports the
@@ -575,7 +596,7 @@ case "$COMMAND" in
575
596
  AFTER_SNAPSHOT=$(snapshot_folder "$PROJECT_DIR")
576
597
 
577
598
  print_init_summary "$PARTS" "$TEMPLATE" "$PROJECT_DIR" "$APP_DIR"
578
- print_changes "$BEFORE_SNAPSHOT" "$AFTER_SNAPSHOT" "$APP_SUBDIR"
599
+ print_snapshot_diff "$BEFORE_SNAPSHOT" "$AFTER_SNAPSHOT" "$APP_SUBDIR"
579
600
 
580
601
  case "$PARTS" in
581
602
  plumbing)
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@asd14/vblocks",
4
- "version": "4.1.0",
4
+ "version": "5.1.0",
5
5
  "description": "Zero-config React builds, as a static site or a single HTML file",
6
6
  "keywords": [
7
7
  "react",
@@ -11,16 +11,17 @@ import webpack from "webpack"
11
11
  import { BundleAnalyzerPlugin } from "webpack-bundle-analyzer"
12
12
 
13
13
  const VB_SWC_CONFIG = process.env["VB_SWC_CONFIG"]
14
- const VB_POSTCONFIG_PATH = process.env["VB_POSTCSS_CONFIG"]
14
+ const VB_POSTCSS_CONFIG = process.env["VB_POSTCSS_CONFIG"]
15
15
 
16
16
  if (!VB_SWC_CONFIG)
17
17
  throw new Error("VB_SWC_CONFIG environment variable is not defined")
18
18
 
19
- if (!VB_POSTCONFIG_PATH)
19
+ if (!VB_POSTCSS_CONFIG)
20
20
  throw new Error("VB_POSTCSS_CONFIG environment variable is not defined")
21
21
 
22
22
  /**
23
- * Load, parse and provide targets defaults for SWC configuration
23
+ * Read the SWC config, default its browser targets, and turn on React Refresh
24
+ * when asked
24
25
  *
25
26
  * @param {{ hasReactRefresh: boolean }} options
26
27
  */
@@ -52,11 +53,11 @@ const loadSwcConfig = ({ hasReactRefresh }) => {
52
53
  }
53
54
 
54
55
  /**
55
- * CSS module configuration shared between global and local styles
56
+ * The CSS Modules options of css-loader, shared by global and local styles
56
57
  *
57
58
  * @param {boolean} isProduction
58
59
  */
59
- const createCssModuleConfig = isProduction => ({
60
+ const getCssModuleOptions = isProduction => ({
60
61
  // import styles from './styles.module.css'
61
62
  // instead of
62
63
  // import * as styles from './styles.module.css'
@@ -71,6 +72,76 @@ const createCssModuleConfig = isProduction => ({
71
72
  localIdentName: isProduction ? "[hash:base64:8]" : "[local]__[hash:base64:5]",
72
73
  })
73
74
 
75
+ /**
76
+ * Print one line of VBlocks: a verb, then what it acted on. The tag tells it
77
+ * apart from the lines of Webpack
78
+ *
79
+ * @param {string} verb
80
+ * @param {string} subject
81
+ */
82
+ const log = (verb, subject) => {
83
+ process.stdout.write(`[vblocks] ${verb.padEnd(7)} ${subject}\n`)
84
+ }
85
+
86
+ /**
87
+ * Serve prints at most this many files per compile, then a count of the rest
88
+ */
89
+ const MAX_REPORTED_FILE_EVENTS = 5
90
+
91
+ /**
92
+ * Print each file a compile in watch mode updates, adds to the build or drops,
93
+ * as $APP_DIR/...
94
+ *
95
+ * @param {string} appDir
96
+ * @returns {(compiler: import("webpack").Compiler) => void}
97
+ */
98
+ const reportFileEvents = appDir => compiler => {
99
+ /** @type {Set<string> | undefined} */
100
+ let previousFiles
101
+ /** @type {Array<[string, string]>} */
102
+ let fileEvents = []
103
+
104
+ // The watcher also names editor files, and folders, eg. the src/ Tailwind
105
+ // scans. Only a file the last compile used is part of the build
106
+ compiler.hooks.watchRun.tap("VBlocksReportFileEvents", watcher => {
107
+ fileEvents = []
108
+ for (const file of watcher.modifiedFiles ?? []) {
109
+ if (
110
+ previousFiles?.has(file) &&
111
+ fs.statSync(file, { throwIfNoEntry: false })?.isFile()
112
+ ) {
113
+ fileEvents.push(["update", file])
114
+ }
115
+ }
116
+ for (const file of watcher.removedFiles ?? []) {
117
+ if (previousFiles?.has(file)) fileEvents.push(["drop", file])
118
+ }
119
+ })
120
+
121
+ // A file joins the build when an import first reaches it, the watcher has
122
+ // no event for that
123
+ compiler.hooks.done.tap("VBlocksReportFileEvents", stats => {
124
+ const files = new Set(stats.compilation.fileDependencies)
125
+
126
+ if (previousFiles) {
127
+ const addedFiles = [...files]
128
+ .filter(file => !previousFiles?.has(file))
129
+ .filter(file => !file.includes("/node_modules/"))
130
+ .toSorted()
131
+
132
+ for (const file of addedFiles) fileEvents.push(["add", file])
133
+ }
134
+ previousFiles = files
135
+
136
+ for (const [verb, file] of fileEvents.slice(0, MAX_REPORTED_FILE_EVENTS)) {
137
+ log(verb, file.replace(appDir, "$APP_DIR"))
138
+ }
139
+ if (fileEvents.length > MAX_REPORTED_FILE_EVENTS) {
140
+ log("…", `and ${fileEvents.length - MAX_REPORTED_FILE_EVENTS} more`)
141
+ }
142
+ })
143
+ }
144
+
74
145
  /**
75
146
  * Replace every script, stylesheet and icon tag of the HTML with the content
76
147
  * of the file it points at, then drop that file from the output.
@@ -144,12 +215,23 @@ const inlineAssets = compiler => {
144
215
  /**
145
216
  * @typedef {Object} VBlocksEnvironment
146
217
  *
147
- * @property {string} entryDir - Target directory from where vblocks cmd was called
148
- * @property {string} robotsPath - Path to robots.txt copied to the output directory
149
- * @property {string} faviconPath - Path to favicon.ico copied to the output directory
218
+ * @property {string} entryDir - The app folder: `--prefix`, or the folder vblocks runs in
219
+ * @property {string} robotsPath - Path to the robots.txt copied to the output folder
220
+ * @property {string} faviconPath - Path to the favicon.svg copied to the output folder
150
221
  * @property {boolean} [single] - Build one standalone index.html, every asset inlined
151
222
  * @property {boolean} [analyze] - Run the bundle analyzer next to the dev server
223
+ * @property {"error"|"warn"|"info"|"verbose"} [logLevel] - How much Webpack and its dev server print
224
+ */
225
+
226
+ /**
227
+ * The stats preset of Webpack for each log level of VBlocks
152
228
  */
229
+ const STATS_BY_LOG_LEVEL = /** @type {const} */ ({
230
+ error: "errors-only",
231
+ warn: "errors-warnings",
232
+ info: "normal",
233
+ verbose: "verbose",
234
+ })
153
235
 
154
236
  /**
155
237
  * @typedef {Object} VBlocksProps
@@ -163,7 +245,7 @@ const inlineAssets = compiler => {
163
245
  * @returns {WebpackConfiguration}
164
246
  */
165
247
  export default (
166
- { entryDir, robotsPath, faviconPath, single, analyze },
248
+ { entryDir, robotsPath, faviconPath, single, analyze, logLevel = "warn" },
167
249
  { mode }
168
250
  ) => {
169
251
  const isProduction = mode === "production"
@@ -172,7 +254,7 @@ export default (
172
254
  const isAnalyze = Boolean(analyze) && isServe
173
255
  const hasReactRefresh = isServe && mode === "development"
174
256
  const swcConfig = loadSwcConfig({ hasReactRefresh })
175
- const commonPostCSSConfigs = createCssModuleConfig(isProduction)
257
+ const cssModuleOptions = getCssModuleOptions(isProduction)
176
258
 
177
259
  const paths = {
178
260
  appEntry: `${entryDir}/src/index.tsx`,
@@ -185,9 +267,8 @@ export default (
185
267
  }
186
268
 
187
269
  return {
188
- // The order of entries matters.
189
- // The global CSS file needs to be first in the array to ensure its
190
- // styles are loaded before any component-specific styles.
270
+ // The global CSS comes first, so component styles load after it and win
271
+ // ties
191
272
  entry: [
192
273
  ...(fs.existsSync(paths.globalCssEntry) ? [paths.globalCssEntry] : []),
193
274
  paths.appEntry,
@@ -195,23 +276,29 @@ export default (
195
276
 
196
277
  mode: mode,
197
278
 
198
- // Keep the summary of VBlocks on screen, `--stats` overrides it
199
- stats: "errors-warnings",
279
+ // Fold the saves within 100 ms into one rebuild, eg. a codemod. A
280
+ // longer wait would stop an edit from feeling instant
281
+ watchOptions: { aggregateTimeout: 100 },
282
+
283
+ // Keep the summary of VBlocks on screen. `--log-level` sets it, `--stats`
284
+ // overrides it
285
+ stats: STATS_BY_LOG_LEVEL[logLevel],
200
286
 
201
287
  output: {
202
288
  // A standalone file opens from disk, where "/" is the filesystem root
203
289
  publicPath: isSingle ? "" : "/",
204
290
  path: paths.output,
205
- // Cannot use 'contenthash' when hot reloading is enabled.
291
+ // Hot reloading breaks on `[contenthash]` names, so serve leaves out the
292
+ // hash
206
293
  filename: isServe ? "js/[name].js" : "js/[name].[contenthash].js",
207
- // Delete existing files in the output directory before building
294
+ // Empty the output folder before each build
208
295
  clean: true,
209
296
  },
210
297
 
211
298
  devtool: isServe ? "eval-source-map" : false,
212
299
 
213
- // Both Webpack and SWC should use the same browserslist configuration
214
- // with .swcrc as source of truth
300
+ // Webpack builds for the browser targets of the SWC config, so both tools
301
+ // agree
215
302
  target: `browserslist:${swcConfig.env.targets}`,
216
303
 
217
304
  module: {
@@ -241,7 +328,7 @@ export default (
241
328
  {
242
329
  loader: "css-loader",
243
330
  options: {
244
- // Enable/disable @import resolving.
331
+ // Resolve @import in CSS files
245
332
  import: true,
246
333
 
247
334
  // Apply "postcss-loader" on imported css files before
@@ -249,7 +336,7 @@ export default (
249
336
  importLoaders: 1,
250
337
 
251
338
  modules: {
252
- ...commonPostCSSConfigs,
339
+ ...cssModuleOptions,
253
340
  mode: "local",
254
341
  },
255
342
  },
@@ -258,7 +345,7 @@ export default (
258
345
  loader: "postcss-loader",
259
346
  options: {
260
347
  postcssOptions: {
261
- config: VB_POSTCONFIG_PATH,
348
+ config: VB_POSTCSS_CONFIG,
262
349
  },
263
350
  },
264
351
  },
@@ -274,7 +361,7 @@ export default (
274
361
  {
275
362
  loader: "css-loader",
276
363
  options: {
277
- // Enable/disable @import resolving.
364
+ // Resolve @import in CSS files
278
365
  import: true,
279
366
 
280
367
  // Apply "postcss-loader" on imported css files before
@@ -282,7 +369,7 @@ export default (
282
369
  importLoaders: 1,
283
370
 
284
371
  modules: {
285
- ...commonPostCSSConfigs,
372
+ ...cssModuleOptions,
286
373
  mode: "global",
287
374
  },
288
375
  },
@@ -291,7 +378,7 @@ export default (
291
378
  loader: "postcss-loader",
292
379
  options: {
293
380
  postcssOptions: {
294
- config: VB_POSTCONFIG_PATH,
381
+ config: VB_POSTCSS_CONFIG,
295
382
  },
296
383
  },
297
384
  },
@@ -328,23 +415,52 @@ export default (
328
415
  devServer: isServe
329
416
  ? {
330
417
  compress: true,
331
- // When using the HTML5 History API, the index.html page will likely
332
- // have to be served in place of any 404 responses.
418
+ // Serve index.html in place of a 404, so the router of the app handles
419
+ // every path
333
420
  historyApiFallback: true,
334
421
 
335
- // Hot Module Replacement (HMR) exchanges, adds, or removes modules
336
- // while an application is running, without a full reload.
422
+ // Hot Module Replacement updates, adds and drops modules in the running
423
+ // app, without a full reload
337
424
  // https://webpack.js.org/concepts/hot-module-replacement/
338
425
  hot: true,
339
426
 
340
- // Tells dev-server to open the browser after server had been started.
427
+ // Open the browser once the server starts
341
428
  open: true,
429
+
430
+ // Only this machine opens the page. `--host 0.0.0.0` exposes it to
431
+ // the network, eg. for a phone
432
+ host: "localhost",
433
+
434
+ // Serve only what Webpack builds, not a public/ folder in the
435
+ // folder VBlocks runs in
436
+ static: false,
437
+
438
+ // Print the URL once, as the result of serve. The startup lines of
439
+ // the dev server stay hidden, see infrastructureLogging
440
+ onListening: developmentServer => {
441
+ const address = developmentServer.server?.address()
442
+
443
+ // A TCP server gives an object, a pipe server gives a string
444
+ if (typeof address !== "object" || address === null) return
445
+
446
+ const { port } = address
447
+ log("serve", `http://localhost:${port}`)
448
+
449
+ if (developmentServer.options.host !== "localhost") {
450
+ log("expose", `${developmentServer.options.host}:${port}`)
451
+ }
452
+ },
453
+
342
454
  client: {
343
455
  overlay: true,
344
456
  },
345
457
  }
346
458
  : undefined,
347
459
 
460
+ // At warn, hide the info lines of the dev server, and of the client in the
461
+ // browser console
462
+ infrastructureLogging: { level: logLevel },
463
+
348
464
  plugins: [
349
465
  new HtmlWebPackPlugin({
350
466
  template: paths.htmlTemplate,
@@ -374,11 +490,13 @@ export default (
374
490
  ],
375
491
  }),
376
492
 
377
- // A dynamic `import()` would otherwise emit a second file
493
+ // Without it, Webpack emits a second file for each dynamic `import()`
378
494
  isSingle && new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }),
379
495
 
380
496
  isSingle && inlineAssets,
381
497
 
498
+ isServe && reportFileEvents(entryDir),
499
+
382
500
  isAnalyze &&
383
501
  new BundleAnalyzerPlugin({
384
502
  openAnalyzer: false,
@@ -400,10 +518,11 @@ export default (
400
518
  // Enable tree shaking for unused exports
401
519
  usedExports: true,
402
520
 
403
- // Merge runtime.js into main.js for fewer HTTP request
521
+ // Merge runtime.js into main.js for fewer HTTP requests
404
522
  runtimeChunk: false,
405
523
 
406
- // Extract node_module dependencies into a separate chunk for better caching
524
+ // Split node_modules into the react and vendors chunks, so a new app
525
+ // build keeps their cache
407
526
  splitChunks: !isSingle && {
408
527
  chunks: "all",
409
528
  cacheGroups: {