Injecting environment variables into webpack configuration

My goal is to set a BACKEND environment variable in order for our VueJS project to communicate with the API hosted there, but I keep receiving an error message saying Unexpected token :.

Here is the current code snippet from our config/dev.env.js, and I'm currently stuck at this point

module.exports = {
  NODE_ENV: '"development"',
  HOST: process.env.BACKEND,
  NAME: '"Jaguar Dashboard"'
}

All I want is for the process.env.BACKEND to be assigned a value like 'http://example.com' so that our VueJS project can function properly. How can I resolve this issue?

UPDATE

I was able to make it work by modifying the code as follows:

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  HOST: 'http://example-0e1b-4a12-91ef-b853a47bab34.node.dockerapp.io:8000',
  NAME: 'Jaguar Dashboard'
})

When attempting JSON.stringify(process.env), an error(Unexpected identifier) occurs in this line:

[...]

When using '"'+process.env.BACKEND+'"', the same error(Unexpected identifier) arises in this line:

[...]

However, when I simply define a string as mentioned above, the code executes without any issues as shown below:

[...]

SCREENSHOTS OF THE CODES:

config/dev.env.js https://i.stack.imgur.com/LoyQq.png

build/webpack.base.conf.js https://i.stack.imgur.com/PAF4n.png

build/webpack.dev.conf.js https://i.stack.imgur.com/t8RDF.png

P.S.

The errors mentioned above occur during the execution of npm run dev in our VueJS project

Answer №1

In reference to your most recent revision: you're attempting to retrieve process.env without specifying an ENV variable name (such as .BACKEND). Could this be a simple typo or the root cause of the problem at hand? : ) It should actually work like this:

