How to use environment variables at build time in

2019-07-26 09:13发布

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"

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?

2条回答
Luminary・发光体
2楼-- · 2019-07-26 09:27

If you're using webpack.config, you can set up DefinePlugin in a similar way.

In your webpack.config.js you would use a new plugin,

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
}),

Where config.prod / config.dev is something like

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

at the top of the file,

and the prod.env.js and dev.env.js files look something like

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

If you wanted to match the vue process more closely,you could filter out the object keys using RegExp /^VUE_APP_.*/.

Then in the data section of your .vue file you can include these by using:

data: {
  VUE_APP_MODE: process.env.VUE_APP_MODE
}
查看更多
太酷不给撩
3楼-- · 2019-07-26 09:39

As mentioned in 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)

查看更多
登录 后发表回答