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

fix(plugin-compiler-web): 修复 web 服务启动的端口号冲突检测逻辑并调整最大检测次数为 5 次 #95

Merged
merged 2 commits into from
Aug 8, 2023
Merged
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
59 changes: 34 additions & 25 deletions packages/plugin-compiler-web/src/plugins/devServerPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const DEFAULT_PORT = 8080
const DEFAULT_HOST = '0.0.0.0'

/**
* 尝试获取可用的端口号,最多重复获取 3
* 尝试获取可用的端口号,最多重复获取 5
* @param port - 端口号
* @param host - ip 地址
* @param retryTimes - 当前重试次数
Expand Down Expand Up @@ -52,8 +52,8 @@ async function checkPortInUseAndReturnAvaliable(
server.listen(availablePort, host)
})

// 重试 3
if (!res && retryTimes < 3) {
// 重试 5
if (!res && retryTimes < 5) {
return checkPortInUseAndReturnAvaliable(
availablePort + 1,
host,
Expand Down Expand Up @@ -82,38 +82,47 @@ export class DevServerPlugin implements Plugin {
wrapper: WebpackWrapper,
userConfig: WebCompilerUserConfig
) {
const { srcPaths = [], web } = userConfig as {
const {
srcPaths = [],
web,
watch
} = userConfig as {
watch: boolean
outputPath: string[]
srcPaths: string[]
ignore: string[]
} & WebCompilerUserConfig
const { devServer = {} } = web || {}
const host = devServer.host || runner.config.env.get('HOST') || DEFAULT_HOST
let port = devServer.port || runner.config.env.get('PORT') || DEFAULT_PORT
// 获取可用 port
const availablePort = await checkPortInUseAndReturnAvaliable(port, host)
if (String(availablePort) !== String(port)) {
const answers = await prompts(
[

// 仅在监听模式下检测端口冲突
if (watch) {
// 获取可用 port
const availablePort = await checkPortInUseAndReturnAvaliable(port, host)
if (String(availablePort) !== String(port)) {
const answers = await prompts(
[
{
type: 'select',
name: 'suggestedPortAccepted',
message: `端口 ${port} 已被占用,使用 ${availablePort} 端口启动?`,
choices: [
{ title: '是', value: true },
{ title: '否', value: false }
]
}
],
{
type: 'select',
name: 'suggestedPortAccepted',
message: `端口 ${port} 已被占用,使用 ${availablePort} 端口启动?`,
choices: [
{ title: '是', value: true },
{ title: '否', value: false }
]
}
],
{
onCancel() {
process.exit(0)
onCancel() {
process.exit(0)
}
}
}
)
)

if (answers.suggestedPortAccepted) {
port = availablePort
if (answers.suggestedPortAccepted) {
port = availablePort
}
}
}

Expand Down