plugins: [
    new webpack.DefinePlugin({
        'process.env': {
            BACKEND: JSON.stringify(process.env.BACKEND),

Update:

The solution came when realizing that a variable value was missing double quotes:

NAME: 'Our site'

// ought to be corrected as:
NAME: '"Our site"'

Answer №2

One might observe that the strings are enveloped in an extra set of quotes. This precaution ensures that strings do not get interpreted as variables.

Referencing the DefinePlugin documentation

It's important to note that due to direct text replacement by the plugin, the value provided must contain actual quotes within the string itself. This is commonly achieved by using alternate quotes like '"production"', or through JSON.stringify('production').

You could utilize

HOST: '"'+process.env.BACKEND+'"' 

or

HOST: JSON.stringify(process.env.BACKEND) 
(which is easier to read)

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

Arrows on the button are unresponsive and there seems to be an incorrect number of

I've been working on a project by combining various examples I found online. I'm puzzled as to why it's displaying all the buttons at once instead of just one per page, and why the number of visible buttons decreases by one with each right c ...

Mastering the art of square bracket destructuring in React through deep comprehension of the concept

import React, { useEffect, useState } from 'react' import { Text } from 'react-native' export default function Counter() { const [count, setCount] = useState(0) useEffect(() => { const id = setInterval(() => setCount((co ...

transferring data from grails to javascript via a map

I am facing an issue with passing a Map object from my Grails controller to JavaScript. The code snippet in my controller is as follows: def scoreValue = new HashMap<String,String>(); scoreValue.put("0","poor"); scoreValue.put("1","good"); ... retu ...

jsTree unable to locate node using the provided ID

Implementing the jsTree on the webpage is not a problem for me. I have experimented with numerous suggestions from different sources. $('#myTree').jstree({ .... }) .on('loaded.jstree', function (e, dta) { var t = $('#myTree&a ...

Can a dynamic title be implemented in a navbar?

On my website, I currently have a title navbar that is displayed on every page (TheNavbar Component). However, I want to dynamically change the title based on the specific page being viewed. For example, within my projects folder there is another folder ...

Discrepancy in div height between Chrome/Edge and Firefox browsers

I am currently in the process of designing a straightforward website layout that includes a navigation bar at the top. The main focus is on an image that needs to stretch from the bottom of the navbar to the bottom of the window, filling up the entire scre ...

Is it acceptable to incorporate Node.js modules for utilization in Next.js?

Here's a funny question for you. I am trying to generate UUID in my Next.js project without adding any unnecessary packages. So, I decided to import crypto in my component like this: import crypto from 'crypto'; After importing it, I used i ...

What is the method for interacting with an embedded alert using SeleniumIDE?

When working with HTML, I came across the following code snippet (it's not from my website): <script> alert('1'); </script> My challenge now is to test this code using Selenium IDE and ensure that the alert will be clicked. How ...

Having trouble opening a JPEG file that was generated using the Writefile Api in Ionic-Cordova

Currently, I am using the writeFile API to create a JPEG image. The process is successful and the image is stored in the directory as expected. However, when I try to open the file manually from the directory, I encounter an error message saying "Oops! Cou ...

Increase the size of the SVG area

I'm still learning how to work with SVGs, so I appreciate your patience as I ask what may seem like a simple question. Currently, I have an SVG image that resembles a cake shape. See it here: Take a look at the code: <svg version="1" id="Layer_1 ...

Exploring how to iterate through multiple arrays simultaneously in JavaScript

I have a specific problem with processing two sets of array objects to achieve a desired output. var parts={"Glenn": [12,22,32], "Ryan": [13,23,33], "Steve K": [14], "Jerom":[15,25,35], }; var labor={ "Glenn": [12,22,32], "Ryan": [13,23,33], "Steve K": [ ...

transferring attributes from a component iterated over to a component it renders

Admitting my lack of expertise, I am seeking assistance with the implementation of the following code. This is my "posts" component responsible for making an API call to fetch all post data: import React from 'react' import Post from '../pos ...

What could be the reason for scope.$watch failing to function properly?

My AngularJS directive has a template with two tags - an input and an empty list. I am trying to watch the input value of the first input tag. However, the $watch() method only gets called once during initialization of the directive and any subsequent chan ...

Encountering a TypeScript error when attempting to utilize indexOf on a Typed Array, leading to restriction

I have been working with an Interface, where I created an array of type Interface. I am currently facing some IDE error complaints when trying to use the .indexOf method on the Array. These errors seem confusing to me, and I'm hoping someone here migh ...

"Encountered a problem when trying to access file with node

An error has occurred: module.js:471 throw err; ^ Error: Module not found at '/Users/vinclo/app.js' at Function.Module._resolveFilename (module.js:469:15) at Function.Module._load (module.js:417:25) at Module.runMain (module.js:604:10) at run ( ...

Looking to show an image when a checkbox is ticked and hide it when it is unticked in HTML?

How do I make a specific image appear when a user clicks on a checkbox? I'm unsure if I should use jQuery, Ajax, or another method. What is the best approach for this task? Your assistance would be greatly appreciated. I have successfully created the ...

Using Jquery and css to toggle and display active menu when clicked

I am trying to create a jQuery dropdown menu similar to the Facebook notification menu. However, I am encountering an issue with the JavaScript code. Here is my JSFiddle example. The problem arises when I click on the menu; it opens with an icon, similar ...

Remove HTML tags from a table cell containing a combination of radio buttons and labels

Javascript Function: My JavaScript function posted below is designed to iterate through the column indexes specified in the 2nd parameter and also iterate through the element ids provided in the 3rd parameter. It will then populate the textbox, radiobutto ...

Is it possible for a Titanium application to utilize the iOS sharing functionalities?

I am looking to integrate a share feature in my app that allows users to easily share content by clicking on a share icon. I want the iOS share page to appear from the bottom of the screen, giving users options to share via message, mail, Twitter, and Face ...

Exploring the mechanics of callbacks in jQuery's Ajax functionality

Greetings fellow developers! I've embarked on a new programming project with the firm intention of writing cleaner and more easily maintainable code than ever before. However, I have encountered my old nemesis - jQuery AJAX returns. The last time I t ...