如何在 VueJS 项目构建时使用环境变量

2023-12-11

我正在尝试在期间使用环境变量buildVueJS 应用程序的 CI 作业阶段。我正在使用 GitLab CI,可用的环境变量之一是CI_COMMIT_SHORT_SHA,

build:
  image: node:latest
  stage: build
  variables:
    CI_COMMIT_SHORT_SHA: "$CI_COMMIT_SHORT_SHA"
  artifacts:
    paths:
      - dist/
  script:
    - npm install --progress=false
    - npm run build
    - echo "Build Complete"

以下是我尝试在 Vue 中使用此变量的方法:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <p>This is a static site that is served with a CloudFront distribution in front of an S3 bucket.</p>
    <p>The site is updated through a GitLab CI/CD pipeline.</p>
    <p>Commit ref: {{ commit }}</p>
    <p>Using cache invalidation</p>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data(){
    return {
      commit: process.env.CI_COMMIT_SHORT_SHA
    }
  }
}
</script>

我没有看到这个变量出现。为了访问环境变量并将其显示在我的组件中,我还需要做其他事情吗?


正如中提到的https://cli.vuejs.org/guide/mode-and-env.html#using-env-variables-in-client-side-code

仅限以以下开头的变量VUE_APP_将静态嵌入到客户端包中webpack.DefinePlugin。您可以在应用程序代码中访问它们:

console.log(process.env.VUE_APP_SECRET)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 VueJS 项目构建时使用环境变量 的相关文章

随机推荐