Skip to content

Commit 5186a77

Browse files
committed
fix(@angular/build): show error when Node.js built-ins are used during ng serve
This commit ensures consistent behavior between `ng build` and `ng serve`. Previously, `ng serve` did not display an error message when Node.js built-in modules were included in browser bundles. By default, Vite replaces Node.js built-ins with empty modules, which can lead to unexpected runtime issues. This update addresses the problem by surfacing clear error messages, providing better developer feedback and alignment between the two commands. Closes: #27425
1 parent 75998eb commit 5186a77

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

packages/angular/build/src/builders/dev-server/vite-server.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -803,6 +803,26 @@ function getDepOptimizationConfig({
803803
thirdPartySourcemaps: boolean;
804804
}): DepOptimizationConfig {
805805
const plugins: ViteEsBuildPlugin[] = [
806+
{
807+
name: 'angular-browser-node-built-in',
808+
setup(build) {
809+
// This namespace is configured by vite.
810+
// @see: https://github.com/vitejs/vite/blob/a1dd396da856401a12c921d0cd2c4e97cb63f1b5/packages/vite/src/node/optimizer/esbuildDepPlugin.ts#L109
811+
build.onLoad({ filter: /.*/, namespace: 'browser-external' }, (args) => {
812+
if (!isBuiltin(args.path)) {
813+
return;
814+
}
815+
816+
return {
817+
errors: [
818+
{
819+
text: `The package "${args.path}" wasn't found on the file system but is built into node.`,
820+
},
821+
],
822+
};
823+
});
824+
},
825+
},
806826
{
807827
name: `angular-vite-optimize-deps${ssr ? '-ssr' : ''}${
808828
thirdPartySourcemaps ? '-vendor-sourcemap' : ''
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import assert from 'node:assert';
2+
import { execAndWaitForOutputToMatch, ng } from '../../utils/process';
3+
import { writeFile } from '../../utils/fs';
4+
5+
export default async function () {
6+
await ng('cache', 'clean');
7+
await ng('cache', 'on');
8+
9+
// The `@angular/cli` package relies on Node.js dependencies and is not designed for use in a browser environment.
10+
await writeFile('src/main.ts', `import '@angular/cli';`);
11+
12+
const { stderr } = await execAndWaitForOutputToMatch('ng', ['serve', '--port=0'], /ERROR/, {
13+
CI: '0',
14+
NO_COLOR: 'true',
15+
});
16+
17+
assert.match(
18+
stderr,
19+
/The package "node:util" wasn't found on the file system but is built into node/,
20+
);
21+
}

0 commit comments

Comments
 (0)