簡體   English   中英

如何在 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>

我沒有看到這個變量通過。 為了訪問環境變量並將其顯示在我的組件中,我還需要做些什么嗎?

如果你使用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
}

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)

經過一些研究,似乎vue-cli-service build命令只查看項目根目錄中的點文件,並且只處理這些以VUE_APP_開頭的變量(在各種 .env 文件中)

您可以在 Gitlab CI 選項中設置所有變量,然后將這些變量復制到 .env 文件中。 現在,當 vue-cli 構建項目時,它會在轉譯的腳本中注入這些值。

您可以在構建項目之前發出這樣的命令:

env | grep 'VUE_APP_' > .env

我還使用了在推送到 staging 分支時構建的 staging 環境。 因此,我將這些變量設置到 Gitlab 中:

  • VUE_APP_VAR1=foo
  • VUE_APP_VAR2=條形
  • VUE_ACCEPT_VAR1=foo
  • VUE_ACCEPT_VAR2=條形

由於 vue-cli 希望變量以VUE_APP_開頭, VUE_APP_我用 sed 替換:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM