@asd14/vblocks 5.0.0 → 5.2.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
@@ -14,7 +14,7 @@ everything set up.
14
14
  -->
15
15
 
16
16
  **🔋 Maximal support**
17
- SWC, PostCSS (CSS Modules configured), MDX, React Refresh, Dotenv
17
+ SWC, PostCSS, CSS Modules, MDX, React Refresh, Dotenv
18
18
 
19
19
  <!--
20
20
  PARKED until SSG is finished, then name both outputs: SPA and SSG.
@@ -24,12 +24,12 @@ Builds to `dist/`, for any static host
24
24
  -->
25
25
 
26
26
  **📦 Several apps, one install**
27
- Apps share one `package.json` and `node_modules/`, a new app reuses the
27
+ Apps share one `package.json` and `node_modules/`. A new app reuses the
28
28
  installed packages
29
29
 
30
30
  **🤖 Optimized for AI agents**
31
- No config to write, so an agent spends its tokens on the content, not on the
32
- setup
31
+ The agent's context holds only the app: no Webpack, PostCSS or TypeScript
32
+ config to write, read or fix
33
33
 
34
34
  > [!IMPORTANT]
35
35
  > VBlocks needs Node `^22.22.3`, `^24.15.0` or `>=26.0`.
@@ -74,7 +74,7 @@ tutorial, How to is how-to guides, Vocabulary and Commands are reference.
74
74
  ## Quick Start
75
75
 
76
76
  <!--
77
- Diátaxis: tutorial. The fewest steps to a working build. It shows enough of
77
+ Diátaxis: tutorial. The fewest steps to a working bundle. It shows enough of
78
78
  VBlocks for the reader to decide whether VBlocks fits their project.
79
79
  -->
80
80
 
@@ -172,6 +172,7 @@ them.
172
172
  | **Project folder** | The folder with `package.json` |
173
173
  | **App folder** | The folder with `src/index.tsx` and `src/index.html` |
174
174
  | **Plumbing** | The project files `init` writes: `package.json`, `.gitignore` |
175
+ | **Bundle** | The files `build` writes to `dist/` |
175
176
 
176
177
  ## How to
177
178
 
@@ -196,7 +197,7 @@ another reader, eg. one with an existing app, goes last.
196
197
  ```
197
198
 
198
199
  Webpack replaces each `process.env["NAME"]` with the value of `NAME`, and
199
- `undefined` when `.env` does not set it. The build leaves out every variable
200
+ `undefined` when `.env` does not set it. The bundle leaves out every variable
200
201
  your code does not read.
201
202
 
202
203
  > [!WARNING]
@@ -205,8 +206,7 @@ your code does not read.
205
206
 
206
207
  > [!NOTE]
207
208
  > The [client types](src/types/client.d.ts) declare `process.env` and nothing
208
- > else from Node, because Webpack replaces nothing else. With the client types,
209
- > `tsc` fails on `process.cwd()` and `Buffer`.
209
+ > else from Node, because Webpack replaces nothing else.
210
210
 
211
211
  ### Stop using `../../../` everywhere
212
212
 
@@ -219,8 +219,8 @@ import { Component } from "@self/components"
219
219
 
220
220
  > [!NOTE]
221
221
  > VBlocks never reads your `tsconfig.json`, so `tsc` needs the alias too. The
222
- > one scaffolded by [`vblocks init`](#vblocks-init) already has it. Otherwise,
223
- > add:
222
+ > `tsconfig.json` that [`vblocks init`](#vblocks-init) writes already has it.
223
+ > Otherwise, add:
224
224
  >
225
225
  > ```json
