@asd14/vblocks 5.1.0 → 5.3.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 config
32
+ 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
 
@@ -83,6 +83,12 @@ Using "scaffold", the field's word for what `init` does, eg. Yeoman and
83
83
  create-vite use it.
84
84
  -->
85
85
 
86
+ <!--
87
+ Using the `my-vblocks-` prefix, the package name, so a reader who tries several
88
+ scaffolders spots the folder at a glance, as with `vite-project` and
89
+ `nuxt-app`.
90
+ -->
91
+
86
92
  1. **Scaffold a minimal React project**
87
93
 
88
94
  ```sh
@@ -172,6 +178,7 @@ them.
172
178
  | **Project folder** | The folder with `package.json` |
173
179
  | **App folder** | The folder with `src/index.tsx` and `src/index.html` |
174
180
  | **Plumbing** | The project files `init` writes: `package.json`, `.gitignore` |
181
+ | **Bundle** | The files `build` writes to `dist/` |
175
182
 
176
183
  ## How to
177
184
 
@@ -196,8 +203,8 @@ another reader, eg. one with an existing app, goes last.
196
203
  ```
197
204
 
198
205
  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
- your code does not read.
206
+ `undefined` when `.env` does not set it. Webpack leaves out of the bundle every
207
+ variable your code does not read.
201
208
 
202
209
  > [!WARNING]
203
210
  > Never expose a secret, eg. an API key, through `process.env`. Anyone who loads
@@ -205,8 +212,7 @@ your code does not read.
205
212
 
206
213
  > [!NOTE]
207
214
  > 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`.
215
+ > else from Node, because Webpack replaces nothing else.
210
216
 
211
217
  ### Stop using `../../../` everywhere
212
218
 
@@ -218,9 +224,10 @@ import { Component } from "@self/components"
218
224
  ```
219
225
 
