Jenkinsfile 里怎么正确处理 Vue 项目中的环境变量?

长孙美美 阅读 6

我在 Jenkinsfile 里构建 Vue 项目时,想根据不同的 pipeline 阶段注入不同的环境变量,比如 dev、test、prod,但打包后发现 process.env 里读不到这些变量,页面直接报错。

我试过在 pipeline 的 environment 块里定义变量,也试过在 sh 脚本里用 export,都不生效。是不是 Vue CLI 对环境变量有特殊要求?下面是我的组件里读取变量的方式:

<script>
export default {
  mounted() {
    console.log('API_BASE:', process.env.VUE_APP_API_BASE);
  }
}
</script>
我来解答 赞 4 收藏
二维码
手机扫码查看
1 条解答
怡轩~
怡轩~ Lv1
在 Vue 项目里,环境变量必须以 VUE_APP_ 开头才能被识别。我一般直接在 Jenkinsfile 的 pipeline 里这样写:

pipeline {
environment {
VUE_APP_API_BASE = (env.BRANCH_NAME == 'master') ? 'https://prod.api.com' : 'https://dev.api.com'
}
stages {
stage('Build') {
steps {
sh 'npm run build'
}
}
}
}


记得把变量定义在 environment 块里,然后 Vue CLI 自动会处理这些以 VUE_APP_ 开头的变量。对了,别忘了重启 Jenkins agent,有时候缓存问题会让你以为配置没生效。
点赞
2026-03-30 16:01