const { execSync } = require('child_process')

/**
 * 获取可用端口号,如果当前端口号已被占用,则自增,直到找到可用端口号为止
 */
const getAvailablePort = port => {
  let targetPort = port
  while (true && targetPort < 9000) {
    try {
      execSync(`netstat -aon | findStr "127.0.0.1:${targetPort}"`)
      targetPort++
    } catch (e) {
      return targetPort
    }
  }
}

用法:

// xx.config.js
module.exports = {
  devServer: {
    port: getAvailablePort(8080)
  }
}