220
226
  > [!NOTE]
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:
227
+ > VBlocks compiles TypeScript with SWC and does not typecheck. Run `tsc`
228
+ > yourself. Your `tsconfig.json` needs the same alias as Webpack.
229
+ > The `tsconfig.json` that [`vblocks init`](#vblocks-init) writes already has
230
+ > it. Otherwise, add:
224
231
  >
225
232
  > ```json
226
233
  > {
@@ -250,27 +257,30 @@ import { Component } from "@self/components"
250
257
  export const Button = () => <button className={styles.primaryButton} />
251
258
  ```
252
259
 
253
- - **camelCase exports** - `.primary-button` becomes `styles.primaryButton`
260
+ - **camelCase keys** - `.primary-button` becomes `styles.primaryButton`
254
261
  - **Class names** - a bare hash in `production` mode, `[local]__[hash]` in
255
262
  `development` mode
256
- - **Global CSS** - a file without `.module` stays global,
257
- `import "./styles.css"`
258
263
 
259
264
  > [!NOTE]
260
- > The [client types](src/types/client.d.ts) declare `.css` imports.
265
+ > The [client types](src/types/client.d.ts) declare `.css`, image and font
266
+ > imports
261
267
 
262
268
  ### Replace a default config
263
269
 
264
- Each of these configs in your app folder replaces the default of the same name:
270
+ Each config in your app folder replaces the default of the same name:
265
271
 
266
272
  - `webpack.config.js`
267
273
  - `postcss.config.js`
274
+ - `postcss-preset-env`, which compiles nesting, `oklch()` and `color-mix()`
275
+ for older browsers and adds vendor prefixes
276
+ - `cssnano` in `production`
268
277
  - `.swcrc`
278
+ - browser targets `> 0.25%, not dead`
269
279
 
270
280
  1. **[Eject](#vblocks-eject) the default into your app folder**
271
281
 
272
282
  ```sh
273
- npx vblocks eject postcss > flow-diagram/postcss.config.js
283
+ npx vblocks eject swc > flow-diagram/.swcrc
274
284
  ```
275
285
 
276
286
  2. **Update the ejected file**
@@ -283,8 +293,8 @@ Each of these configs in your app folder replaces the default of the same name:
283
293
  > transform when `serve` runs in `development` mode
284
294
 
285
295
  > [!NOTE]
286
- > [`build --single-file`](#vblocks-build) and
287
- > [`serve --analyze`](#vblocks-serve) reach your `webpack.config.js` as
296
+ > VBlocks passes [`build --single-file`](#vblocks-build) and
297
+ > [`serve --analyze`](#vblocks-serve) to your `webpack.config.js` as
288
298
  > `env.single` and `env.analyze`.
289
299
 
290
300
  ### Style with Tailwind
@@ -370,8 +380,9 @@ app folder:
370
380
 
371
381
  <!--
372
382
  Diátaxis: reference. Mirror SYNOPSIS and OPTIONS of `vblocks --help`, in the
373
- same words. Each option and operand is a term, a line break, then its
374
- description, like OPTIONS in a man page.
383
+ same words. The SYNOPSIS puts one option per line, with its values, so it fits
384
+ the width of GitHub. Below it, each option is a bullet with its default, and
385
+ its description in sub-bullets.
375
386
  -->
376
387
 
377
388
  ### `vblocks init`
@@ -379,114 +390,95 @@ description, like OPTIONS in a man page.
379
390
  Write a template's plumbing, app, or both into `<directory>`.
380
391
 
381
392
  ```text
382
- vblocks init <directory> [--template <name>] [--only <app|plumbing>]
393
+ vblocks init <directory>
394
+ [--template <plain|xyflow>]
395
+ [--only <app|plumbing>]
383
396
  ```
384
397
 
385
- - `<directory>`\
386
- The folder to write into. It must be missing or empty
387
- - `--template <name>`\
388
- `plain`, or `xyflow` with React Flow and Tailwind (default: `plain`)
389
- - `--only <app|plumbing>`\
390
- Write one part of the template (default: both)
398
+ - `<directory>`
399
+ - The folder to write into. It must be missing or empty
400
+ - `--template` (default: `plain`)
401
+ - `xyflow` adds React Flow and Tailwind
402
+ - `--only` (default: both)
403
+ - Write one part of the template
391
404
  - `plumbing`: `package.json`, `.gitignore`
392
405
  - `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
395
-
396
- **Example**:
397
-
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`.
401
- -->
402
-
403
- ```sh
404
- npx @asd14/vblocks init my-vblock-flow --template xyflow
405
- cd my-vblock-flow
406
- npm install
407
- ```
406
+ template's dependencies to the `package.json` of the
407
+ [project folder](#vocabulary), the nearest folder above `<directory>` with a
408
+ `package.json`. Without that folder, `init` fails
408
409
 
409
410
  ### `vblocks serve`
410
411
 
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 `localhost`, so another device on your network, eg. a phone, cannot
416
+ open the page
415
417
  - Opens the page in the browser
416
418
 
417
419
  ```text
418
- vblocks serve [--mode <mode>] [--prefix <directory>] [--analyze] [--log-level <level>] [<webpack option>...]
420
+ vblocks serve
421
+ [--mode <development|production>]
422
+ [--prefix <directory>]
423
+ [--analyze]
424
+ [--log-level <error|warn|info|verbose>]
425
+ [<webpack option>...]
419
426
  ```
420
427
 
421
- - `--mode <mode>`\
422
- The Webpack mode, `development` or `production` (default: `development`).
423
- React Refresh runs only in `development`
424
- - `--prefix <directory>`\
425
- The [app folder](#vocabulary), which must exist (default: the current folder)
426
- - `--analyze`\
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`)
431
- - `<webpack option>`\
432
- Any other [`webpack serve`](https://webpack.js.org/api/cli/) option. VBlocks
433
- passes it to Webpack unchanged
434
-
435
- **Example**:
436
-
437
- ```sh
438
- cd my-vblock-flow
439
- npx vblocks serve
440
- # ↓↓↓
441
- # npx webpack serve --config <webpack config> \
442
- # --env entryDir=<app folder> \
443
- # --mode development \
444
- # ...
445
- ```
428
+ - `--mode` (default: `development`)
429
+ - The Webpack mode
430
+ - React Refresh runs only in `development`
431
+ - `--prefix` (default: the current folder)
432
+ - The [app folder](#vocabulary), which must exist
433
+ - `--analyze`
434
+ - Run the bundle analyzer, on a free port
435
+ - `--log-level` (default: `warn`)
436
+ - How much Webpack, its development server and npm print
437
+ - `<webpack option>...`
438
+ - Any other [`webpack serve`](https://webpack.js.org/api/cli/) option, passed
439
+ unchanged, eg. `--host 0.0.0.0` to listen on the network
446
440
 
447
441
  ### `vblocks build`
448
442
 
449
- Build the app into `dist/` in the app folder. Without `--single-file`, the
450
- build:
443
+ Build the app into a bundle in the `dist/` of the app folder.
444
+
445
+ By default, `build`:
451
446
 
452
447
  - Writes JS and CSS files with content-hashed names
453
448
  - Writes a `react` chunk, and a `vendors` chunk when your other dependencies
454
449
  total over 20 KB (10 KB in `development`)
450
+ - Inlines `jpg`, `gif`, `png` and `svg` files up to 10 KB, writes larger ones to
451
+ `dist/` with content-hashed names
452
+ - Writes `woff`, `woff2`, `ttf` and `eot` files to `dist/fonts/`
453
+ - Copies `src/public/favicon.svg` and `src/public/robots.txt` of your app, or
454
+ the defaults of VBlocks
455
455
 
456
456
  ```text
457
- vblocks build [--mode <mode>] [--prefix <directory>] [--single-file] [--log-level <level>] [<webpack option>...]
457
+ vblocks build
458
+ [--mode <development|production>]
459
+ [--prefix <directory>]
460
+ [--single-file]
461
+ [--log-level <error|warn|info|verbose>]
462
+ [<webpack option>...]
458
463
  ```
459
464
 
460
- - `--mode <mode>`\
461
- 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
464
- - `--prefix <directory>`\
465
- The [app folder](#vocabulary), which must exist (default: the current folder)
466
- - `--single-file`\
467
- The build writes one standalone `dist/index.html`, every asset inlined
465
+ - `--mode` (default: `production`)
466
+ - The Webpack mode
467
+ - In `production`, `build` minifies JS, HTML and, with the default PostCSS
468
+ config, CSS
469
+ - `--prefix` (default: the current folder)
470
+ - The [app folder](#vocabulary), which must exist
471
+ - `--single-file`
472
+ - Write one standalone `dist/index.html`, every asset inlined
468
473
  - A browser opens the file from disk, with no server and no network
469
- - The build leaves `robots.txt` out
470
- - Keep the route in the URL hash. On `file://`, `history.pushState` to another
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`)
475
- - `<webpack option>`\
476
- Any other [`webpack build`](https://webpack.js.org/api/cli/) option, eg.
477
- `--stats errors-only`. VBlocks passes it to Webpack unchanged
478
-
479
- **Example**:
480
-
481
- ```sh
482
- cd my-vblock-flow
483
- npx vblocks build
484
- # ↓↓↓
485
- # npx webpack build --config <webpack config> \
486
- # --env entryDir=<app folder> \
487
- # --mode production \
488
- # ...
489
- ```
474
+ - The bundle has no `robots.txt`
475
+ - Keep the route in the URL hash
476
+ - On `file://`, `history.pushState` to another path throws
477
+ - `--log-level` (default: `warn`)
478
+ - How much Webpack and npm print
479
+ - `<webpack option>...`
480
+ - Any other [`webpack build`](https://webpack.js.org/api/cli/) option, passed
481
+ unchanged, eg. `--stats errors-only`
490
482
 
491
483
  ### `vblocks eject`
492
484
 
@@ -496,8 +488,8 @@ Print a default config to stdout.
496
488
  vblocks eject <webpack|postcss|swc>
497
489
  ```
498
490
 
499
- - `<webpack|postcss|swc>`\
500
- The config to print
491
+ - `<webpack|postcss|swc>`
492
+ - The config to print
501
493
 
502
494
  Save the output in your app folder to
503
495
  [replace the default](#replace-a-default-config):
@@ -508,77 +500,6 @@ npx vblocks eject postcss > postcss.config.js
508
500
  npx vblocks eject swc > .swcrc
509
501
  ```
510
502
 
511
- <!--
512
- PARKED: sort each fact below into an existing section or a new one, or drop
513
- it. The client types and the PostCSS default have no home yet.
514
-
515
- ## Details
516
-
517
- ### TypeScript
518
-
519
- VBlocks does not check types and never reads your `tsconfig.json`. It only
520
- compiles TypeScript with SWC.
521
-
522
- For convenience, VBlocks provides client types in
523
- [`client.d.ts`](src/types/client.d.ts) for:
524
-
525
- - `.css` imports
526
- - Image and font imports
527
- - `process.env`
528
-
529
- You can use them in your `tsconfig.json`:
530
-
531
- ```json
532
- {
533
- "compilerOptions": {
534
- "types": ["@asd14/vblocks/client"]
535
- }
536
- }
537
- ```
538
-
539
- > [!NOTE]
540
- > The `tsconfig.json` that [`vblocks init`](#vblocks-init) writes has the client
541
- > types and the [`@self`](#stop-using--everywhere) alias.
542
-
543
- ### PostCSS
544
-
545
- The default `postcss.config.js`:
546
-
547
- ```js
548
- /**
549
- * @param {{ mode: "production" | "development" | "none" }} api
550
- */
551
- export default ({ mode }) => ({
552
- plugins: {
553
- "postcss-preset-env": {
554
- stage: 2,
555
- },
556
- "cssnano": mode === "production" && {
557
- preset: "default",
558
- },
559
- },
560
- })
561
- ```
562
-
563
- > [!NOTE]
564
- > `postcss-preset-env` compiles nesting, `oklch()` and `color-mix()` for older
565
- > browsers and adds vendor prefixes.
566
-
567
- ### Asset Handling
568
-
569
- - **Images** - the build inlines `jpg`, `gif`, `png` and `svg` files up to 10 KB
570
- - **Fonts** - the build writes `woff`, `woff2`, `ttf` and `eot` files to
571
- `dist/fonts/`
572
- - **Favicon and `robots.txt`** - yours or the default. With `--single-file`, the
573
- build inlines the favicon and leaves `robots.txt` out
574
-
575
- ## How It Works
576
-
577
- VBlocks is a POSIX shell script that runs Webpack. The script exports
578
- `VB_POSTCSS_CONFIG` and `VB_SWC_CONFIG`, the paths of the configs it picked. The
579
- Webpack config reads them.
580
- -->
581
-
582
503
  ## License
583
504
 
584
505
  MIT
package/bin/vblocks.sh CHANGED
@@ -6,11 +6,21 @@ set -eu
6
6
  # vblocks - Run Webpack with the configs of VBlocks, write a project or an app
7
7
  #
8
8
  # SYNOPSIS
9
- # vblocks init <directory> [--template <name>] [--only <app|plumbing>]
10
- # vblocks serve [--mode <mode>] [--prefix <directory>] [--analyze]
11
- # [--log-level <level>] [<webpack option>...]
12
- # vblocks build [--mode <mode>] [--prefix <directory>] [--single-file]
13
- # [--log-level <level>] [<webpack option>...]
9
+ # vblocks init <directory>
10
+ # [--template <plain|xyflow>]
11
+ # [--only <app|plumbing>]
12
+ # vblocks serve
13
+ # [--mode <development|production>]
14
+ # [--prefix <directory>]
15
+ # [--analyze]
16
+ # [--log-level <error|warn|info|verbose>]
17
+ # [<webpack option>...]
18
+ # vblocks build
19
+ # [--mode <development|production>]
20
+ # [--prefix <directory>]
21
+ # [--single-file]
22
+ # [--log-level <error|warn|info|verbose>]
23
+ # [<webpack option>...]
14
24
  # vblocks eject <webpack|postcss|swc>
15
25
  # vblocks -h | --help
16
26
  #
@@ -26,7 +36,8 @@ set -eu
26
36
  # After each part, run its post-init hooks in <directory>.
27
37
  # Print each file it adds or updates, then the next steps
28
38
  # serve Start the development server
29
- # build Build the app into dist/ in the app folder
39
+ # build Build the app into dist/ in the app folder, then print each
40
+ # file in it
30
41
  # eject Print a default config, to save in the app folder
31
42
  #
32
43
  # serve and build pass every option not listed under OPTIONS to Webpack.
@@ -275,7 +286,7 @@ snapshot_folder() {
275
286
  | sed 's|^\./||' \
276
287
  | LC_ALL=C sort \
277
288
  | while IFS= read -r snapshot_file; do
278
- printf '%s\t%s\n' "$(cksum < "$1/$snapshot_file")" "$snapshot_file"
289
+ printf '%s\t%s\n' "$(cksum <"$1/$snapshot_file")" "$snapshot_file"
279
290
  done
280
291
  }
281
292
 
@@ -316,6 +327,31 @@ print_snapshot_diff() {
316
327
  '
317
328
  }
318
329
 
330
+ # print_build_files <app-dir>
331
+ #
332
+ # Print each file in the dist/ of <app-dir> as $APP_DIR/dist/..., a tab and its
333
+ # size, then the total size. Webpack empties dist/ before each build, so every
334
+ # file there is from the last build.
335
+ print_build_files() {
336
+ # An ejected config can write elsewhere
337
+ [ -d "$1/dist" ] || return 0
338
+
339
+ (cd -- "$1/dist" && find . -type f | LC_ALL=C sort) \
340
+ | while IFS= read -r build_file; do
341
+ printf '%s\t%s\n' "$(wc -c <"$1/dist/$build_file")" "${build_file#./}"
342
+ done \
343
+ | awk -F '\t' '
344
+ function format_size(bytes) {
345
+ if (bytes < 1024) return bytes " B"
346
+ if (bytes < 1024 * 1024) return sprintf("%.1f KiB", bytes / 1024)
347
+ return sprintf("%.1f MiB", bytes / 1024 / 1024)
348
+ }
349
+
350
+ { total += $1; printf "$APP_DIR/dist/%s\t%s\n", $2, format_size($1) }
351
+ END { printf "\nTotal\t%s\n", format_size(total) }
352
+ '
353
+ }
354
+
319
355
  # print_init_summary <parts> <template> <project-dir> <app-dir>
320
356
  #
321
357
  # Print the version, the parts of <template> that init writes and their
@@ -600,11 +636,11 @@ case "$COMMAND" in
600
636
 
601
637
  case "$PARTS" in
602
638
  plumbing)
603
- printf '\nNext, add an app:\n\n'
639
+ printf '\nNext, add an app:\n'
604
640
  printf ' npx @asd14/vblocks init %s/<app> --only app\n' "$INIT_DIR"
605
641
  ;;
606
642
  app)
607
- printf '\nNext:\n\n'
643
+ printf '\nNext:\n'
608
644
  if [ "$PROJECT_DIR" != "$PWD" ]; then
609
645
  printf ' cd %s\n' "$(shorten_path "$PROJECT_DIR")"
610
646
  fi
@@ -612,7 +648,7 @@ case "$COMMAND" in
612
648
  printf ' npx vblocks serve --prefix %s\n' "$APP_SUBDIR"
613
649
  ;;
614
650
  *)
615
- printf '\nNext:\n\n'
651
+ printf '\nNext:\n'
616
652
  printf ' cd %s\n' "$INIT_DIR"
617
653
  printf ' npm install\n'
618
654
  printf ' npx vblocks serve\n'
@@ -635,6 +671,8 @@ case "$COMMAND" in
635
671
  # "$@" comes later, so it overrides this one
636
672
  if [ "$COMMAND" = "build" ]; then
637
673
  run_webpack build "$APP_DIR" "$WEBPACK_CONFIG" --mode production "$@"
674
+ printf '\n'
675
+ print_build_files "$APP_DIR"
638
676
  else
639
677
  run_webpack serve "$APP_DIR" "$WEBPACK_CONFIG" --mode development "$@"
640
678
  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.1.0",
4
+ "version": "5.3.0",
5
5
  "description": "Zero-config React builds, as a static site or a single HTML file",
6
6
  "keywords": [
7
7
  "react",
@@ -64,22 +64,22 @@
64
64
  "browserslist": "^4.29.3",
65
65
  "copy-webpack-plugin": "^14.0.0",
66
66
  "css-loader": "^7.1.5",
67
- "cssnano": "^9.6.0",
67
+ "cssnano": "^9.9.0",
68
68
  "dotenv-webpack": "^9.0.0",
69
69
  "html-webpack-plugin": "^5.6.8",
70
70
  "mini-css-extract-plugin": "^2.10.2",
71
- "postcss": "^8.5.29",
71
+ "postcss": "^8.5.30",
72
72
  "postcss-loader": "^8.2.1",
73
73
  "postcss-preset-env": "^11.6.1",
74
74
  "react-refresh": "^0.19.0",
75
75
  "swc-loader": "^0.2.7",
76
- "webpack": "^5.111.1",
76
+ "webpack": "^5.112.0",
77
77
  "webpack-bundle-analyzer": "^5.4.0",
78
78
  "webpack-cli": "^7.2.3",
79
79
  "webpack-dev-server": "^6.0.0"
80
80
  },
81
81
  "devDependencies": {
82
- "@asd14/eslint-config": "^15.4.0",
82
+ "@asd14/eslint-config": "^16.0.0",
83
83
  "@asd14/prettier-config": "^1.5.0",
84
84
  "@asd14/semantic-release-config": "^1.0.1",
85
85
  "@asd14/ts-config": "^1.6.0",
@@ -10,6 +10,8 @@ import MiniCssExtractPlugin from "mini-css-extract-plugin"
10
10
  import webpack from "webpack"
11
11
  import { BundleAnalyzerPlugin } from "webpack-bundle-analyzer"
12
12
 
13
+ // `bin/vblocks.sh` sets them to the PostCSS and SWC configs it picked, the
14
+ // app's own or the default
13
15
  const VB_SWC_CONFIG = process.env["VB_SWC_CONFIG"]
14
16
  const VB_POSTCSS_CONFIG = process.env["VB_POSTCSS_CONFIG"]
15
17
 
@@ -20,8 +22,8 @@ if (!VB_POSTCSS_CONFIG)
20
22
  throw new Error("VB_POSTCSS_CONFIG environment variable is not defined")
21
23
 
22
24
  /**
23
- * Read the SWC config, default its browser targets, and turn on React Refresh
24
- * when asked
25
+ * Read the SWC config, set the browser targets it lacks, and turn on React
26
+ * Refresh when `hasReactRefresh` is true
25
27
  *
26
28
  * @param {{ hasReactRefresh: boolean }} options
27
29
  */
@@ -42,7 +44,7 @@ const loadSwcConfig = ({ hasReactRefresh }) => {
42
44
  ...typedConfig.jsc?.transform,
43
45
  react: {
44
46
  ...typedConfig.jsc?.transform?.react,
45
- // SWC marks components and their hooks, `ReactRefreshWebpackPlugin`
47
+ // SWC marks components and their hooks. `ReactRefreshWebpackPlugin`
46
48
  // loads the runtime that reads the marks. One without the other
47
49
  // breaks the page
48
50
  ...(hasReactRefresh ? { development: true, refresh: true } : {}),
@@ -63,18 +65,55 @@ const getCssModuleOptions = isProduction => ({
63
65
  // import * as styles from './styles.module.css'
64
66
  namedExport: false,
65
67
 
66
- // Use camelCase when referring to CSS classes in JavaScript code
67
- // Example: styles.myClass in JS maps to .my-class in CSS
68
+ // Map `.my-class` in CSS to `styles.myClass` in JavaScript
68
69
  exportLocalsConvention: "camelCase",
69
70
 
70
- // Use a unique hash in production, but include class names
71
- // in development for easier debugging
71
+ // Production names a class by its hash alone. Development puts the class
72
+ // name before the hash, for debugging
72
73
  localIdentName: isProduction ? "[hash:base64:8]" : "[local]__[hash:base64:5]",
73
74
  })
74
75
 
75
76
  /**
76
- * Print one line of VBlocks: a verb, then what it acted on. The tag tells it
77
- * apart from the lines of Webpack
77
+ * The loaders of a CSS file. Webpack runs them last to first: PostCSS,
78
+ * css-loader, then the extract into a .css file
79
+ *
80
+ * @param {Object} options
81
+ * @param {"local" | "global"} options.classScope - `local` renames each class
82
+ * to a unique name, for `*.module.css`. `global` keeps the names as written
83
+ * @param {boolean} options.isProduction
84
+ */
85
+ const getCssLoaders = ({ classScope, isProduction }) => [
86
+ {
87
+ loader: MiniCssExtractPlugin.loader,
88
+ },
89
+ {
90
+ loader: "css-loader",
91
+ options: {
92
+ // Resolve @import in CSS files
93
+ import: true,
94
+
95
+ // Run postcss-loader on each @import-ed CSS file too, before css-loader
96
+ importLoaders: 1,
97
+
98
+ modules: {
99
+ ...getCssModuleOptions(isProduction),
100
+ mode: classScope,
101
+ },
102
+ },
103
+ },
104
+ {
105
+ loader: "postcss-loader",
106
+ options: {
107
+ postcssOptions: {
108
+ config: VB_POSTCSS_CONFIG,
109
+ },
110
+ },
111
+ },
112
+ ]
113
+
114
+ /**
115
+ * Print one line of VBlocks: a verb, then its subject. The `[vblocks]` prefix
116
+ * lets the reader tell it apart from the lines of Webpack
78
117
  *
79
118
  * @param {string} verb
80
119
  * @param {string} subject
@@ -89,8 +128,8 @@ const log = (verb, subject) => {
89
128
  const MAX_REPORTED_FILE_EVENTS = 5
90
129
 
91
130
  /**
92
- * Print each file a compile in watch mode updates, adds to the build or drops,
93
- * as $APP_DIR/...
131
+ * In serve, print each file of the build that was updated, added or dropped
132
+ * since the last compile, as $APP_DIR/...
94
133
  *
95
134
  * @param {string} appDir
96
135
  * @returns {(compiler: import("webpack").Compiler) => void}
@@ -101,8 +140,8 @@ const reportFileEvents = appDir => compiler => {
101
140
  /** @type {Array<[string, string]>} */
102
141
  let fileEvents = []
103
142
 
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
143
+ // The watcher also reports editor swap files and folders, eg. the src/ that
144
+ // Tailwind scans. Only a file the last compile used is part of the build
106
145
  compiler.hooks.watchRun.tap("VBlocksReportFileEvents", watcher => {
107
146
  fileEvents = []
108
147
  for (const file of watcher.modifiedFiles ?? []) {
@@ -118,7 +157,7 @@ const reportFileEvents = appDir => compiler => {
118
157
  }
119
158
  })
120
159
 
121
- // A file joins the build when an import first reaches it, the watcher has
160
+ // A file joins the build when an import first reaches it. The watcher has
122
161
  // no event for that
123
162
  compiler.hooks.done.tap("VBlocksReportFileEvents", stats => {
124
163
  const files = new Set(stats.compilation.fileDependencies)
@@ -143,8 +182,9 @@ const reportFileEvents = appDir => compiler => {
143
182
  }
144
183
 
145
184
  /**
146
- * Replace every script, stylesheet and icon tag of the HTML with the content
147
- * of the file it points at, then drop that file from the output.
185
+ * Replace every script and stylesheet tag of the HTML with the content of the
186
+ * file it points at. Point the icon tag at a data URL of its file. Then drop
187
+ * each of those files from the output.
148
188
  *
149
189
  * Lives in this file so an ejected config stays one file.
150
190
  *
@@ -169,8 +209,9 @@ const inlineAssets = compiler => {
169
209
  return {
170
210
  ...tag,
171
211
  attributes: {},
172
- // The HTML parser reads `</script` and `<!--` inside a script, a
173
- // `\x3C` means the same `<` to JavaScript and nothing to the parser
212
+ // The HTML parser reads `</script` and `<!--` inside a script.
213
+ // Inside a JavaScript string, `\x3C` means `<` to JavaScript and
214
+ // nothing to the parser
174
215
  innerHTML: takeAsset(src)
175
216
  .toString()
176
217
  .replaceAll("</script", String.raw`\x3C/script`)
@@ -193,7 +234,7 @@ const inlineAssets = compiler => {
193
234
  ...tag,
194
235
  attributes: {
195
236
  rel,
196
- // `bin/vblocks.sh` only ever passes a `favicon.svg`
237
+ // `bin/vblocks.sh` only passes a `favicon.svg`
197
238
  href: `data:image/svg+xml;base64,${Buffer.from(takeAsset(href)).toString("base64")}`,
198
239
  },
199
240
  }
@@ -215,7 +256,7 @@ const inlineAssets = compiler => {
215
256
  /**
216
257
  * @typedef {Object} VBlocksEnvironment
217
258
  *
218
- * @property {string} entryDir - The app folder: `--prefix`, or the folder vblocks runs in
259
+ * @property {string} entryDir - The app folder: `--prefix`, or the folder VBlocks runs in
219
260
  * @property {string} robotsPath - Path to the robots.txt copied to the output folder
220
261
  * @property {string} faviconPath - Path to the favicon.svg copied to the output folder
221
262
  * @property {boolean} [single] - Build one standalone index.html, every asset inlined
@@ -254,7 +295,6 @@ export default (
254
295
  const isAnalyze = Boolean(analyze) && isServe
255
296
  const hasReactRefresh = isServe && mode === "development"
256
297
  const swcConfig = loadSwcConfig({ hasReactRefresh })
257
- const cssModuleOptions = getCssModuleOptions(isProduction)
258
298
 
259
299
  const paths = {
260
300
  appEntry: `${entryDir}/src/index.tsx`,
@@ -276,20 +316,21 @@ export default (
276
316
 
277
317
  mode: mode,
278
318
 
279
- // Fold the saves within 100 ms into one rebuild, eg. a codemod. A
280
- // longer wait would stop an edit from feeling instant
319
+ // Merge the saves within 100 ms into one compile, eg. those of a codemod.
320
+ // A longer wait would stop an edit from feeling instant
281
321
  watchOptions: { aggregateTimeout: 100 },
282
322
 
283
- // Keep the summary of VBlocks on screen. `--log-level` sets it, `--stats`
284
- // overrides it
323
+ // Print little, so the summary of VBlocks stays on screen. `--log-level`
324
+ // picks the stats preset. `--stats` overrides it
285
325
  stats: STATS_BY_LOG_LEVEL[logLevel],
286
326
 
287
327
  output: {
288
- // A standalone file opens from disk, where "/" is the filesystem root
328
+ // The browser opens a standalone file from disk, where "/" is the
329
+ // filesystem root
289
330
  publicPath: isSingle ? "" : "/",
290
331
  path: paths.output,
291
- // Hot reloading breaks on `[contenthash]` names, so serve leaves out the
292
- // hash
332
+ // Hot Module Replacement breaks on `[contenthash]` names, so serve leaves
333
+ // out the hash
293
334
  filename: isServe ? "js/[name].js" : "js/[name].[contenthash].js",
294
335
  // Empty the output folder before each build
295
336
  clean: true,
@@ -321,68 +362,12 @@ export default (
321
362
  },
322
363
  {
323
364
  test: /\.module\.css$/,
324
- use: [
325
- {
326
- loader: MiniCssExtractPlugin.loader,
327
- },
328
- {
329
- loader: "css-loader",
330
- options: {
331
- // Resolve @import in CSS files
332
- import: true,
333
-
334
- // Apply "postcss-loader" on imported css files before
335
- // processing them with "css-loader"
336
- importLoaders: 1,
337
-
338
- modules: {
339
- ...cssModuleOptions,
340
- mode: "local",
341
- },
342
- },
343
- },
344
- {
345
- loader: "postcss-loader",
346
- options: {
347
- postcssOptions: {
348
- config: VB_POSTCSS_CONFIG,
349
- },
350
- },
351
- },
352
- ],
365
+ use: getCssLoaders({ classScope: "local", isProduction }),
353
366
  },
354
367
  {
355
368
  test: /\.css$/,
356
369
  exclude: /\.module\.css$/,
357
- use: [
358
- {
359
- loader: MiniCssExtractPlugin.loader,
360
- },
361
- {
362
- loader: "css-loader",
363
- options: {
364
- // Resolve @import in CSS files
365
- import: true,
366
-
367
- // Apply "postcss-loader" on imported css files before
368
- // processing them with "css-loader"
369
- importLoaders: 1,
370
-
371
- modules: {
372
- ...cssModuleOptions,
373
- mode: "global",
374
- },
375
- },
376
- },
377
- {
378
- loader: "postcss-loader",
379
- options: {
380
- postcssOptions: {
381
- config: VB_POSTCSS_CONFIG,
382
- },
383
- },
384
- },
385
- ],
370
+ use: getCssLoaders({ classScope: "global", isProduction }),
386
371
  },
387
372
  {
388
373
  test: /\.(jpg|gif|png|svg)$/,
@@ -427,7 +412,7 @@ export default (
427
412
  // Open the browser once the server starts
428
413
  open: true,
429
414
 
430
- // Only this machine opens the page. `--host 0.0.0.0` exposes it to
415
+ // Only this machine can open the page. `--host 0.0.0.0` exposes it to
431
416
  // the network, eg. for a phone
432
417
  host: "localhost",
433
418
 
@@ -435,8 +420,8 @@ export default (
435
420
  // folder VBlocks runs in
436
421
  static: false,
437
422
 
438
- // Print the URL once, as the result of serve. The startup lines of
439
- // the dev server stay hidden, see infrastructureLogging
423
+ // Print the URL once, as the result of serve. At the `warn` log
424
+ // level, the dev server prints no startup lines
440
425
  onListening: developmentServer => {
441
426
  const address = developmentServer.server?.address()
442
427
 
@@ -465,8 +450,8 @@ export default (
465
450
  new HtmlWebPackPlugin({
466
451
  template: paths.htmlTemplate,
467
452
  favicon: paths.favicon,
468
- // An inline script ignores `defer` and runs where it stands, so it
469
- // must stand after the element the app renders into
453
+ // An inline script ignores `defer` and runs once the parser reaches
454
+ // it. It must come after the element the app renders into
470
455
  inject: isSingle ? "body" : "head",
471
456
  }),
472
457
 
@@ -515,14 +500,14 @@ export default (
515
500
  },
516
501
 
517
502
  optimization: {
518
- // Enable tree shaking for unused exports
503
+ // Mark unused exports, so the minifier drops them
519
504
  usedExports: true,
520
505
 
521
506
  // Merge runtime.js into main.js for fewer HTTP requests
522
507
  runtimeChunk: false,
523
508
 
524
- // Split node_modules into the react and vendors chunks, so a new app
525
- // build keeps their cache
509
+ // Split node_modules into the react and vendors chunks, so the browser
510
+ // keeps them cached across builds of the app
526
511
  splitChunks: !isSingle && {
527
512
  chunks: "all",
528
513
  cacheGroups: {
@@ -545,6 +530,10 @@ export default (
545
530
  performance: {
546
531
  // A standalone file is over the size limit by design
547
532
  hints: isProduction && !isSingle ? "warning" : false,
533
+ // React and react-dom alone are over the 244 KiB default. Vite warns
534
+ // at 500 kB
535
+ maxAssetSize: 500 * 1000,
536
+ maxEntrypointSize: 500 * 1000,
548
537
  },
549
538
  }
550
539
  }