Skip to content

Commit 5b8e2d5

Browse files
committed
fix(@angular-devkit/build-angular): ensure port 0 uses random port with Vite development server
Vite appears to consider a port value of `0` as a falsy value and use the default Vite port of `5173` when zero is used as a value for the development server port option. To workaround this issue, the port checker code now explicitly handles the zero value case and determines a random port as would be done automatically by the Webpack-based development server.
1 parent 204794c commit 5b8e2d5

File tree

2 files changed

+23
-7
lines changed

2 files changed

+23
-7
lines changed

packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/port_spec.ts

+5
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,11 @@ describeServeBuilder(
7171
expect(result?.success).toBeTrue();
7272
const port = getResultPort(result);
7373
expect(port).not.toBe('4200');
74+
if (isViteRun) {
75+
// Should not be default Vite port either
76+
expect(port).not.toBe('5173');
77+
}
78+
7479
expect(port).toMatch(/\d{4,6}/);
7580
expect(await response?.text()).toContain('<title>');
7681

packages/angular_devkit/build_angular/src/utils/check-port.ts

+18-7
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
* found in the LICENSE file at https://angular.io/license
77
*/
88

9-
import * as net from 'net';
9+
import assert from 'node:assert';
10+
import { AddressInfo, createServer } from 'node:net';
1011
import { loadEsmModule } from './load-esm';
1112
import { isTTY } from './tty';
1213

@@ -15,12 +16,14 @@ function createInUseError(port: number): Error {
1516
}
1617

1718
export async function checkPort(port: number, host: string): Promise<number> {
18-
if (port === 0) {
19-
return 0;
20-
}
19+
// Disabled due to Vite not handling port 0 and instead always using the default value (5173)
20+
// TODO: Enable this again once Vite is fixed
21+
// if (port === 0) {
22+
// return 0;
23+
// }
2124

2225
return new Promise<number>((resolve, reject) => {
23-
const server = net.createServer();
26+
const server = createServer();
2427

2528
server
2629
.once('error', (err: NodeJS.ErrnoException) => {
@@ -46,13 +49,21 @@ export async function checkPort(port: number, host: string): Promise<number> {
4649
}),
4750
)
4851
.then(
49-
(answers) => (answers.useDifferent ? resolve(0) : reject(createInUseError(port))),
52+
(answers) =>
53+
answers.useDifferent ? resolve(checkPort(0, host)) : reject(createInUseError(port)),
5054
() => reject(createInUseError(port)),
5155
);
5256
})
5357
.once('listening', () => {
58+
// Get the actual address from the listening server instance
59+
const address = server.address();
60+
assert(
61+
address && typeof address !== 'string',
62+
'Port check server address should always be an object.',
63+
);
64+
5465
server.close();
55-
resolve(port);
66+
resolve(address.port);
5667
})
5768
.listen(port, host);
5869
});

0 commit comments

Comments
 (0)