Skip to content

Commit

Permalink
fix(@angular/build): show error when Node.js built-ins are used durin…
Browse files Browse the repository at this point in the history
…g `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
  • Loading branch information
alan-agius4 committed Dec 5, 2024
1 parent 75998eb commit a26f6b6
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
19 changes: 19 additions & 0 deletions packages/angular/build/src/builders/dev-server/vite-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -803,6 +803,25 @@ function getDepOptimizationConfig({
thirdPartySourcemaps: boolean;
}): DepOptimizationConfig {
const plugins: ViteEsBuildPlugin[] = [
{
name: 'angular-browser-node-built-in',
setup(build) {
// This namespace is configured by vite.
build.onLoad({ filter: /.*/, namespace: 'browser-external' }, (args) => {
if (!isBuiltin(args.path)) {
return;
}

return {
errors: [
{
text: `The package "${args.path}" wasn't found on the file system but is built into node.`,
},
],
};
});
},
},
{
name: `angular-vite-optimize-deps${ssr ? '-ssr' : ''}${
thirdPartySourcemaps ? '-vendor-sourcemap' : ''
Expand Down
19 changes: 19 additions & 0 deletions tests/legacy-cli/e2e/tests/vite/browser-node-module-dep-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import assert from 'node:assert';
import { execAndWaitForOutputToMatch, ng } from '../../utils/process';
import { installPackage } from '../../utils/packages';
import { writeFile } from '../../utils/fs';

export default async function () {
await ng('cache', 'clean');
await ng('cache', 'on');

await installPackage('express@4');
await writeFile('src/main.ts', `import 'express';`);

const { stderr } = await execAndWaitForOutputToMatch('ng', ['serve', '--port=0'], /ERROR/, {
CI: '0',
NO_COLOR: 'true',
});

assert.match(stderr, /The package "http" wasn't found on the file system but is built into node/);
}

0 comments on commit a26f6b6

Please sign in to comment.