vue.config.js 配置// vue.config.js
module.exports = {
devServer: {
port: 8081, // 修改端口号
host: '0.0.0.0', // 可选的,允许外部访问
open: true, // 自动打开浏览器
https: false, // 是否使用 HTTPS
// 其他配置...
}
}
# 启动时指定端口
npm run serve -- --port 8081
# 或使用 yarn
yarn serve --port 8081
# 同时指定主机
npm run serve -- --port 8081 --host 0.0.0.0
.env 文件中配置# .env.development
PORT=8081
HOST=0.0.0.0
package.json 中设置{
"scripts": {
"serve": "vue-cli-service serve --port 8081",
"serve:dev": "vue-cli-service serve --port 3000"
}
}
vue.config.js 配置示例module.exports = {
devServer: {
port: 8081, // 端口号
host: '0.0.0.0', // 主机地址
open: true, // 启动后自动打开浏览器
https: false, // 是否启用 https
hot: true, // 启用热更新
compress: true, // 启用 gzip 压缩
// 代理配置(解决跨域)
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
// 自定义中间件
onBeforeSetupMiddleware: (devServer) => {
if (!devServer) {
throw new Error('webpack-dev-server is not defined');
}
// 添加自定义中间件
},
// 客户端配置
client: {
overlay: {
warnings: true,
errors: true
}
}
}
}
// vue.config.js
module.exports = {
devServer: {
port: 8081,
// 如果端口被占用,自动尝试下一个端口
open: false // 建议关闭自动打开,避免重复打开
}
}
# 查看端口占用情况
netstat -ano | findstr :8080 # Windows
lsof -i :8080 # Mac/Linux
# 杀死占用进程
taskkill /PID <进程ID> /F # Windows
kill -9 <进程ID> # Mac/Linux
// vue.config.js
const port = process.env.port || process.env.npm_config_port || 8080
module.exports = {
devServer: {
port: port,
// 根据环境变量配置
...(process.env.NODE_ENV === 'production'
? {
// 生产环境配置
}
: {
// 开发环境配置
}
)
}
}
选择适合你项目需求的方式配置即可,推荐使用 vue.config.js 文件进行统一管理。