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

标签 javascript vue.js npm gitlab-ci

我正在尝试在 VueJS 应用程序的 CI 作业的 build 阶段使用环境变量。我正在使用 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 中所述

Only variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin. You can access them in your application code:

console.log(process.env.VUE_APP_SECRET)

关于javascript - 如何在 VueJS 项目的构建时使用环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54792619/

相关文章:

javascript - 解析联系表单的 URL 时遇到问题

javascript - 如何使图表水平滚动(使用 Chart.js 时)

javascript - Vue.js <component> 标签未加载导入的组件;使用组合 API

javascript - 为什么命名为 : false does not work for me

reactjs - 新的 create-react-app 构建上的 npm start 返回 ELIFECYCLE 错误

node.js - Kubernetes 上 pod 中的 localhost

javascript - 如何使用 cy.load 设置 cytoscape.js 中节点的起始位置?

javascript - 如何阻止模态直到 api 请求得到解决

ruby - 更新 gem 时 Docker 包安装缓存问题

javascript - Chrome扩展程序内容脚本不适用于gmail