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

How to use environment variables at build time in a VueJS project

我正在尝试在 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)

如果您使用的是 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过滤掉object keys /^VUE_APP_.*/.

然后在 .vue 文件的数据部分中,您可以使用以下方法包含这些内容:

data: {
  VUE_APP_MODE: process.env.VUE_APP_MODE
}

经过一些研究,vue-cli-service build 命令似乎只查看项目根目录中的 dot-files,并且只处理这些以 VUE_APP_ 开头的变量(在各种 .环境文件)

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

您可以在构建项目之前发出这样的命令:

env | grep 'VUE_APP_' > .env

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

  • VUE_APP_VAR1=foo
  • VUE_APP_VAR2=栏
  • VUE_ACCEPT_VAR1=foo
  • VUE_ACCEPT_VAR2=栏

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

env | grep 'VUE_ACCEPT_' | sed 's/VUE_ACCEPT_/VUE_APP_/' > .env