Skip to content

Commit

Permalink
fix(@angular-devkit/build-angular): ensure all build resources are se…
Browse files Browse the repository at this point in the history
…rved in esbuild dev server

Previously when using the esbuild-based browser application builder with the new dev server,
resource files referenced via stylesheets may not have been served by the development server.
The development server has now been adjusted to properly prioritize and serve files that were
generated during the build process.
Global stylesheets are also currently considered resource files as well to workaround issues
with development sourcemaps within the development server itself. Global stylesheets are already
fully processed by the build system prior to being passed to the development server.

(cherry picked from commit 26c67f9)
  • Loading branch information
clydin authored and dgp1130 committed Apr 12, 2023
1 parent 42b9de6 commit ff8a89c
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 15 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@
"loader-utils": "3.2.1",
"magic-string": "0.30.0",
"mini-css-extract-plugin": "2.7.5",
"mrmime": "1.0.1",
"ng-packagr": "16.0.0-next.2",
"node-fetch": "^2.2.0",
"npm": "^8.11.0",
Expand Down
1 change: 1 addition & 0 deletions packages/angular_devkit/build_angular/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ ts_library(
"@npm//loader-utils",
"@npm//magic-string",
"@npm//mini-css-extract-plugin",
"@npm//mrmime",
"@npm//ng-packagr",
"@npm//open",
"@npm//ora",
Expand Down
1 change: 1 addition & 0 deletions packages/angular_devkit/build_angular/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"loader-utils": "3.2.1",
"magic-string": "0.30.0",
"mini-css-extract-plugin": "2.7.5",
"mrmime": "1.0.1",
"open": "8.4.2",
"ora": "5.4.1",
"parse5-html-rewriting-stream": "7.0.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import type { BuilderContext } from '@angular-devkit/architect';
import type { json } from '@angular-devkit/core';
import { lookup as lookupMimeType } from 'mrmime';
import assert from 'node:assert';
import { BinaryLike, createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
Expand All @@ -21,7 +22,7 @@ import type { NormalizedDevServerOptions } from './options';
import type { DevServerBuilderOutput } from './webpack-server';

interface OutputFileRecord {
text: string;
contents: Uint8Array;
size: number;
hash?: Buffer;
updated: boolean;
Expand Down Expand Up @@ -69,7 +70,7 @@ export async function* serveWithVite(
// Skip analysis of sourcemaps
if (filePath.endsWith('.map')) {
outputFiles.set(filePath, {
text: file.text,
contents: file.contents,
size: file.contents.byteLength,
updated: false,
});
Expand All @@ -82,7 +83,7 @@ export async function* serveWithVite(
if (existingRecord && existingRecord.size === file.contents.byteLength) {
// Only hash existing file when needed
if (existingRecord.hash === undefined) {
existingRecord.hash = hashContent(existingRecord.text);
existingRecord.hash = hashContent(existingRecord.contents);
}

// Compare against latest result output
Expand All @@ -95,7 +96,7 @@ export async function* serveWithVite(
}

outputFiles.set(filePath, {
text: file.text,
contents: file.contents,
size: file.contents.byteLength,
hash: fileHash,
updated: true,
Expand Down Expand Up @@ -213,25 +214,59 @@ async function setupServer(
},
load(id) {
const [file] = id.split('?', 1);
const code = outputFiles.get(file)?.text;
const code = outputFiles.get(file)?.contents;
const map = outputFiles.get(file + '.map')?.contents;

return (
code && {
code,
map: outputFiles.get(file + '.map')?.text,
code: code && Buffer.from(code).toString('utf-8'),
map: map && Buffer.from(map).toString('utf-8'),
}
);
},
configureServer(server) {
// Assets get handled first
// Assets and resources get handled first
server.middlewares.use(function angularAssetsMiddleware(req, res, next) {
if (req.url) {
// Rewrite all build assets to a vite raw fs URL
const assetSource = assets.get(req.url);
if (assetSource !== undefined) {
req.url = `/@fs/${assetSource}`;
if (req.url === undefined || res.writableEnded) {
return;
}

// Parse the incoming request.
// The base of the URL is unused but required to parse the URL.
const parsedUrl = new URL(req.url, 'http://localhost');
const extension = path.extname(parsedUrl.pathname);

// Rewrite all build assets to a vite raw fs URL
const assetSourcePath = assets.get(parsedUrl.pathname);
if (assetSourcePath !== undefined) {
req.url = `/@fs/${assetSourcePath}`;
next();

return;
}

// Resource files are handled directly.
// Global stylesheets (CSS files) are currently considered resources to workaround
// dev server sourcemap issues with stylesheets.
if (extension !== '.js' && extension !== '.html') {
const outputFile = outputFiles.get(parsedUrl.pathname);
if (outputFile) {
const mimeType = lookupMimeType(extension);
if (mimeType) {
res.setHeader('Content-Type', mimeType);
}
res.setHeader('Cache-Control', 'no-cache');
if (serverOptions.headers) {
Object.entries(serverOptions.headers).forEach(([name, value]) =>
res.setHeader(name, value),
);
}
res.end(outputFile.contents);

return;
}
}

next();
});

Expand All @@ -240,10 +275,14 @@ async function setupServer(
return () =>
server.middlewares.use(function angularIndexMiddleware(req, res, next) {
if (req.url === '/' || req.url === `/index.html`) {
const rawHtml = outputFiles.get('/index.html')?.text;
const rawHtml = outputFiles.get('/index.html')?.contents;
if (rawHtml) {
server
.transformIndexHtml(req.url, rawHtml, req.originalUrl)
.transformIndexHtml(
req.url,
Buffer.from(rawHtml).toString('utf-8'),
req.originalUrl,
)
.then((processedHtml) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('Cache-Control', 'no-cache');
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -8617,6 +8617,11 @@ mkdirp@^0.5.1, mkdirp@^0.5.5, mkdirp@~0.5.1:
dependencies:
minimist "^1.2.6"

[email protected]:
version "1.0.1"
resolved "https://registry.yarnpkg.com/mrmime/-/mrmime-1.0.1.tgz#5f90c825fad4bdd41dc914eff5d1a8cfdaf24f27"
integrity sha512-hzzEagAgDyoU1Q6yg5uI+AorQgdvMCur3FcKf7NhMKWsaYg+RnbTyHRa/9IlLF9rf455MOCtcqqrQQ83pPP7Uw==

[email protected]:
version "2.0.0"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"
Expand Down

0 comments on commit ff8a89c

Please sign in to comment.