Skip to content

Commit 3f28e68

Browse files
committed
fix: address review findings
- fail a build whose prerendered pages did not pass through the wrapper - report routes ending in 'index' and colliding routes as build errors - ng add stops if the build target or a configuration ships an SSR server - ng add detects the default project - engines follow @angular/build 22 - CI: test script for the lowest and latest Angular 22, with two locales and the '/index' error - README: stopgap for Angular 22, comparison with Astro and other frameworks
1 parent 9bc1c07 commit 3f28e68

13 files changed

Lines changed: 411 additions & 106 deletions
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
#!/usr/bin/env bash
2+
# End-to-end test with a fresh Angular app.
3+
#
4+
# Usage: test-angular-app.sh <ng-new-command> <package-tgz> <angular-version-range>
5+
# ng-new-command: command that runs `ng new`, e.g. "npx @angular/cli@22"
6+
# package-tgz: packed @angular-schule/flat-prerender
7+
# angular-version-range: version range for all @angular/* packages, e.g. "^22.0.0" or "~22.0.0"
8+
#
9+
# Checks: ng add refuses outputMode "server", ng add + ng build write flat files
10+
# (also for a second locale), and a route "index" fails with a clear message.
11+
set -euo pipefail
12+
13+
NG_NEW="$1"
14+
TGZ="$2"
15+
RANGE="$3"
16+
APP=test-app
17+
18+
export NG_CLI_ANALYTICS=false
19+
20+
$NG_NEW new "$APP" --defaults --ssr --skip-git --skip-install
21+
cd "$APP"
22+
23+
# Pin all @angular/* packages to the requested range
24+
node -e '
25+
const fs = require("fs");
26+
const pkg = JSON.parse(fs.readFileSync("package.json", "utf8"));
27+
for (const deps of [pkg.dependencies, pkg.devDependencies]) {
28+
for (const name of Object.keys(deps ?? {})) {
29+
if (name.startsWith("@angular/")) deps[name] = process.argv[1];
30+
}
31+
}
32+
fs.writeFileSync("package.json", JSON.stringify(pkg, null, 2));
33+
' "$RANGE"
34+
npm install --no-audit --no-fund
35+
npm install --save-dev --no-audit --no-fund "$TGZ"
36+
NG=./node_modules/.bin/ng
37+
echo "@angular/build $(node -p 'require("@angular/build/package.json").version')"
38+
39+
set_build_option() {
40+
node -e '
41+
const fs = require("fs");
42+
const a = JSON.parse(fs.readFileSync("angular.json", "utf8"));
43+
a.projects["'"$APP"'"].architect.build.options[process.argv[1]] = JSON.parse(process.argv[2]);
44+
fs.writeFileSync("angular.json", JSON.stringify(a, null, 2));
45+
' "$1" "$2"
46+
}
47+
48+
expect_failure() {
49+
local expected="$1"
50+
shift
51+
if "$@" > output.log 2>&1; then
52+
cat output.log
53+
echo "Expected '$*' to fail"
54+
exit 1
55+
fi
56+
if ! grep -q "$expected" output.log; then
57+
cat output.log
58+
echo "Expected output to contain: $expected"
59+
exit 1
60+
fi
61+
echo "Failed as expected: $expected"
62+
}
63+
64+
# ng new --ssr uses outputMode "server", which flat output refuses
65+
expect_failure "ships an Angular SSR server" $NG add @angular-schule/flat-prerender --skip-confirmation
66+
67+
set_build_option outputMode '"static"'
68+
$NG add @angular-schule/flat-prerender --skip-confirmation
69+
70+
cat > src/app/app.routes.ts <<'EOF'
71+
import { Routes } from '@angular/router';
72+
import { App } from './app';
73+
74+
export const routes: Routes = [
75+
{ path: '', component: App },
76+
{ path: 'about', component: App },
77+
{ path: 'blog', component: App },
78+
{ path: 'blog/article', component: App }
79+
];
80+
EOF
81+
82+
$NG build
83+
(cd "dist/$APP/browser" && find . -name '*.html' | sort)
84+
for file in index.html about.html blog.html blog/article.html; do
85+
test -f "dist/$APP/browser/$file" || { echo "Missing $file"; exit 1; }
86+
done
87+
for dir in about blog/article; do
88+
test ! -e "dist/$APP/browser/$dir/index.html" || { echo "Unexpected $dir/index.html"; exit 1; }
89+
done
90+
91+
# Second locale: each locale keeps its start page as index.html
92+
npm install --save-dev --no-audit --no-fund "@angular/localize@$RANGE"
93+
$NG add @angular/localize --skip-confirmation
94+
mkdir -p src/locale
95+
cat > src/locale/messages.de.xlf <<'EOF'
96+
<?xml version="1.0" encoding="UTF-8" ?>
97+
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
98+
<file source-language="en-US" target-language="de" datatype="plaintext" original="ng2.template">
99+
<body></body>
100+
</file>
101+
</xliff>
102+
EOF
103+
node -e '
104+
const fs = require("fs");
105+
const a = JSON.parse(fs.readFileSync("angular.json", "utf8"));
106+
const project = a.projects["'"$APP"'"];
107+
project.i18n = { sourceLocale: "en-US", locales: { de: { translation: "src/locale/messages.de.xlf" } } };
108+
project.architect.build.options.localize = true;
109+
fs.writeFileSync("angular.json", JSON.stringify(a, null, 2));
110+
'
111+
$NG build
112+
(cd "dist/$APP/browser" && find . -name '*.html' | sort)
113+
for locale in en-US de; do
114+
for file in index.html about.html blog.html blog/article.html; do
115+
test -f "dist/$APP/browser/$locale/$file" || { echo "Missing $locale/$file"; exit 1; }
116+
done
117+
test ! -e "dist/$APP/browser/$locale/about/index.html" || { echo "Unexpected $locale/about/index.html"; exit 1; }
118+
done
119+
120+
# A route "index" would overwrite the start page
121+
node -e '
122+
const fs = require("fs");
123+
const file = "src/app/app.routes.ts";
124+
fs.writeFileSync(file, fs.readFileSync(file, "utf8").replace("];", ",\n { path: \"index\", component: App }\n];"));
125+
'
126+
expect_failure "Route '/index' cannot be prerendered" $NG build
127+
128+
echo "Angular $RANGE: flat prerender output successful"

