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

a function that repeats every single second

A challenge I am facing is creating a countdown timer with a time that refreshes every second. My current implementation uses setInterval, but it only seems to run once instead of every second. Can anyone help me identify the issue in my code? var countDo ...

Enhance your React project by incorporating Material-UI card media elements with the ability to add

I am trying to figure out how to create an opaque colored overlay on top of an image using Material-UI. While it is possible with plain HTML, CSS, and JavaScript, I am facing some challenges with Material-UI. <Card> <CardMedia> <im ...

What is the method for retrieving data from the root component within a child template in VueJs?

How can I access this.$root from within a VueJs template? For example: <template> <v-card elevation="this.$root.$refs.foo.cardElevation"> Foo </v-card> </template> I am aware that I can create a data property and ...

Issue encountered when attempting to install React modules

Attempted to install sass-loader, as well as node-sass using both yarn and npm; however, encountered identical errors. Various methods were tried: yarn add <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="057664767628696a646160 ...

applying v-bind directive when the variable is null

I am using Vue and have a variable. If the variable has a value, I want to display an image (pic1). However, if the variable is empty, then I want to show another image (pic2). Here's my code... <template v-for="(item, index) in items"> <im ...

Displaying both items upon clicking

Hey there, I'm having an issue where clicking on one article link opens both! <span class='pres'><img src='http://files.appcheck.se/icons/minecraft.png' /></span><span class='info'><a href=&apo ...

Utilize Vuex to close a Vuetify dialog box seamlessly

After hours of struggling and experimenting with different methods, my beginner's mind reached its limit. I've attempted numerous solutions, but I'm completely lost. Everything else seems to be functioning correctly - I can remove the desire ...

Can anyone provide guidance on creating a Jest test for an authenticated Express endpoint?

I have been working on a seemingly straightforward 4-file toy solution that I thought was simple. I am looking to write a Jest test for the '/bingo' route in bingo.js which requires authentication. Below are the four files that make up this setup ...

Customizing the renderInput of the Material UI DatePicker

Recently I integrated material-ui into my React project with TypeScript. I implemented the following code based on the example provided on the official website. import AdapterDateFns from '@mui/lab/AdapterDateFns'; import DatePicker from '@m ...

A simple guide on how to surround every incorrect input index in mapped inputs with red borders

I am incorporating a modal that corresponds each element of the object newCompanies to a specific row: {newCompanies.map((company, index) => { return ( <div> <div className="side- ...

The JQuery chosen dropdown experiences a visual issue when placed inside a scrollbar, appearing to be "cut

Good day, I've been using the jQuery "chosen" plugin for a dropdown menu, but I encountered an issue with it being located in a scrollable area. The problem is that the dropdown items are getting cut off by the outer div element. I have provided a si ...

Unspecified data response error in Angular JS

As a beginner in Angular JS, I am currently working on calling a Rest API using JSON data. However, when I run the HTTP-server, I am not receiving my response data as expected. function retrieveContacts(contactsdata) { contactsdata.getContacts().the ...

Iterating through elements within a Div will retrieve the initial element exclusively

Is there a way to loop through all elements within the MainDiv Div in order to retrieve their values? Currently, I am only able to retrieve the value of the first element. <div id="MainDiv"> <input type="text" id="MyText"value="Text1" /> ...

Is it possible to utilize both the /app and /pages folders in my Next 13 application?

I am currently working on a project where the /app folder is utilized as the primary route container. However, we have encountered performance issues on localhost caused by memory leaks identified in an issue on the Next.js repository. I am curious to fi ...

Determining the file path in HTML5

Can anyone help me with retrieving the file path using html5 javascript once a user selects a file? I require the file path for a specific scenario: In this case, the user uploads a file and pauses it (currently only supported by Mozilla browsers), then c ...

Customizing the main icon in the Windows 10 Action Center through a notification from Microsoft Edge

I am facing an issue with setting the top icon of a notification sent from a website in Microsoft Edge. Let's consider this code as an example: Notification.requestPermission(function (permission) { if (permission == "granted") { new ...

Best practices for managing login authentication using MongoDB in a RESTful API

I'm currently figuring out how to verify if the values align with the MongoDB data. In my approach, I'm utilizing the PUT method along with attempting to utilize findOneAndUpdate to validate the values. <script> const logindetails = new Vu ...

Setting the default selection in AngularJS based on the URL entered

I've encountered an issue with a dropdown menu in my AngularJS version 1.4 application. The dropdown menu contains links to different sections of the page. The problem arises when I directly enter the page URL - instead of selecting the correct link f ...

JavaScript allows users to create a single string by merging multiple strings positioned at various points

Let's say we have 3 strings: s1 = "ab", s2 = "cd", s3 = "ef". The task is to form a new string by merging s1, s2, and s3. The twist here is that the user has the freedom to choose the positions of these 3 strings. For example: s1 - position 3; s2 - ...

Exploring the power of promise chaining within AWS Lambda

I'm feeling a bit confused about how Promise chaining works in AWS Lambda. exports.handler = async(event) => { firstMethod = () => { return new Promise(function(resolve, reject){ setTimeout(function() { ...