Skip to content

Commit c63773f

Browse files
authored
feat(dev): add STRICT_PORT environment variable for port availability check (#12921)
1 parent 95872bd commit c63773f

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

docs/docs/docs/guides/env-variables.en-US.md

+8
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,14 @@ Specifies the socket server for HMR. For example:
157157
$ SOCKET_SERVER=http://localhost:8000/ umi dev
158158
```
159159

160+
### STRICT_PORT
161+
162+
If set, when the port is occupied, it will prompt the user to use another port and exit the process.
163+
164+
```bash
165+
$ STRICT_PORT=8000 umi dev
166+
```
167+
160168
### SPEED_MEASURE
161169

162170
Analyzes the Webpack compile time, supports `CONSOLE` and `JSON` formats, the default is `CONSOLE`.

docs/docs/docs/guides/env-variables.md

+8
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,14 @@ $ ANALYZE=1 umi build
156156
$ SOCKET_SERVER=http://localhost:8000/ umi dev
157157
```
158158

159+
### STRICT_PORT
160+
161+
如果设置,当端口被占用时,会提示用户使用其他端口,并退出进程。
162+
163+
```bash
164+
$ STRICT_PORT=8000 umi dev
165+
```
166+
159167
### SPEED_MEASURE
160168

161169
分析 Webpack 编译时间,支持 `CONSOLE``JSON` 两种格式,默认是 `CONSOLE`

packages/preset-umi/src/commands/dev/dev.ts

+26
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,24 @@ PORT=8888 umi dev
7878
// clear tmp
7979
rimraf.sync(api.paths.absTmpPath);
8080

81+
// check strict port
82+
if (process.env.STRICT_PORT) {
83+
logger.info(
84+
`Checking port ${process.env.STRICT_PORT} since STRICT_PORT is set...`,
85+
);
86+
const port = parseInt(String(process.env.STRICT_PORT), 10);
87+
const isPortAvailableResult = await isPortAvailable(port);
88+
if (!isPortAvailableResult) {
89+
logger.error(
90+
`Port ${port} is not available, please use another port.`,
91+
);
92+
logger.info(
93+
`If you don't want to exit when the port is not available, use PORT instead.`,
94+
);
95+
process.exit(1);
96+
}
97+
}
98+
8199
// check package.json
82100
await api.applyPlugins({
83101
key: 'onCheckPkgJSON',
@@ -488,3 +506,11 @@ PORT=8888 umi dev
488506
return viteConfig;
489507
});
490508
};
509+
510+
async function isPortAvailable(port: number) {
511+
const foundPort = await portfinder.getPortPromise({
512+
port,
513+
});
514+
return foundPort === port;
515+
}
516+

0 commit comments

Comments
 (0)