@asd14/vblocks 5.0.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/bin/vblocks.sh CHANGED
@@ -279,13 +279,13 @@ snapshot_folder() {
279
279
  done
280
280
  }
281
281
 
282
- # print_changes <before-snapshot> <after-snapshot> <app-subdir>
282
+ # print_snapshot_diff <before-snapshot> <after-snapshot> <app-subdir>
283
283
  #
284
284
  # Print "add", "update" or "drop" for each file that differs between two
285
285
  # snapshots of the project folder. A path inside <app-subdir> prints as
286
286
  # $APP_DIR/..., the rest as $PROJECT_DIR/... <app-subdir> is "." when the app
287
287
  # is the project folder, empty when there is no app.
288
- print_changes() {
288
+ print_snapshot_diff() {
289
289
  # Every snapshot line has a tab. The AFTER line has none, so it marks where
290
290
  # the second snapshot starts
291
291
  {
@@ -596,7 +596,7 @@ case "$COMMAND" in
596
596
  AFTER_SNAPSHOT=$(snapshot_folder "$PROJECT_DIR")
597
597
 
598
598
  print_init_summary "$PARTS" "$TEMPLATE" "$PROJECT_DIR" "$APP_DIR"
599
- print_changes "$BEFORE_SNAPSHOT" "$AFTER_SNAPSHOT" "$APP_SUBDIR"
599
+ print_snapshot_diff "$BEFORE_SNAPSHOT" "$AFTER_SNAPSHOT" "$APP_SUBDIR"
600
600
 
601
601
  case "$PARTS" in
602
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": "5.0.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,9 +215,9 @@ 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
152
223
  * @property {"error"|"warn"|"info"|"verbose"} [logLevel] - How much Webpack and its dev server print
@@ -183,7 +254,7 @@ export default (
183
254
  const isAnalyze = Boolean(analyze) && isServe
184
255
  const hasReactRefresh = isServe && mode === "development"
185
256
  const swcConfig = loadSwcConfig({ hasReactRefresh })
186
- const commonPostCSSConfigs = createCssModuleConfig(isProduction)
257
+ const cssModuleOptions = getCssModuleOptions(isProduction)
187
258
 
188
259
  const paths = {
189
260
  appEntry: `${entryDir}/src/index.tsx`,
@@ -196,9 +267,8 @@ export default (
196
267
  }
197
268
 
198
269
  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.
270
+ // The global CSS comes first, so component styles load after it and win
271
+ // ties
202
272
  entry: [
203
273
  ...(fs.existsSync(paths.globalCssEntry) ? [paths.globalCssEntry] : []),
204
274
  paths.appEntry,
@@ -206,6 +276,10 @@ export default (
206
276
 
207
277
  mode: mode,
208
278
 
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
+
209
283
  // Keep the summary of VBlocks on screen. `--log-level` sets it, `--stats`
210
284
  // overrides it
211
285
  stats: STATS_BY_LOG_LEVEL[logLevel],
@@ -214,16 +288,17 @@ export default (
214
288
  // A standalone file opens from disk, where "/" is the filesystem root
215
289
  publicPath: isSingle ? "" : "/",
216
290
  path: paths.output,
217
- // Cannot use 'contenthash' when hot reloading is enabled.
291
+ // Hot reloading breaks on `[contenthash]` names, so serve leaves out the
292
+ // hash
218
293
  filename: isServe ? "js/[name].js" : "js/[name].[contenthash].js",
219
- // Delete existing files in the output directory before building
294
+ // Empty the output folder before each build
220
295
  clean: true,
221
296
  },
222
297
 
223
298
  devtool: isServe ? "eval-source-map" : false,
224
299
 
225
- // Both Webpack and SWC should use the same browserslist configuration
226
- // with .swcrc as source of truth
300
+ // Webpack builds for the browser targets of the SWC config, so both tools
301
+ // agree
227
302
  target: `browserslist:${swcConfig.env.targets}`,
228
303
 
229
304
  module: {
@@ -253,7 +328,7 @@ export default (
253
328
  {
254
329
  loader: "css-loader",
255
330
  options: {
256
- // Enable/disable @import resolving.
331
+ // Resolve @import in CSS files
257
332
  import: true,
258
333
 
259
334
  // Apply "postcss-loader" on imported css files before
@@ -261,7 +336,7 @@ export default (
261
336
  importLoaders: 1,
262
337
 
263
338
  modules: {
264
- ...commonPostCSSConfigs,
339
+ ...cssModuleOptions,
265
340
  mode: "local",
266
341
  },
267
342
  },
@@ -270,7 +345,7 @@ export default (
270
345
  loader: "postcss-loader",
271
346
  options: {
272
347
  postcssOptions: {
273
- config: VB_POSTCONFIG_PATH,
348
+ config: VB_POSTCSS_CONFIG,
274
349
  },
275
350
  },
276
351
  },
@@ -286,7 +361,7 @@ export default (
286
361
  {
287
362
  loader: "css-loader",
288
363
  options: {
289
- // Enable/disable @import resolving.
364
+ // Resolve @import in CSS files
290
365
  import: true,
291
366
 
292
367
  // Apply "postcss-loader" on imported css files before
@@ -294,7 +369,7 @@ export default (
294
369
  importLoaders: 1,
295
370
 
296
371
  modules: {
297
- ...commonPostCSSConfigs,
372
+ ...cssModuleOptions,
298
373
  mode: "global",
299
374
  },
300
375
  },
@@ -303,7 +378,7 @@ export default (
303
378
  loader: "postcss-loader",
304
379
  options: {
305
380
  postcssOptions: {
306
- config: VB_POSTCONFIG_PATH,
381
+ config: VB_POSTCSS_CONFIG,
307
382
  },
308
383
  },
309
384
  },
@@ -340,16 +415,16 @@ export default (
340
415
  devServer: isServe
341
416
  ? {
342
417
  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.
418
+ // Serve index.html in place of a 404, so the router of the app handles
419
+ // every path
345
420
  historyApiFallback: true,
346
421
 
347
- // Hot Module Replacement (HMR) exchanges, adds, or removes modules
348
- // 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
349
424
  // https://webpack.js.org/concepts/hot-module-replacement/
350
425
  hot: true,
351
426
 
352
- // Tells dev-server to open the browser after server had been started.
427
+ // Open the browser once the server starts
353
428
  open: true,
354
429
 
355
430
  // Only this machine opens the page. `--host 0.0.0.0` exposes it to
@@ -369,12 +444,10 @@ export default (
369
444
  if (typeof address !== "object" || address === null) return
370
445
 
371
446
  const { port } = address
372
- process.stdout.write(`Local: http://localhost:${port}\n`)
447
+ log("serve", `http://localhost:${port}`)
373
448
 
374
449
  if (developmentServer.options.host !== "localhost") {
375
- process.stdout.write(
376
- `Network: ${developmentServer.options.host}:${port}\n`
377
- )
450
+ log("expose", `${developmentServer.options.host}:${port}`)
378
451
  }
379
452
  },
380
453
 
@@ -417,11 +490,13 @@ export default (
417
490
  ],
418
491
  }),
419
492
 
420
- // A dynamic `import()` would otherwise emit a second file
493
+ // Without it, Webpack emits a second file for each dynamic `import()`
421
494
  isSingle && new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }),
422
495
 
423
496
  isSingle && inlineAssets,
424
497
 
498
+ isServe && reportFileEvents(entryDir),
499
+
425
500
  isAnalyze &&
426
501
  new BundleAnalyzerPlugin({
427
502
  openAnalyzer: false,
@@ -443,10 +518,11 @@ export default (
443
518
  // Enable tree shaking for unused exports
444
519
  usedExports: true,
445
520
 
446
- // Merge runtime.js into main.js for fewer HTTP request
521
+ // Merge runtime.js into main.js for fewer HTTP requests
447
522
  runtimeChunk: false,
448
523
 
449
- // 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
450
526
  splitChunks: !isSingle && {
451
527
  chunks: "all",
452
528
  cacheGroups: {