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

时间:2019-02-20 18:01:25

标签: javascript vue.js npm gitlab-ci

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

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

3 个答案:

答案 0 :(得分:2)

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)

答案 1 :(得分:1)

如果您使用的是webpack.config,则可以类似的方式设置DefinePlugin

在您的webpack.config.js中,您将使用一个新插件,

new webpack.DefinePlugin({
  /* 
    JSON.stringify(yourconfig) is highly recommened 
    to avoid overwriting existing keysother process.env
  */
  'process.env': JSON.stringify(config.prod), // or config.dev
}),

config.prod / config.dev类似于

let config = {};
config.prod = require('./config/prod.env'); // imports ./config/prod.env.js
config.dev = require('./config/dev.env');

位于文件顶部

以及prod.env.jsdev.env.js文件看起来像

'use strict';
module.exports = {
  VUE_APP_MODE: 'MYMODE'
};

如果您想更紧密地匹配Vue流程,则可以使用RegExp /^VUE_APP_.*/过滤掉对象键。

然后在.vue文件的数据部分中,您可以通过以下方式添加这些内容:

data: {
  VUE_APP_MODE: process.env.VUE_APP_MODE
}

答案 2 :(得分:0)

经过一番研究,似乎vue-cli-service build命令仅查看项目根目录中的点文件,并且仅处理以VUE_APP_开头的这些变量(在各种.env文件中)< / p>

您可以在Gitlab CI选项中设置所有变量,然后将这些变量复制到.env文件。现在,当vue-cli构建项目时,它将这些值注入到已编译的脚本中。

您可以在构建项目之前发出如下命令:

env | grep 'VUE_APP_' > .env

我还使用推入暂存分支时构建的暂存环境。因此,我将这些变量设置到了Gitlab中:

  • VUE_APP_VAR1 = foo
  • VUE_APP_VAR2 = bar
  • VUE_ACCEPT_VAR1 = foo
  • VUE_ACCEPT_VAR2 = bar

由于vue-cli希望变量以VUE_APP_开头,所以我用sed进行了替换:

env | grep 'VUE_ACCEPT_' | sed 's/VUE_ACCEPT_/VUE_APP_/' > .env
相关问题