如何在VueJS项目中的构建时使用环境变量 [英] How to use environment variables at build time in a VueJS project

查看:269
本文介绍了如何在VueJS项目中的构建时使用环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在CI作业的build阶段为VueJS应用程序使用环境变量.我使用的是GitLab CI,可以使用的环境变量之一是CI_COMMIT_SHORT_SHA

I'm trying to use an environment variable during the build stage of a CI job for a VueJS app. I'm using GitLab CI, and one of the environment variables that is made available is 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中使用此变量的方式:

Here's how I'm trying to use this variable in 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>

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

I'm not seeing this variable come through. Is there something else I need to do in order to access the environment variable and display it in my component?

推荐答案

只有以VUE_APP_开头的变量将通过webpack.DefinePlugin静态地嵌入到客户端捆绑包中.您可以在应用程序代码中访问它们:

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)

这篇关于如何在VueJS项目中的构建时使用环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