Unable to access the .env file in Vue.js when executing cross-env NODE_ENV=development webpack-dev-server --open --hot

I'm attempting to utilize an .env file for storing local variables, but I am encountering an issue where they appear as undefined when I try to log them.

Here is a snippet from my .env file (located at the root of my project):

VUE_APP_STRAPI_HOST=http://localhost:1337/

When attempting to console log this variable, I am using the following code:

console.log(process.env.VUE_APP_STRAPI_HOST)

This is the command I am running in the terminal:

cross-env NODE_ENV=development webpack-dev-server --open --hot 

I suspect that the issue may be related to the cross-env package. Any suggestions?

Answer №1

Summary:

require('dotenv').config()

Too long, didn't read:

Simply creating a file named .env won't automatically export variables to your process. To do so in bash or any shell system, you can either use the command

export VUE_APP_STRAPI_HOST=http://localhost:1337/
before running your process, or use
VUE_APP_STRAPI_HOST=http://localhost:1337/ node webpack-dev-server --open --hot 
.

If you're looking for a way to access variables from a .env file in your process, consider using dotenv:

require('dotenv').config()

However, keep in mind that this only updates the global variable process.env with your configuration.

To export variables from a .env file to your environment variables, you can use a shell script like the following:

source_it() {
  while read -r line; do
    if [[ -n "$line" ]] && [[ $line != \#* ]]; then
      export "$line"
    fi
  done < $1
}
source_it .env

Afterwards, you can run your process as usual:

node ./node_modules/.bin/cross-env NODE_ENV=development webpack-dev-server --open --hot

P.S.

Keep in mind that displaying console.log messages in your browser is unrelated to the Node.js process running webpack-dev-server. To make your process.env variable accessible globally in your browser, consider using something like DefinePlugin

Answer №2

Big shoutout to @deathangel908 for helping me develop this solution:

config.js

module.exports.plugins = (module.exports.plugins || []).concat([
  new webpack.EnvironmentPlugin({
    CUSTOM_HOST: 'example'
  })
])

An issue I encountered with using webpack EnvironmentPlugin is the inability to utilize .env files such as .env.development. While there is a webpack plugin available, I faced persistent errors in my specific project that posed difficulty in resolving.

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

Eliminating the dynamic element in jQuery causes disruption to the ViewContainerRef container

In my Angular 2+ application, I am dynamically creating components using the following code snippet: @ViewChild("containerNode", { read: ViewContainerRef }) cardContainer; const factory = this.ComponentFactoryResolver.resolveComponentFactory(CardComponen ...

Heroku is encountering an issue as it is unable to locate the module '/tmp/build_.../.yarn eleasesyarn-1.22.4.js'

I have successfully implemented the Flask+Vue.js template from this source, designed specifically for Heroku deployment. However, when attempting to integrate Vuetify into my project, I encountered the following error upon pushing my code: Error Message ...

Sending a POST request in nodeJs that does not return any value

I have a button on my client site that sends a POST request to my server. The request does not require a response as it simply inserts data into the database. However, after clicking the button, the client continues to wait for a response until it times ou ...

When a user focuses out of a field, an event object will appear within it

Currently, I am developing a VueJS application that enables users to modify JSON files containing specific data. In my project, I have implemented two similar components: AliasEntry and EquipmentEntry. The latter is responsible for manipulating an array of ...

Deactivate toggle effect by clicking on a different link

My existing JavaScript code changes the background color of a link when it is clicked: $(".button").click(function(){ $(this).css('background-color', '#555'); }); While this functionality works, I am looking to have the color tog ...

Emails can be sent through a form without the need for refreshing

I am currently working on a webpage that utilizes parallax scrolling, and the contact box is located in the last section. However, I encountered an issue where using a simple HTML + PHP contact box would cause the page to refresh back to the first section ...

The functionality of php.js is compromised

I've been attempting to integrate php.js into my scripts, but have encountered a problem. I debugged a function and loaded it onto a single page containing only jQuery and php.js, yet it is still not functioning properly. <script src="http://code. ...

Tips for sending a Django queryset as an AJAX HttpResponse

Currently, I am faced with the challenge of fetching a Django queryset and storing it in a JavaScript variable using Ajax. I have attempted to employ the following code snippet for this purpose; however, I keep encountering the issue of "Queryset is not J ...

Adding a button in Node and Mongoose for updating data: A step-by-step guide

I have set up a mongoose database containing events, each event is displayed within a bootstrap card. My challenge now is to find a way to redirect the admin to a page where they can update the event card and save it to my mongoose db. The problem I' ...

Observing changes in a parent component variable with Angular

One feature of my form is that it consists of a parent component and a child component. To disable a button within the form, I utilize a function called isDatasetFilesValid() which checks a specific variable (datasetList[i].fileValid). This variable is mo ...

Guide to sending back a promise using JQuery

Here is the Durendal code I am working with: var variable = ko.observable(""); function activate(){ return myModel.doSomething(variable); } The doSomething function looks like this: function doSomething(variable){ if(someCondition) return ...

Sending a PDF document to a function that specifically calls for a file location or URL

Currently, I am developing a web application for an online library where I need to extract metadata from PDF files that are uploaded. To achieve this, I am utilizing the nodejs libraries pdf.js-extract and multer-gridfs-storage for file uploads. However, I ...

Mouse hovering over the JS slider activates the sliding functionality, while removing the cursor

Hi there, I'm encountering some issues with the JS clients slider on my website. I need to pause it when the mouse is over and resume when the mouse leaves. I've double-checked the code but for some reason it's still not functioning properl ...

jQuery click event handler performing no action

I am encountering an issue with the input on my index page: <input type="button" name="goReplaceAll" value="Go" id="allReplaceGo" style="cursor:hand;" /> There is an onclick call from jQuery as follows: $(document).ready(function() { $(&ap ...

Leveraging the power of node pkg to generate standalone executables while configuring npm

I have successfully used pkg to create an executable file for my node js application. Everything is working fine in that aspect. However, I am also utilizing the config module to load yaml configuration files based on the environment. During the packaging ...

Unable to access Vue component method beyond its scope

Having an issue with my Vue component that I'm trying to call a method from outside its wrapper element #app. Is there a way to register the component so I can easily call it like Component.function(); var viewController = new Vue({ el: "#app", ...

Center a grid of cards on the page while keeping them aligned to the left

I have a grid of cards that I need to align in the center of the page and left within the grid, adjusting responsively to different screen sizes. For example, if there are 10 cards and only 4 can fit on a row due to screen size constraints, the first two ...

What is the best way to emphasize a table row during a search rather than just the text?

I am currently using a jQuery script that searches for a specific string in a simple text input field and highlights only the string itself if it is found. However, my data is organized within a table and I am interested in knowing if it is possible to hig ...

What is the process for including a static file on an http server?

Looking to create a chatroom using node.js. Utilizing the socket.io template for this project. var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); var fs = require(&ap ...

developing a dropdown menu feature

I'm struggling with a small issue related to my drop-down menu function. My goal is to hide the visibility of a menu tab after it has been clicked for the second time. Below is the code snippet I've been working on: HTML:- <nav class="clea ...