Skip to content

Commit

Permalink
feat(dev): add STRICT_PORT environment variable for port availability…
Browse files Browse the repository at this point in the history
… check (#12921)
  • Loading branch information
sorrycc authored Feb 14, 2025
1 parent 95872bd commit c63773f
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
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;
}

0 comments on commit c63773f

Please sign in to comment.