226
226
  > {
@@ -250,14 +250,13 @@ import { Component } from "@self/components"
250
250
  export const Button = () => <button className={styles.primaryButton} />
251
251
  ```
252
252
 
253
- - **camelCase exports** - `.primary-button` becomes `styles.primaryButton`
253
+ - **camelCase keys** - `.primary-button` becomes `styles.primaryButton`
254
254
  - **Class names** - a bare hash in `production` mode, `[local]__[hash]` in
255
255
  `development` mode
256
- - **Global CSS** - a file without `.module` stays global,
257
- `import "./styles.css"`
258
256
 
259
257
  > [!NOTE]
260
- > The [client types](src/types/client.d.ts) declare `.css` imports.
258
+ > The [client types](src/types/client.d.ts) declare `.css` imports and other
259
+ > common client specific extensions like `.png`, `.ttf` etc.
261
260
 
262
261
  ### Replace a default config
263
262
 
@@ -270,7 +269,7 @@ Each of these configs in your app folder replaces the default of the same name:
270
269
  1. **[Eject](#vblocks-eject) the default into your app folder**
271
270
 
272
271
  ```sh
273
- npx vblocks eject postcss > flow-diagram/postcss.config.js
272
+ npx vblocks eject swc > flow-diagram/.swcrc
274
273
  ```
275
274
 
276
275
  2. **Update the ejected file**
@@ -283,8 +282,8 @@ Each of these configs in your app folder replaces the default of the same name:
283
282
  > transform when `serve` runs in `development` mode
284
283
 
285
284
  > [!NOTE]
286
- > [`build --single-file`](#vblocks-build) and
287
- > [`serve --analyze`](#vblocks-serve) reach your `webpack.config.js` as
285
+ > VBlocks passes [`build --single-file`](#vblocks-build) and
286
+ > [`serve --analyze`](#vblocks-serve) to your `webpack.config.js` as
288
287
  > `env.single` and `env.analyze`.
289
288
 
290
289
  ### Style with Tailwind
@@ -390,19 +389,21 @@ vblocks init <directory> [--template <name>] [--only <app|plumbing>]
390
389
  Write one part of the template (default: both)
391
390
  - `plumbing`: `package.json`, `.gitignore`
392
391
  - `app`: `src/`, `tsconfig.json` and the template's configs. `init` adds the
393
- template's dependencies to the nearest `package.json` above `<directory>`.
394
- Without one, `init` fails
392
+ template's dependencies to the `package.json` of the
393
+ [project folder](#vocabulary), the nearest folder above `<directory>` with a
394
+ `package.json`. Without that folder, `init` fails
395
395
 
396
396
  **Example**:
397
397
 
398
398
  <!--
399
- Using the `my-vblock-` prefix, so a reader who tries several scaffolders spots
400
- the folder at a glance, as with `vite-project` and `nuxt-app`.
399
+ Using the `my-vblocks-` prefix, the package name, so a reader who tries several
400
+ scaffolders spots the folder at a glance, as with `vite-project` and
401
+ `nuxt-app`.
401
402
  -->
402
403
 
403
404
  ```sh
404
- npx @asd14/vblocks init my-vblock-flow --template xyflow
405
- cd my-vblock-flow
405
+ npx @asd14/vblocks init my-vblocks-flow --template xyflow
406
+ cd my-vblocks-flow
406
407
  npm install
407
408
  ```
408
409
 
@@ -411,7 +412,7 @@ npm install
411
412
  Start the development server.
412
413
 
413
414
  - 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
415
+ - Listens on this machine only. Pass `--host 0.0.0.0` to listen on the network
415
416
  - Opens the page in the browser
416
417
 
417
418
  ```text
@@ -426,8 +427,8 @@ vblocks serve [--mode <mode>] [--prefix <directory>] [--analyze] [--log-level <l
426
427
  - `--analyze`\
427
428
  Run the bundle analyzer, on a free port
428
429
  - `--log-level <level>`\
429
- How much Webpack, its dev server and npm print: `error`, `warn`, `info` or
430
- `verbose` (default: `warn`)
430
+ How much Webpack, its development server and npm print: `error`, `warn`,
431
+ `info` or `verbose` (default: `warn`)
431
432
  - `<webpack option>`\
432
433
  Any other [`webpack serve`](https://webpack.js.org/api/cli/) option. VBlocks
433
434
  passes it to Webpack unchanged
@@ -435,7 +436,7 @@ vblocks serve [--mode <mode>] [--prefix <directory>] [--analyze] [--log-level <l
435
436
  **Example**:
436
437
 
437
438
  ```sh
438
- cd my-vblock-flow
439
+ cd my-vblocks-flow
439
440
  npx vblocks serve
440
441
  # ↓↓↓
441
442
  # npx webpack serve --config <webpack config> \
@@ -446,8 +447,8 @@ npx vblocks serve
446
447
 
447
448
  ### `vblocks build`
448
449
 
449
- Build the app into `dist/` in the app folder. Without `--single-file`, the
450
- build:
450
+ Build the app into a bundle in the `dist/` of the app folder. Without
451
+ `--single-file`, `build`:
451
452
 
452
453
  - Writes JS and CSS files with content-hashed names
453
454
  - Writes a `react` chunk, and a `vendors` chunk when your other dependencies
@@ -459,19 +460,19 @@ vblocks build [--mode <mode>] [--prefix <directory>] [--single-file] [--log-leve
459
460
 
460
461
  - `--mode <mode>`\
461
462
  The Webpack mode, `development` or `production` (default: `production`). In
462
- `production`, the build minifies JS and HTML, and cssnano, in the default
463
- PostCSS config, minifies CSS
463
+ `production`, `build` minifies JS and HTML, and the default PostCSS config
464
+ runs cssnano, which minifies CSS
464
465
  - `--prefix <directory>`\
465
466
  The [app folder](#vocabulary), which must exist (default: the current folder)
466
467
  - `--single-file`\
467
- The build writes one standalone `dist/index.html`, every asset inlined
468
+ `build` writes one standalone `dist/index.html`, every asset inlined
468
469
  - A browser opens the file from disk, with no server and no network
469
- - The build leaves `robots.txt` out
470
+ - The bundle has no `robots.txt`
470
471
  - Keep the route in the URL hash. On `file://`, `history.pushState` to another
471
472
  path throws
472
473
  - `--log-level <level>`\
473
- How much Webpack, its dev server and npm print: `error`, `warn`, `info` or
474
- `verbose` (default: `warn`)
474
+ How much Webpack and npm print: `error`, `warn`, `info` or `verbose` (default:
475
+ `warn`)
475
476
  - `<webpack option>`\
476
477
  Any other [`webpack build`](https://webpack.js.org/api/cli/) option, eg.
477
478
  `--stats errors-only`. VBlocks passes it to Webpack unchanged
@@ -479,7 +480,7 @@ vblocks build [--mode <mode>] [--prefix <directory>] [--single-file] [--log-leve
479
480
  **Example**:
480
481
 
481
482
  ```sh
482
- cd my-vblock-flow
483
+ cd my-vblocks-flow
483
484
  npx vblocks build
484
485
  # ↓↓↓
485
486
  # npx webpack build --config <webpack config> \
package/bin/vblocks.sh CHANGED
@@ -26,7 +26,8 @@ set -eu
26
26
  # After each part, run its post-init hooks in <directory>.
27
27
  # Print each file it adds or updates, then the next steps
28
28
  # serve Start the development server
29
- # build Build the app into dist/ in the app folder
29
+ # build Build the app into dist/ in the app folder, then print each
30
+ # file in it
30
31
  # eject Print a default config, to save in the app folder
31
32
  #
32
33
  # serve and build pass every option not listed under OPTIONS to Webpack.
@@ -275,17 +276,17 @@ snapshot_folder() {
275
276
  | sed 's|^\./||' \
276
277
  | LC_ALL=C sort \
277
278
  | while IFS= read -r snapshot_file; do
278
- printf '%s\t%s\n' "$(cksum < "$1/$snapshot_file")" "$snapshot_file"
279
+ printf '%s\t%s\n' "$(cksum <"$1/$snapshot_file")" "$snapshot_file"
279
280
  done
280
281
  }
281
282
 
282
- # print_changes <before-snapshot> <after-snapshot> <app-subdir>
283
+ # print_snapshot_diff <before-snapshot> <after-snapshot> <app-subdir>
283
284
  #
284
285
  # Print "add", "update" or "drop" for each file that differs between two
285
286
  # snapshots of the project folder. A path inside <app-subdir> prints as
286
287
  # $APP_DIR/..., the rest as $PROJECT_DIR/... <app-subdir> is "." when the app
287
288
  # is the project folder, empty when there is no app.
288
- print_changes() {
289
+ print_snapshot_diff() {
289
290
  # Every snapshot line has a tab. The AFTER line has none, so it marks where
290
291
  # the second snapshot starts
291
292
  {
@@ -316,6 +317,31 @@ print_changes() {
316
317
  '
317
318
  }
318
319
 
320
+ # print_build_files <app-dir>
321
+ #
322
+ # Print each file in the dist/ of <app-dir> as $APP_DIR/dist/..., a tab and its
323
+ # size, then the total size. Webpack empties dist/ before each build, so every
324
+ # file there is from the last build.
325
+ print_build_files() {
326
+ # An ejected config can write elsewhere
327
+ [ -d "$1/dist" ] || return 0
328
+
329
+ (cd -- "$1/dist" && find . -type f | LC_ALL=C sort) \
330
+ | while IFS= read -r build_file; do
331
+ printf '%s\t%s\n' "$(wc -c <"$1/dist/$build_file")" "${build_file#./}"
332
+ done \
333
+ | awk -F '\t' '
334
+ function format_size(bytes) {
335
+ if (bytes < 1024) return bytes " B"
336
+ if (bytes < 1024 * 1024) return sprintf("%.1f KiB", bytes / 1024)
337
+ return sprintf("%.1f MiB", bytes / 1024 / 1024)
338
+ }
339
+
340
+ { total += $1; printf "$APP_DIR/dist/%s\t%s\n", $2, format_size($1) }
341
+ END { printf "\nTotal\t%s\n", format_size(total) }
342
+ '
343
+ }
344
+
319
345
  # print_init_summary <parts> <template> <project-dir> <app-dir>
320
346
  #
321
347
  # Print the version, the parts of <template> that init writes and their
@@ -596,15 +622,15 @@ case "$COMMAND" in
596
622
  AFTER_SNAPSHOT=$(snapshot_folder "$PROJECT_DIR")
597
623
 
598
624
  print_init_summary "$PARTS" "$TEMPLATE" "$PROJECT_DIR" "$APP_DIR"
599
- print_changes "$BEFORE_SNAPSHOT" "$AFTER_SNAPSHOT" "$APP_SUBDIR"
625
+ print_snapshot_diff "$BEFORE_SNAPSHOT" "$AFTER_SNAPSHOT" "$APP_SUBDIR"
600
626
 
601
627
  case "$PARTS" in
602
628
  plumbing)
603
- printf '\nNext, add an app:\n\n'
629
+ printf '\nNext, add an app:\n'
604
630
  printf ' npx @asd14/vblocks init %s/<app> --only app\n' "$INIT_DIR"
605
631
  ;;
606
632
  app)
607
- printf '\nNext:\n\n'
633
+ printf '\nNext:\n'
608
634
  if [ "$PROJECT_DIR" != "$PWD" ]; then
609
635
  printf ' cd %s\n' "$(shorten_path "$PROJECT_DIR")"
610
636
  fi
@@ -612,7 +638,7 @@ case "$COMMAND" in
612
638
  printf ' npx vblocks serve --prefix %s\n' "$APP_SUBDIR"
613
639
  ;;
614
640
  *)
615
- printf '\nNext:\n\n'
641
+ printf '\nNext:\n'
616
642
  printf ' cd %s\n' "$INIT_DIR"
617
643
  printf ' npm install\n'
618
644
  printf ' npx vblocks serve\n'
@@ -635,6 +661,8 @@ case "$COMMAND" in
635
661
  # "$@" comes later, so it overrides this one
636
662
  if [ "$COMMAND" = "build" ]; then
637
663
  run_webpack build "$APP_DIR" "$WEBPACK_CONFIG" --mode production "$@"
664
+ printf '\n'
665
+ print_build_files "$APP_DIR"
638
666
  else
639
667
  run_webpack serve "$APP_DIR" "$WEBPACK_CONFIG" --mode development "$@"
640
668
  fi
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": "5.0.0",
4
+ "version": "5.2.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, set the browser targets it lacks, and turn on React
24
+ * Refresh when `hasReactRefresh` is true
24
25
  *
25
26
  * @param {{ hasReactRefresh: boolean }} options
26
27
  */
@@ -41,7 +42,7 @@ const loadSwcConfig = ({ hasReactRefresh }) => {
41
42
  ...typedConfig.jsc?.transform,
42
43
  react: {
43
44
  ...typedConfig.jsc?.transform?.react,
44
- // SWC marks components and their hooks, `ReactRefreshWebpackPlugin`
45
+ // SWC marks components and their hooks. `ReactRefreshWebpackPlugin`
45
46
  // loads the runtime that reads the marks. One without the other
46
47
  // breaks the page
47
48
  ...(hasReactRefresh ? { development: true, refresh: true } : {}),
@@ -52,28 +53,136 @@ 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'
63
64
  namedExport: false,
64
65
 
65
- // Use camelCase when referring to CSS classes in JavaScript code
66
- // Example: styles.myClass in JS maps to .my-class in CSS
66
+ // Map `.my-class` in CSS to `styles.myClass` in JavaScript
67
67
  exportLocalsConvention: "camelCase",
68
68
 
69
- // Use a unique hash in production, but include class names
70
- // in development for easier debugging
69
+ // Production names a class by its hash alone. Development puts the class
70
+ // name before the hash, for debugging
71
71
  localIdentName: isProduction ? "[hash:base64:8]" : "[local]__[hash:base64:5]",
72
72
  })
73
73
 
74
74
  /**
75
- * Replace every script, stylesheet and icon tag of the HTML with the content
76
- * of the file it points at, then drop that file from the output.
75
+ * The loaders of a CSS file. Webpack runs them last to first: PostCSS,
76
+ * css-loader, then the extract into a .css file
77
+ *
78
+ * @param {Object} options
79
+ * @param {"local" | "global"} options.classScope - `local` renames each class
80
+ * to a unique name, for `*.module.css`. `global` keeps the names as written
81
+ * @param {boolean} options.isProduction
82
+ */
83
+ const getCssLoaders = ({ classScope, isProduction }) => [
84
+ {
85
+ loader: MiniCssExtractPlugin.loader,
86
+ },
87
+ {
88
+ loader: "css-loader",
89
+ options: {
90
+ // Resolve @import in CSS files
91
+ import: true,
92
+
93
+ // Run postcss-loader on each @import-ed CSS file too, before css-loader
94
+ importLoaders: 1,
95
+
96
+ modules: {
97
+ ...getCssModuleOptions(isProduction),
98
+ mode: classScope,
99
+ },
100
+ },
101
+ },
102
+ {
103
+ loader: "postcss-loader",
104
+ options: {
105
+ postcssOptions: {
106
+ config: VB_POSTCSS_CONFIG,
107
+ },
108
+ },
109
+ },
110
+ ]
111
+
112
+ /**
113
+ * Print one line of VBlocks: a verb, then its subject. The `[vblocks]` prefix
114
+ * lets the reader tell it apart from the lines of Webpack
115
+ *
116
+ * @param {string} verb
117
+ * @param {string} subject
118
+ */
119
+ const log = (verb, subject) => {
120
+ process.stdout.write(`[vblocks] ${verb.padEnd(7)} ${subject}\n`)
121
+ }
122
+
123
+ /**
124
+ * Serve prints at most this many files per compile, then a count of the rest
125
+ */
126
+ const MAX_REPORTED_FILE_EVENTS = 5
127
+
128
+ /**
129
+ * In serve, print each file of the build that was updated, added or dropped
130
+ * since the last compile, as $APP_DIR/...
131
+ *
132
+ * @param {string} appDir
133
+ * @returns {(compiler: import("webpack").Compiler) => void}
134
+ */
135
+ const reportFileEvents = appDir => compiler => {
136
+ /** @type {Set<string> | undefined} */
137
+ let previousFiles
138
+ /** @type {Array<[string, string]>} */
139
+ let fileEvents = []
140
+
141
+ // The watcher also reports editor swap files and folders, eg. the src/ that
142
+ // Tailwind scans. Only a file the last compile used is part of the build
143
+ compiler.hooks.watchRun.tap("VBlocksReportFileEvents", watcher => {
144
+ fileEvents = []
145
+ for (const file of watcher.modifiedFiles ?? []) {
146
+ if (
147
+ previousFiles?.has(file) &&
148
+ fs.statSync(file, { throwIfNoEntry: false })?.isFile()
149
+ ) {
150
+ fileEvents.push(["update", file])
151
+ }
152
+ }
153
+ for (const file of watcher.removedFiles ?? []) {
154
+ if (previousFiles?.has(file)) fileEvents.push(["drop", file])
155
+ }
156
+ })
157
+
158
+ // A file joins the build when an import first reaches it. The watcher has
159
+ // no event for that
160
+ compiler.hooks.done.tap("VBlocksReportFileEvents", stats => {
161
+ const files = new Set(stats.compilation.fileDependencies)
162
+
163
+ if (previousFiles) {
164
+ const addedFiles = [...files]
165
+ .filter(file => !previousFiles?.has(file))
166
+ .filter(file => !file.includes("/node_modules/"))
167
+ .toSorted()
168
+
169
+ for (const file of addedFiles) fileEvents.push(["add", file])
170
+ }
171
+ previousFiles = files
172
+
173
+ for (const [verb, file] of fileEvents.slice(0, MAX_REPORTED_FILE_EVENTS)) {
174
+ log(verb, file.replace(appDir, "$APP_DIR"))
175
+ }
176
+ if (fileEvents.length > MAX_REPORTED_FILE_EVENTS) {
177
+ log("…", `and ${fileEvents.length - MAX_REPORTED_FILE_EVENTS} more`)
178
+ }
179
+ })
180
+ }
181
+
182
+ /**
183
+ * Replace every script and stylesheet tag of the HTML with the content of the
184
+ * file it points at. Point the icon tag at a data URL of its file. Then drop
185
+ * each of those files from the output.
77
186
  *
78
187
  * Lives in this file so an ejected config stays one file.
79
188
  *
@@ -98,8 +207,9 @@ const inlineAssets = compiler => {
98
207
  return {
99
208
  ...tag,
100
209
  attributes: {},
101
- // The HTML parser reads `</script` and `<!--` inside a script, a
102
- // `\x3C` means the same `<` to JavaScript and nothing to the parser
210
+ // The HTML parser reads `</script` and `<!--` inside a script.
211
+ // Inside a JavaScript string, `\x3C` means `<` to JavaScript and
212
+ // nothing to the parser
103
213
  innerHTML: takeAsset(src)
104
214
  .toString()
105
215
  .replaceAll("</script", String.raw`\x3C/script`)
@@ -122,7 +232,7 @@ const inlineAssets = compiler => {
122
232
  ...tag,
123
233
  attributes: {
124
234
  rel,
125
- // `bin/vblocks.sh` only ever passes a `favicon.svg`
235
+ // `bin/vblocks.sh` only passes a `favicon.svg`
126
236
  href: `data:image/svg+xml;base64,${Buffer.from(takeAsset(href)).toString("base64")}`,
127
237
  },
128
238
  }
@@ -144,9 +254,9 @@ const inlineAssets = compiler => {
144
254
  /**
145
255
  * @typedef {Object} VBlocksEnvironment
146
256
  *
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
257
+ * @property {string} entryDir - The app folder: `--prefix`, or the folder VBlocks runs in
258
+ * @property {string} robotsPath - Path to the robots.txt copied to the output folder
259
+ * @property {string} faviconPath - Path to the favicon.svg copied to the output folder
150
260
  * @property {boolean} [single] - Build one standalone index.html, every asset inlined
151
261
  * @property {boolean} [analyze] - Run the bundle analyzer next to the dev server
152
262
  * @property {"error"|"warn"|"info"|"verbose"} [logLevel] - How much Webpack and its dev server print
@@ -183,7 +293,6 @@ export default (
183
293
  const isAnalyze = Boolean(analyze) && isServe
184
294
  const hasReactRefresh = isServe && mode === "development"
185
295
  const swcConfig = loadSwcConfig({ hasReactRefresh })
186
- const commonPostCSSConfigs = createCssModuleConfig(isProduction)
187
296
 
188
297
  const paths = {
189
298
  appEntry: `${entryDir}/src/index.tsx`,
@@ -196,9 +305,8 @@ export default (
196
305
  }
197
306
 
198
307
  return {
199
- // The order of entries matters.
200
- // The global CSS file needs to be first in the array to ensure its
201
- // styles are loaded before any component-specific styles.
308
+ // The global CSS comes first, so component styles load after it and win
309
+ // ties
202
310
  entry: [
203
311
  ...(fs.existsSync(paths.globalCssEntry) ? [paths.globalCssEntry] : []),
204
312
  paths.appEntry,
@@ -206,24 +314,30 @@ export default (
206
314
 
207
315
  mode: mode,
208
316
 
209
- // Keep the summary of VBlocks on screen. `--log-level` sets it, `--stats`
210
- // overrides it
317
+ // Merge the saves within 100 ms into one compile, eg. those of a codemod.
318
+ // A longer wait would stop an edit from feeling instant
319
+ watchOptions: { aggregateTimeout: 100 },
320
+
321
+ // Print little, so the summary of VBlocks stays on screen. `--log-level`
322
+ // picks the stats preset. `--stats` overrides it
211
323
  stats: STATS_BY_LOG_LEVEL[logLevel],
212
324
 
213
325
  output: {
214
- // A standalone file opens from disk, where "/" is the filesystem root
326
+ // The browser opens a standalone file from disk, where "/" is the
327
+ // filesystem root
215
328
  publicPath: isSingle ? "" : "/",
216
329
  path: paths.output,
217
- // Cannot use 'contenthash' when hot reloading is enabled.
330
+ // Hot Module Replacement breaks on `[contenthash]` names, so serve leaves
331
+ // out the hash
218
332
  filename: isServe ? "js/[name].js" : "js/[name].[contenthash].js",
219
- // Delete existing files in the output directory before building
333
+ // Empty the output folder before each build
220
334
  clean: true,
221
335
  },
222
336
 
223
337
  devtool: isServe ? "eval-source-map" : false,
224
338
 
225
- // Both Webpack and SWC should use the same browserslist configuration
226
- // with .swcrc as source of truth
339
+ // Webpack builds for the browser targets of the SWC config, so both tools
340
+ // agree
227
341
  target: `browserslist:${swcConfig.env.targets}`,
228
342
 
229
343
  module: {
@@ -246,68 +360,12 @@ export default (
246
360
  },
247
361
  {
248
362
  test: /\.module\.css$/,
249
- use: [
250
- {
251
- loader: MiniCssExtractPlugin.loader,
252
- },
253
- {
254
- loader: "css-loader",
255
- options: {
256
- // Enable/disable @import resolving.
257
- import: true,
258
-
259
- // Apply "postcss-loader" on imported css files before
260
- // processing them with "css-loader"
261
- importLoaders: 1,
262
-
263
- modules: {
264
- ...commonPostCSSConfigs,
265
- mode: "local",
266
- },
267
- },
268
- },
269
- {
270
- loader: "postcss-loader",
271
- options: {
272
- postcssOptions: {
273
- config: VB_POSTCONFIG_PATH,
274
- },
275
- },
276
- },
277
- ],
363
+ use: getCssLoaders({ classScope: "local", isProduction }),
278
364
  },
279
365
  {
280
366
  test: /\.css$/,
281
367
  exclude: /\.module\.css$/,
282
- use: [
283
- {
284
- loader: MiniCssExtractPlugin.loader,
285
- },
286
- {
287
- loader: "css-loader",
288
- options: {
289
- // Enable/disable @import resolving.
290
- import: true,
291
-
292
- // Apply "postcss-loader" on imported css files before
293
- // processing them with "css-loader"
294
- importLoaders: 1,
295
-
296
- modules: {
297
- ...commonPostCSSConfigs,
298
- mode: "global",
299
- },
300
- },
301
- },
302
- {
303
- loader: "postcss-loader",
304
- options: {
305
- postcssOptions: {
306
- config: VB_POSTCONFIG_PATH,
307
- },
308
- },
309
- },
310
- ],
368
+ use: getCssLoaders({ classScope: "global", isProduction }),
311
369
  },
312
370
  {
313
371
  test: /\.(jpg|gif|png|svg)$/,
@@ -340,19 +398,19 @@ export default (
340
398
  devServer: isServe
341
399
  ? {
342
400
  compress: true,
343
- // When using the HTML5 History API, the index.html page will likely
344
- // have to be served in place of any 404 responses.
401
+ // Serve index.html in place of a 404, so the router of the app handles
402
+ // every path
345
403
  historyApiFallback: true,
346
404
 
347
- // Hot Module Replacement (HMR) exchanges, adds, or removes modules
348
- // while an application is running, without a full reload.
405
+ // Hot Module Replacement updates, adds and drops modules in the running
406
+ // app, without a full reload
349
407
  // https://webpack.js.org/concepts/hot-module-replacement/
350
408
  hot: true,
351
409
 
352
- // Tells dev-server to open the browser after server had been started.
410
+ // Open the browser once the server starts
353
411
  open: true,
354
412
 
355
- // Only this machine opens the page. `--host 0.0.0.0` exposes it to
413
+ // Only this machine can open the page. `--host 0.0.0.0` exposes it to
356
414
  // the network, eg. for a phone
357
415
  host: "localhost",
358
416
 
@@ -360,8 +418,8 @@ export default (
360
418
  // folder VBlocks runs in
361
419
  static: false,
362
420
 
363
- // Print the URL once, as the result of serve. The startup lines of
364
- // the dev server stay hidden, see infrastructureLogging
421
+ // Print the URL once, as the result of serve. At the `warn` log
422
+ // level, the dev server prints no startup lines
365
423
  onListening: developmentServer => {
366
424
  const address = developmentServer.server?.address()
367
425
 
@@ -369,12 +427,10 @@ export default (
369
427
  if (typeof address !== "object" || address === null) return
370
428
 
371
429
  const { port } = address
372
- process.stdout.write(`Local: http://localhost:${port}\n`)
430
+ log("serve", `http://localhost:${port}`)
373
431
 
374
432
  if (developmentServer.options.host !== "localhost") {
375
- process.stdout.write(
376
- `Network: ${developmentServer.options.host}:${port}\n`
377
- )
433
+ log("expose", `${developmentServer.options.host}:${port}`)
378
434
  }
379
435
  },
380
436
 
@@ -392,8 +448,8 @@ export default (
392
448
  new HtmlWebPackPlugin({
393
449
  template: paths.htmlTemplate,
394
450
  favicon: paths.favicon,
395
- // An inline script ignores `defer` and runs where it stands, so it
396
- // must stand after the element the app renders into
451
+ // An inline script ignores `defer` and runs once the parser reaches
452
+ // it. It must come after the element the app renders into
397
453
  inject: isSingle ? "body" : "head",
398
454
  }),
399
455
 
@@ -417,11 +473,13 @@ export default (
417
473
  ],
418
474
  }),
419
475
 
420
- // A dynamic `import()` would otherwise emit a second file
476
+ // Without it, Webpack emits a second file for each dynamic `import()`
421
477
  isSingle && new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }),
422
478
 
423
479
  isSingle && inlineAssets,
424
480
 
481
+ isServe && reportFileEvents(entryDir),
482
+
425
483
  isAnalyze &&
426
484
  new BundleAnalyzerPlugin({
427
485
  openAnalyzer: false,
@@ -440,13 +498,14 @@ export default (
440
498
  },
441
499
 
442
500
  optimization: {
443
- // Enable tree shaking for unused exports
501
+ // Mark unused exports, so the minifier drops them
444
502
  usedExports: true,
445
503
 
446
- // Merge runtime.js into main.js for fewer HTTP request
504
+ // Merge runtime.js into main.js for fewer HTTP requests
447
505
  runtimeChunk: false,
448
506
 
449
- // Extract node_module dependencies into a separate chunk for better caching
507
+ // Split node_modules into the react and vendors chunks, so the browser
508
+ // keeps them cached across builds of the app
450
509
  splitChunks: !isSingle && {
451
510
  chunks: "all",
452
511
  cacheGroups: {
@@ -469,6 +528,10 @@ export default (
469
528
  performance: {
470
529
  // A standalone file is over the size limit by design
471
530
  hints: isProduction && !isSingle ? "warning" : false,
531
+ // React and react-dom alone are over the 244 KiB default. Vite warns
532
+ // at 500 kB
533
+ maxAssetSize: 500 * 1000,
534
+ maxEntrypointSize: 500 * 1000,
472
535
  },
473
536
  }
474
537
  }