重庆市文章资讯

vue配置修改端口方式

2026-04-07 12:53:02 浏览次数:2
详细信息

1. 配置文件方式(推荐)

vue.config.js 配置

// vue.config.js
module.exports = {
  devServer: {
    port: 8081, // 修改端口号
    host: '0.0.0.0', // 可选的,允许外部访问
    open: true, // 自动打开浏览器
    https: false, // 是否使用 HTTPS
    // 其他配置...
  }
}

2. 命令行参数方式

临时修改端口

# 启动时指定端口
npm run serve -- --port 8081

# 或使用 yarn
yarn serve --port 8081

# 同时指定主机
npm run serve -- --port 8081 --host 0.0.0.0

3. 环境变量方式

.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"
  }
}

4. 完整的 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
      }
    }
  }
}

5. 端口被占用时的处理

自动选择可用端口

// 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

6. 多环境配置

// vue.config.js
const port = process.env.port || process.env.npm_config_port || 8080

module.exports = {
  devServer: {
    port: port,
    // 根据环境变量配置
    ...(process.env.NODE_ENV === 'production' 
      ? {
          // 生产环境配置
        }
      : {
          // 开发环境配置
        }
    )
  }
}

7. 注意事项

权限问题:低于 1024 的端口需要管理员权限(如 80、443) 端口范围:建议使用 3000-9999 之间的端口 缓存问题:修改配置后重启服务生效 多项目运行:同时运行多个项目时需配置不同端口

8. 常用端口参考

选择适合你项目需求的方式配置即可,推荐使用 vue.config.js 文件进行统一管理。

相关推荐