Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(dev): add STRICT_PORT environment variable for port availability check #12921

Merged
merged 1 commit into from
Feb 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/docs/docs/guides/env-variables.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,14 @@ Specifies the socket server for HMR. For example:
$ SOCKET_SERVER=http://localhost:8000/ umi dev
```

### STRICT_PORT

If set, when the port is occupied, it will prompt the user to use another port and exit the process.

```bash
$ STRICT_PORT=8000 umi dev
```

### SPEED_MEASURE

Analyzes the Webpack compile time, supports `CONSOLE` and `JSON` formats, the default is `CONSOLE`.
Expand Down
8 changes: 8 additions & 0 deletions docs/docs/docs/guides/env-variables.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,14 @@ $ ANALYZE=1 umi build
$ SOCKET_SERVER=http://localhost:8000/ umi dev
```

### STRICT_PORT

如果设置,当端口被占用时,会提示用户使用其他端口,并退出进程。

```bash
$ STRICT_PORT=8000 umi dev
```

### SPEED_MEASURE

分析 Webpack 编译时间,支持 `CONSOLE` 和 `JSON` 两种格式,默认是 `CONSOLE`。
Expand Down
26 changes: 26 additions & 0 deletions packages/preset-umi/src/commands/dev/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,24 @@ PORT=8888 umi dev
// clear tmp
rimraf.sync(api.paths.absTmpPath);

// check strict port
if (process.env.STRICT_PORT) {
logger.info(
`Checking port ${process.env.STRICT_PORT} since STRICT_PORT is set...`,
);
const port = parseInt(String(process.env.STRICT_PORT), 10);
const isPortAvailableResult = await isPortAvailable(port);
if (!isPortAvailableResult) {
logger.error(
`Port ${port} is not available, please use another port.`,
);
logger.info(
`If you don't want to exit when the port is not available, use PORT instead.`,
);
process.exit(1);
}
}

// check package.json
await api.applyPlugins({
key: 'onCheckPkgJSON',
Expand Down Expand Up @@ -488,3 +506,11 @@ PORT=8888 umi dev
return viteConfig;
});
};

async function isPortAvailable(port: number) {
const foundPort = await portfinder.getPortPromise({
port,
});
return foundPort === port;
}