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

Learn how to display a tooltip for every individual point on a Highcharts network graph within an Angular

I am currently working on developing network graphs using highcharts and highcharts-angular within my Angular application. I have successfully managed to display the graph with datalabels, but now I need to implement tooltips for each point or node on the ...

employing iframes dynamically to overlay a webpage

I inserted this iframe into a webpage <iframe src='http://redbug.redrocksoftware.com.au:80/Pages/chamara.html' style="position:absolute;z-index:1;" ></iframe> The chamara.html page has a button that, when clicked, should cover the c ...

Tokenizing with jQuery UI

I have been following a tutorial that utilizes jQuery UI to generate Facebook tokens, as shown in this link: However, I am facing an issue where I need to pass two values through JSON: the ID and the NAME. The server-side script is structured as follows: ...

Showing JSON information on a web browser

Here is a snippet of JSON data that I am working with: {"earthquakes":[{"datetime":"2011-03-11 04:46:23","depth":24.39999999999999857891452847979962825775146484375,"lng":142.36899999999999977262632455676794 ...

Using a Hook inside a React function is not possible

I encountered an error message known as the "invalid hook call error" while using the useEffect hook in my code. According to the documentation, this issue usually arises due to either a version mismatch or incorrect function calls. Could someone kindly r ...

What is the reason behind jshint issuing an alert specifically for the lastSelectedRow being

Upon pasting the code below into jshint.com, an error is generated: Read only in reference to line: lastSelectedRow = 1; I am curious as to why this error occurs and how it can be remedied. Interestingly, jslint does not return this error. /*global la ...

Exploring the combined application of the AND and OR operators in JavaScript programming

{Object.keys(groupByMonthApplicants).map((obj,i) => <div key={obj} style={(i > 0 && (this.state.selectedTabId !== 'rejected' || this.state.selectedTabId !== 'approved')) ? {paddingTop:'15px',background:&a ...

How to make Sails.js package accessible across all modules

Recently, I have been using Sails frequently and came across a common practice question. Whenever I need to use a specific NPM package multiple times in a project, I typically include it in my config/bootstrap.js file like this: module.exports.bootstrap = ...

Is there a way to sequentially load two iframes, with the second one loading only after the first one is fully loaded

Having two different links that trigger ajax calls can be tricky if only one request is allowed per load. This may result in both iframes displaying the same data. Is there a way to work around this issue? Perhaps loading one iframe first and then triggeri ...

When integrating React with Tawk, the user's name and email are automatically encoded before being sent

My code within the componentDidMount() function initializes a widget popup when the page loads. It then sets the name and email using parameters received from the previous page. const fullName = this.state.data[0]; console.log(fullName); const e ...

The routes may be the same in both React Router Dom v6, but each one leads to a different

I am struggling to set up different routes for navigation and I'm not sure how to do it. Here is what I have attempted so far: const router = createBrowserRouter( createRoutesFromElements( <> <Route path="/" element={<NavB ...

A guide to incorporating a textview into a React application using the Google Maps API

Wondering how to incorporate a textview within a react-google-maps component? Successfully setting up a Google map page in React using the react-google-maps API, I've managed to insert markers and link them with polylines. import React from "react"; ...

Why does Vue only change a specific array element without updating the DOM?

My curiosity is piqued by a puzzling issue with updating specific items in an array using Vue.js. The documentation cautions that: Due to limitations in JavaScript, Vue cannot detect the following changes to an array: When you directly set an item with th ...

Error: FileReader is not defined in Node.js (Nest.js) environment

I am working on converting my image to base64 using a custom function. However, when I try to execute the code, I encounter an error message stating ReferenceError: FileReader is not defined. This error has left me puzzled and unsure of its cause. Below i ...

Prevent the Swiper slider from autoplaying while a video is being played, and automatically move to the next slide once the video is paused or

<div class="swiper mySwiper"> <div class="swiper-wrapper"> <div class="swiper-slide"> <video-js id="6304418462001" class="overlayVideo" data-account= ...

Performing an Ajax POST request using jQuery

I am currently working on modifying my code to use POST instead of GET to send variables to a PHP page. The current code sends data via GET and receives it in JSON format. What changes should I make in order to pass the variables to process_parts.php usi ...

Creating an Angular JS controller that utilizes a filter for a JSON array of objects

I have the following JSON data and I'm trying to determine the number of objects with Status: 1 in the JSON. The approach I've taken so far is not working. I understand that ng-filter should only be applied to Arrays, but I'm struggling to ...

Utilizing ChartJS to convert a chart into a Base64 image within a Vue environment

I am currently utilizing the PrimeVue chart component, which is built on top of ChartJS. The configuration is very similar. The documentation indicates that I need to instantiate a new Chart() and then call toBase64Image(); My main query is, how do I ac ...

The React.js .map function encountered an error while trying to map the results from Firebase

As a newcomer to the realm of React and Firebase, I find myself struggling with arrays and objects. It seems like the way my data is formatted or typed does not play well with the .map method. Despite scouring Stack Overflow for answers, none of the soluti ...

Incorporate React into current Node express application by utilizing a content delivery network (CD

I'm currently in the process of developing a web application utilizing both Node and React. Instead of having separate Node and React applications, I decided to integrate React directly into my existing setup. To achieve this, I attempted importing th ...