Utilizing Environment Variables during the build process in a VueJS project

During the build stage of a CI job for my VueJS app, I am attempting to utilize an environment variable provided by GitLab CI called 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"

This is how I am trying to use the variable in my Vue component:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <p>This site is static and utilizes CloudFront and S3 bucket.</p>
    <p>Updates are done through GitLab CI/CD pipeline.</p>
    <p>Commit ref: {{ commit }}</p>
    <p>Implementing cache invalidation</p>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data(){
    return {
      commit: process.env.CI_COMMIT_SHORT_SHA
    }
  }
}
</script>

Despite my efforts, the variable does not seem to be passing through. Is there an additional step required to access the environment variable and show it in my component?

Answer №2

When working with webpack.config, setting up DefinePlugin can be done in a similar manner.

To implement this in your webpack.config.js, you will need to utilize 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
}),

The values for config.prod / config.dev would typically look like this:

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

In these scenarios, the files prod.env.js and dev.env.js would resemble something along the lines of:

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

If there's a need to align more closely with the vue process, one could use a RegExp filter to select object keys matching /^VUE_APP_.*/.

Subsequently, within the data section of your .vue file, you can incorporate these values by utilizing:

data: {
  VUE_APP_MODE: process.env.VUE_APP_MODE
}

Answer №3

My findings revealed that the vue-cli-service build command specifically scans dot-files located in the root of your project and only processes variables prefixed with VUE_APP_ (found in different .env files).

To streamline this process, I decided to input all the necessary variables in the Gitlab CI options and then transfer them to the .env file. This way, when vue-cli compiles the project, it automatically integrates these values into the transpired scripts.

Prior to building the project, implementing a command like the following was crucial:

env | grep 'VUE_APP_' > .env

In addition to my main setup, I also manage a staging environment that gets generated upon pushing changes to the staging branch. To accommodate this, I defined specific variables in Gitlab:

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

As vue-cli mandates that variables must start with VUE_APP_, I applied a modification using sed:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Controlling HTML elements with a controller

This seems chaotic and I long for a more organized solution. I have different HTML elements: <input class="form-control" required="true" name="Spanish" type="text" value="blah blah" id="lang_1"> <input class="form-control" required="true" name= ...

Troubleshooting Yeoman and Angular: Routing troubles persist

I recently started exploring with yeoman to develop angular applications. I am facing an issue while trying to create routes using yo:angular route. After running the command: yo:angular route foo yeoman generates the following files: app/scripts/contr ...

Having trouble locating an element on a webpage? When inspecting the element, are you noticing that the HTML code differs from the source page?

I'm having trouble locating a specific element on a webpage. When I use the Inspect Element tool, I can see the HTML code with the element id = username, but when I check the page source, all I see is JavaScript code. Does anyone have any suggestions ...

How can one determine if a user's location is in proximity to a specific position?

I am currently working on a Firefox add-on that utilizes GPS to determine the user's location and triggers a specific action when they are in close proximity to a certain point. For example, the add-on should only take action when green users are near ...

Integrating external JavaScript widgets into the web application in real-time

I am currently engaged in a React js project that involves the dynamic addition of third party scripts (widgets) to the web app. These widgets encompass various third party platforms such as Twitter, Instagram, Youplay, Youtube, and more. The existing co ...

Align the text on the same horizontal line

I have been struggling with this issue for hours. Here is my Header.js <div className="navbar-inner"> <h2>Text1</h2> <h3>Text2</h3> </div> This is the content of my Header.css: .navbar-inner { ...

What is the best approach to managing a 204 status in Typescript in conjunction with the Fetch API

Struggling to handle a 204 status response in my post request using fetch and typescript. I've attempted to return a promise with a null value, but it's not working as expected. postRequest = async <T>(url: string, body: any): Promise ...

Utilize express.static to showcase and fetch HTML content before serving JavaScript files

I'm having trouble getting my home.html file to display properly on the browser when I'm using express.static. Here is how my directory and file layout are structured: dir main -server.js dir subMain dir routing -routes.js ...

Combining Laravel and vue.js for seamless file uploading functionality

Successfully uploading files using vue.js 1.0 with a POST request looks like: store () { this.storingMessage = true; var form = new FormData(); form.append('subject', this.message.subject); form.ap ...

Is it possible to expand the Angular Material Data Table Header Row to align with the width of the row content?

Issue with Angular Material Data Table Layout Link to relevant feature request on GitHub On this StackBlitz demo, the issue of rows bleeding through the header when scrolling to the right and the row lines not expanding past viewport width is evident. Ho ...

Efficiently sending VueJS data to a separate script

I am in the process of transitioning an existing site to VueJS, but I have encountered a roadblock when it comes to finding the best method to accomplish this task. The site currently utilizes D3-Funnel (https://github.com/jakezatecky/d3-funnel) to genera ...

Tips for choosing the remaining items in a multiple selection process

In my HTML form, I have a multi-select field that contains categories and the corresponding items within each category. My goal is to allow users to select individual courses or select an entire category (identified by values starting with "cat_") in orde ...

Exploring the firestore section with vuefire for seamless access to methods

I am attempting to access a method in the firestore section of vuefire, but encountering the following error: vue-router.esm.js?8c4f:2257 TypeError: Cannot read property 'messagesWith' of undefined at eval (Chat.vue?62f3:214) This is the lin ...

What is the significance of default parameters in a JavaScript IIFE within a TypeScript module?

If I were to create a basic TypeScript module called test, it would appear as follows: module test { export class MyTest { name = "hello"; } } The resulting JavaScript generates an IIFE structured like this: var test; (function (test) { ...

Tips for switching between two CSS classes for a single control in ASP.Net

<style type="text/css> .CssStyle1 { font: 10pt Verdana; font-weight:700; color: Green; } .CssStyle2 { font: 15pt Times; font-weight:250; color: Blue; } </style> <as ...

Query Selector(jQuery selector) is a powerful tool for

Here is the HTML Table structure: <table class="display" style="width: 1000px;" id="failoverServers"> <thead> <tr> <th class="row_selector_head"> <input type='checkbox' class='select_all_ch ...

Include the JS file after finishing the control processing

I've been grappling with an issue for several days now. The view I have is populated by my controller through an API call, which works perfectly fine in rendering the HTML. $http.get(url). success(function(data, status, headers, config) { ...

Programmatically select rows in multiple mode using Primevue Datatable

Currently, I am utilizing the PrimeVue Datatable which includes multiple selection checkboxes. One key feature that I aim to implement is the ability to add a new row to the table and have it automatically selected upon addition. However, I am encounterin ...

Angular 6 and the intricacies of nested ternary conditions

I need help with a ternary condition in an HTML template file: <div *ngFor="let $m of $layer.child; let $childIndex=index" [Latitude]="$m.latitude" [Longitude]="$m.longitude" [IconInfo]="$childIndex== 0 ? _iconInfo1:$c ...

The browser sends a request for a file, the server then downloads a pdf, and finally, the

Here is the process I am trying to achieve: 1) A browser sends an ajax request to the server, requesting a pdf file. 2) The server downloads the pdf file and returns it for display. 3) The browser then displays the downloaded pdf in an existing iframe. Be ...