‎.github/workflows/main.yml‎

Lines changed: 17 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -34,23 +34,28 @@ jobs:
3434
path: src/dist
3535
retention-days: 1
3636

37-
# Builds a fresh Angular app with SSG and checks the flat output end to end:
38-
# ng add swaps the builder, ng build writes about.html next to index.html.
39-
# The project is created OUTSIDE the repo so it gets its own node_modules.
37+
# Builds a fresh Angular app with SSG and checks the flat output end to end,
38+
# for the lowest and the latest supported Angular 22 version.
39+
# See .github/scripts/test-angular-app.sh for the checks.
4040
test-angular-versions:
4141
needs: build-and-test
4242
runs-on: ubuntu-latest
43-
env:
44-
NG_CLI_ANALYTICS: 'false'
43+
strategy:
44+
fail-fast: false
45+
matrix:
46+
include:
47+
- cli: '22.0'
48+
range: '~22.0.0'
49+
- cli: '22'
50+
range: '^22.0.0'
51+
name: test-angular (${{ matrix.range }})
4552

4653
steps:
4754
- uses: actions/checkout@v4
4855

4956
- uses: actions/setup-node@v4
5057
with:
5158
node-version: 24
52-
cache: npm
53-
cache-dependency-path: src/package-lock.json
5459

5560
- name: Download build artifact
5661
uses: actions/download-artifact@v4
@@ -62,37 +67,10 @@ jobs:
6267
working-directory: src/dist
6368
run: npm pack --pack-destination /tmp
6469

65-
- name: Test Angular 22
70+
- name: Test Angular ${{ matrix.range }}
6671
run: |
6772
cd /tmp
68-
npx @angular/cli@22 new test-app-22 --defaults --ssr --skip-git
69-
cd test-app-22
70-
npm install --save-dev /tmp/angular-schule-flat-prerender-*.tgz
71-
npx ng add @angular-schule/flat-prerender --skip-confirmation
72-
# ng new --ssr uses outputMode "server", which flat output refuses
73-
if npx ng build; then echo "Expected the build to fail with outputMode server"; exit 1; fi
74-
node -e '
75-
const fs = require("fs");
76-
const a = JSON.parse(fs.readFileSync("angular.json", "utf8"));
77-
a.projects["test-app-22"].architect.build.options.outputMode = "static";
78-
fs.writeFileSync("angular.json", JSON.stringify(a, null, 2));
79-
'
80-
cat > src/app/app.routes.ts <<'EOF'
81-
import { Routes } from '@angular/router';
82-
import { App } from './app';
83-
84-
export const routes: Routes = [
85-
{ path: '', component: App },
86-
{ path: 'about', component: App },
87-
{ path: 'blog/article', component: App }
88-
];
89-
EOF
90-
npx ng build
91-
cd dist/test-app-22/browser
92-
find . -name '*.html' | sort
93-
test -f index.html
94-
test -f about.html
95-
test -f blog/article.html
96-
test ! -e about/index.html
97-
test ! -e blog/article/index.html
98-
echo "Angular 22: flat prerender output successful"
73+
bash "$GITHUB_WORKSPACE/.github/scripts/test-angular-app.sh" \
74+
"npx --yes @angular/cli@${{ matrix.cli }}" \
75+
"$(ls /tmp/angular-schule-flat-prerender-*.tgz)" \
76+
"${{ matrix.range }}"

‎CLAUDE.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,14 +71,16 @@ npm dist-tag add @angular-schule/flat-prerender@X.X.X-rc.X next
7171
## Architecture
7272

7373
1. **Builder** (`src/application/`):
74-
- `builder.ts` - Angular builder entry point, called by `ng build`. Strips `prerenderOutputStyle`, refuses flat output when a server is shipped, then delegates to `buildApplication`.
74+
- `builder.ts` - Angular builder entry point, called by `ng build`. Strips `prerenderOutputStyle`, refuses flat output when a server is shipped, delegates to `buildApplication` and fails a build whose prerendered pages did not go through the wrapper.
75+
- `ships-server.ts` - The rule for "this build ships an SSR server", shared by builder and `ng add`.
7576
- `flat-output.ts` - Wraps the internal `prerenderPages()` of `@angular/build`. `execute-post-bundle.js` reads it from the module's exports object at call time, so replacing the export takes effect for regular and localized builds.
7677
- `schema.json` - Generated, see above.
7778

7879
2. **Schematic** (`src/ng-add.ts`):
7980
- Implements `ng add @angular-schule/flat-prerender`
8081
- Swaps the build target's builder and sets `prerenderOutputStyle: "flat"`
82+
- Stops if the build target or one of its configurations ships an SSR server
8183

8284
### Internal API
8385

84-
`prerenderPages()` in `@angular/build/src/utils/server-rendering/prerender.js` is not public. The builder fails loudly if the module or the export is missing, and `flat-output.spec.ts` checks the call site in `execute-post-bundle.js`. After every `@angular/build` update: run the tests and the CI job that builds a fresh Angular app.
86+
`prerenderPages()` in `@angular/build/src/utils/server-rendering/prerender.js` is not public. The builder fails loudly if the module or the export is missing, and `flat-output.spec.ts` checks the call site in `execute-post-bundle.js`. The package supports Angular 22 only. `.github/scripts/test-angular-app.sh` builds a fresh Angular app (lowest and latest 22.x in CI) and checks `ng add`, flat output for two locales and the `/index` error.

