vite-plugin-auto-port
v1.0.0
Published
A Vite plugin that automatically finds and uses the next available port when the default port is occupied
Downloads
7
Maintainers
Readme
vite-plugin-auto-port
一个当指定端口被占用时,自动查找并使用下一个可用端口的 Vite 插件
为什么需要这个插件?
虽然 Vite 官方配置中有 strictPort: false 选项,但在某些环境下可能无法正常工作。此插件通过在配置阶段主动检测端口占用情况,提供更可靠的端口自动切换功能。
特性
- ✅ 可靠的端口检测:在 Vite 启动前主动检测端口占用
- ✅ 自动递增:端口被占用时自动尝试下一个端口
- ✅ 友好提示:清晰的控制台输出,告知端口切换情况
- ✅ TypeScript 支持:完整的类型定义
- ✅ 零配置:开箱即用,也支持自定义配置
- ✅ 轻量级:无额外依赖,仅使用 Node.js 原生模块
安装
npm install vite-plugin-auto-port --save-dev或使用 yarn:
yarn add vite-plugin-auto-port -D或使用 pnpm:
pnpm add vite-plugin-auto-port -D使用方法
基础用法
在你的 vite.config.js 或 vite.config.ts 中:
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import autoPortPlugin from 'vite-plugin-auto-port';
export default defineConfig({
plugins: [
autoPortPlugin(), // 默认从 3000 端口开始
vue(),
],
});自定义配置
import { defineConfig } from 'vite';
import autoPortPlugin from 'vite-plugin-auto-port';
export default defineConfig({
plugins: [
autoPortPlugin({
port: 8080, // 起始端口,默认 3000
maxAttempts: 20, // 最大尝试次数,默认 10
silent: false, // 是否静默模式,默认 false
}),
],
});配置选项
| 选项 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| port | number | 3000 | 起始端口号 |
| maxAttempts | number | 10 | 最大尝试次数(会尝试 port 到 port+maxAttempts-1) |
| silent | boolean | false | 是否静默模式(不输出端口切换日志) |
示例输出
当端口 8080 被占用时:
[vite-plugin-auto-port] 端口 8080 被占用,尝试下一个...
✅ [vite-plugin-auto-port] 自动切换端口:8080 -> 8081
VITE v4.5.0 ready in 285 ms
➜ Local: http://localhost:8081/
➜ Network: http://192.168.1.100:8081/实际应用场景
场景 1:多项目并行开发
当你需要同时运行多个 Vite 项目时,无需手动修改端口配置:
// 项目 A、B、C 都使用相同配置
export default defineConfig({
plugins: [autoPortPlugin({ port: 3000 })],
});启动结果:
- 项目 A:http://localhost:3000
- 项目 B:http://localhost:3001
- 项目 C:http://localhost:3002
场景 2:CI/CD 环境
在持续集成环境中,避免端口冲突导致的构建失败。
兼容性
- ✅ Vite 2.x
- ✅ Vite 3.x
- ✅ Vite 4.x
- ✅ Vite 5.x
- ✅ Vite 6.x
- ✅ Vite 7.x
- ✅ Node.js 14+
常见问题
Q: 这个插件和 strictPort: false 有什么区别?
A: strictPort: false 是 Vite 的原生配置,但在某些环境下可能无法正常工作。此插件通过在配置阶段主动检测端口,提供更可靠的解决方案。
Q: 可以用于生产环境吗?
A: 这个插件主要用于开发环境。生产环境通常不需要动态端口检测。
Q: 如何在静默模式下使用?
A: 设置 silent: true 即可:
autoPortPlugin({ port: 8080, silent: true })贡献
欢迎提交 Issue 和 Pull Request!
开源协议
作者
GongTengXY
更新日志
1.0.0 (2025-11-24)
- 🎉 首次发布
- ✨ 支持自动端口检测和递增
- ✨ 完整的 TypeScript 类型支持
- ✨ 友好的控制台输出