‎README.md‎

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,11 @@
1313
3. [🚀 Quick Start](#quickstart)
1414
4. [⚙️ Installation](#installation)
1515
5. [📦 Options](#options)
16-
6. [🌍 Hosts](#hosts)
17-
7. [🔧 How it works](#how-it-works)
18-
8. [📁 Known limitations](#limitations)
19-
9. [🏁 License](#license)
16+
6. [🔭 Other frameworks](#other-frameworks)
17+
7. [🌍 Hosts](#hosts)
18+
8. [🔧 How it works](#how-it-works)
19+
9. [📁 Known limitations](#limitations)
20+
10. [🏁 License](#license)
2021

2122
<hr>
2223

@@ -30,7 +31,7 @@ With this builder, the same route becomes `blog/my-article.html`.
3031
Hosts like Cloudflare Pages serve that file under `/blog/my-article` directly, with status 200.
3132

3233
This is the option proposed in [angular/angular-cli#29173](https://github.com/angular/angular-cli/issues/29173).
33-
As long as Angular has no built-in option, this builder provides it.
34+
The builder is a stopgap: developed and tested for Angular 22, until Angular has a built-in option and this package is no longer needed.
3435

3536
## ⚠️ Prerequisites <a name="prerequisites"></a>
3637

@@ -47,7 +48,8 @@ ng build
4748

4849
## ⚙️ Installation <a name="installation"></a>
4950

50-
`ng add @angular-schule/flat-prerender` installs the package and changes the build target in your `angular.json`:
51+
`ng add @angular-schule/flat-prerender` installs the package and changes the builder of your build target in `angular.json` and sets `prerenderOutputStyle`.
52+
Your build must already use `"outputMode": "static"`: if the build target (or one of its configurations) ships an SSR server, `ng add` stops and tells you so.
5153

5254
```json
5355
"build": {
@@ -77,6 +79,23 @@ Use `--project` to choose the project in a workspace with several projects.
7779
Parent and child routes live side by side: `blog.html` next to the folder `blog/`.
7880
The start page of each locale (for example with base href `/en/`) stays `index.html`.
7981

82+
A route whose last segment is `index` (`/index`, `/docs/index`) fails the build with a clear message: as `index.html` it would be served under the parent path, and `/index` would overwrite the start page.
83+
84+
## 🔭 Other frameworks <a name="other-frameworks"></a>
85+
86+
Static site generators have offered this choice for a long time. Astro is the closest match:
87+
88+
| Framework | Option | `about/index.html` | `about.html` |
89+
|---|---|---|---|
90+
| **Astro** | `build.format` | `'directory'` (default) | `'file'` |
91+
| Next.js (static export) | `trailingSlash` | `true` | `false` (default) |
92+
| SvelteKit | `trailingSlash` | `'always'` | `'never'` (default) |
93+
| Nuxt 2 | `generate.subFolders` | `true` (default) | `false` |
94+
| Hugo | `uglyURLs` | `false` (default) | `true` |
95+
| **Angular** | – | always | this builder |
96+
97+
Astro's documentation recommends `build.format: 'file'` together with `trailingSlash: 'never'`, which is exactly the combination this builder enables for Angular.
98+
8099
## 🌍 Hosts <a name="hosts"></a>
81100

82101
Measured on **Cloudflare Pages** with a flat build:
@@ -90,16 +109,16 @@ Measured on **Cloudflare Pages** with a flat build:
90109

91110
Old addresses with a trailing slash keep working, they redirect to the address without it.
92111

93-
Other hosts (GitHub Pages, Firebase Hosting, Vercel, Netlify) are listed in the Angular issue as supporting this, some of them behind a setting.
112+
GitHub Pages, Firebase Hosting, Vercel and Netlify are listed in the Angular issue as supporting this, some of them behind a setting.
94113
Check your host before switching.
95114

96115
## 🔧 How it works <a name="how-it-works"></a>
97116

98117
The builder calls `buildApplication` from `@angular/build` and wraps its internal `prerenderPages()` function, which returns the prerendered pages as a record of output paths.
99118
The wrapper renames `foo/index.html` to `foo.html` before anything is written, so the service worker manifest and all later build steps see the final file names.
100119

101-
`prerenderPages()` is internal API.
102-
If a version of `@angular/build` changes it, the build fails with a clear error instead of silently writing `index.html` files.
120+
`prerenderPages()` is internal API, so this package supports Angular 22 only.
121+
After a successful build, the builder checks that the prerendered pages actually went through the wrapper, and fails otherwise.
103122

104123
## 📁 Known limitations <a name="limitations"></a>
105124

‎src/application/builder.ts‎

Lines changed: 39 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/ar
22
import { ApplicationBuilderOptions, buildApplication } from '@angular/build';
33
import * as path from 'path';
44

5-
import { installFlatPrerender } from './flat-output';
5+
import { getPrerenderCalls, installFlatPrerender } from './flat-output';
6+
import { shipsServer } from './ships-server';
67

78
export type PrerenderOutputStyle = 'directory' | 'flat';
89

@@ -26,32 +27,48 @@ export async function* executeBuild(
2627
): AsyncIterable<BuilderOutput> {
2728
const { prerenderOutputStyle = 'directory', ...applicationOptions } = options;
2829

29-
if (prerenderOutputStyle === 'flat') {
30-
// With 'outputMode: "static"' the SSR entry only renders at build time; every other SSR setup ships a server.
31-
const shipsServer =
32-
applicationOptions.outputMode === 'server' ||
33-
(applicationOptions.outputMode === undefined && !!applicationOptions.ssr);
34-
if (shipsServer) {
35-
context.logger.error(
36-
`❌ 'prerenderOutputStyle: "flat"' requires 'outputMode: "static"': ` +
37-
`the Angular SSR server looks up prerendered pages as 'index.html'.`
38-
);
39-
yield { success: false };
30+
if (prerenderOutputStyle !== 'flat') {
31+
yield* buildApplication(applicationOptions, context);
4032

41-
return;
42-
}
33+
return;
34+
}
4335

44-
try {
45-
installFlatPrerender(path.dirname(require.resolve('@angular/build/package.json')));
46-
} catch (e) {
47-
context.logger.error('❌ ' + (e instanceof Error ? e.message : String(e)));
48-
yield { success: false };
36+
if (shipsServer(applicationOptions)) {
37+
context.logger.error(
38+
`❌ 'prerenderOutputStyle: "flat"' requires 'outputMode: "static"': ` +
39+
`the Angular SSR server looks up prerendered pages as 'index.html'.`
40+
);
41+
yield { success: false };
4942

50-
return;
51-
}
43+
return;
44+
}
45+
46+
try {
47+
installFlatPrerender(path.dirname(require.resolve('@angular/build/package.json')));
48+
} catch (e) {
49+
context.logger.error('❌ ' + (e instanceof Error ? e.message : String(e)));
50+
yield { success: false };
51+
52+
return;
5253
}
5354

54-
yield* buildApplication(applicationOptions, context);
55+
// Every successful build must have passed its prerendered pages through the wrapper.
56+
// Otherwise nothing was prerendered, or @angular/build no longer calls the wrapped function.
57+
let callsBefore = getPrerenderCalls();
58+
for await (const result of buildApplication(applicationOptions, context)) {
59+
const calls = getPrerenderCalls();
60+
if (result.success && calls === callsBefore) {
61+
context.logger.error(
62+
`❌ 'prerenderOutputStyle: "flat"' had no effect: no pages were prerendered through @angular-schule/flat-prerender. ` +
63+
`Check that prerendering is enabled ('outputMode: "static"' with server routes, or 'prerender'). ` +
64+
`If it is, this version of @angular/build is not supported.`
65+
);
66+
yield { ...result, success: false };
67+
} else {
68+
yield result;
69+
}
70+
callsBefore = calls;
71+
}
5572
}
5673

5774
export default createBuilder<Schema>(executeBuild);

0 commit comments

Comments
 (0)