How can you retrieve command line variables within your code by utilizing npm script in webpack?

I'm trying to access command line parameters from an npm script in my "constants.js" file.

While I have been able to access parameters in the webpack.config.js file using process.env, it seems to be undefined in my app source files.

The scenario consists of running a script from the console like so:

npm webpack-dev-server --hot MY_PARAMETER=some_value

Afterwards, I want to somehow access MY_PARAMETER in my constants.js file by checking:

process.env.MY_PARAMETER === "some_value"   // true

If anyone could provide some assistance on this matter, I would greatly appreciate it. Thank you!

Answer №1

If you come across a .env file, it is highly recommended to utilize dotenv-webpack (and optionally, string-replace-webpack-plugin or a similar tool). After reviewing the documentation, it is advised to include a .env.local entry in your VCS ignore file (.gitignore, .hgignore, etc.) for security reasons, and initialize the new DotenvPlugin with an object specifying the path, as shown below:

const DotEnvPlugin = require('dotenv-webpack');
module.exports = {
/* other settings */
  plugins: [
    // other plugins,
    new DotEnvPlugin({
      path:'.env.local',
      // safe: true, // load '.env.example' to verify the '.env' variables are all set. Can also be a string to a different file.
    })
  ]
}

In case you do not possess a .env file, consider utilizing the aforementioned string-replace-webpack-plugin and simply add those variables to your environment. You may need to seek guidance from your OS/administrator on how to proceed.

Lastly, remember that you can define these variables in a command-line call; just ensure they are placed before any executed command, like so (for bash shell):

MY_PARAMETER=some_value node_modules/.bin/webpack-dev-server --hot

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

Is there a way for me to identify the value within useCallback without any intermediaries?

How can I ensure that console.log('success') is triggered when the ids of myFood[myFood.length - 1]?.id and viewableItems[viewableItems.length - 1]?.item?.id match? Despite both values being equal, there seems to be an issue preventing console.l ...

Installing nodejs will cause issues with the successful installation of Npm

I recently started using Node.js and I used the following command to install it: sudo apt-get install -y nodejs Usually, npm is automatically installed along with Node.js. However, when I checked the version of npm, I received this output: https://i.sta ...

Using VueJS Computed Property along with Lodash Debounce

I have been encountering a slowdown while filtering through a large array of items based on user input. I decided to implement Lodash debounce to address this issue, but unfortunately, it doesn't seem to be having any effect. Below is the HTML search ...

Verify the form data before triggering the ajax call with just one click

Ensuring that all required areas are completed in a form is crucial. The form needs to be validated properly to either reject the request with a message showing what information is missing, or submit it successfully... The rejection process works well as ...

Cannot utilize remote.require() in TypeScript due to compatibility issues

Recently, I've been facing a frustrating issue while developing an Electron application in TypeScript. I've been trying to execute a module from a renderer process using the code snippet below: import { remote } from 'electron' const ...

Is it a Mozilla Firefox glitch or something else?

After writing the code, I noticed a bug in Firefox and a small bug in Chrome. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> ...

Display the overlay solely when the dropdown is visible

My code works, but the 'overlay active' class only functions properly when I click on the button. If I click outside of the button, it doesn't work as intended. I want the 'overlay active' class to be displayed only when the dropd ...

Using NodeJS to extract information from Opendata JSON files

I'm currently working on a project that involves fetching JSON data from an Open Dataset using NodeJS and passing it to angular. The challenge I'm facing is that I'm receiving a JSON file instead of a JSON object, which makes it difficult to ...

"Safari (iOS) is experiencing a functionality issue where Alert() is working, but console.log() is

Just a heads up before you dive in: I've encountered an issue with Safari related to Chrome, but it seems to work fine on other browsers. So, it could be more OS-specific rather than a general problem. I recently ran into a frustrating situation whil ...

Troubleshooting a ThreeJS Issue: the Mystery of the Malfunction

I have a ribbon showcasing various thumbnails. These thumbnails are painted on a canvas and then added to a Texture. var texture = new THREE.Texture(textureCanvas); The mesh is generated as shown below loader.load('mesh_blender.js', functi ...

Searching for documents in MongoDB using minimum as a condition in the query

My user base is expansive, each facing a unique set of problems at different times. I am currently searching for users or documents that share a specific problem type (referred to as "top":1) but only among those, I am interested in isolating the entry wit ...

Is it possible to load a JS file using Node.js's `

Is there a way to load the contents of a js file into a variable without it returning as an object? How can I achieve this? server.js const file = require("./server/file.js"); ctx.body = `${file}`; // The expected output is "(function () { ...

Is there a way to create an HTML select element where each option has a unique background color, and will display properly

I want to create multiple HTML select elements with unique background colors for each option: <select runat="server" id="select"> <option value="A">White</option> <option value="B">Red</option> <option value="C">Yellow& ...

"Encountering a problem with the Flicker API while trying to view personal

I've been attempting to retrieve my personal photos using the following function with a node package obtained from this source https://www.npmjs.com/package/flickrapi\ When trying to access pictures of another user like 136485307@N06 (Apollo Im ...

Showing the unique identifier instead of the actual data in HTML for a Firebase Object using Angularfire

Currently, I am utilizing AngularFire for a specific project. The structure of my firebase Object is as follows: { mainKey: { key1:value1, key2:value2 }, mainkey2: { key3:value3 } } The data has been inputted in a manner tha ...

How come I am receiving a null value for isMatch from bcrypt compare even though the two password strings match exactly?

Currently, I am attempting to authenticate a user based on a password. My approach involves using bcrypt compare to check if the user's requested password matches one stored in a MongoDB database. Despite the passwords being identical, I keep receivin ...

shifting the length of o to the right by zero with the

While exploring the polyfill function for Array.includes, I stumbled upon the following lines of code: // 2. Let len be ? ToLength(? Get(O, "length")). var len = o.length >>> 0; // 4. Let n be ? ToInteger(fromIndex). // (If fromIndex is undef ...

Tips for automatically filling out a div class form:

I currently have an Autoresponder email form featured on my webpage. Here is a snippet of the code for the section where customers enter their email: <div id = "af-form-45" class = "af-form" > <div id = "af-body-45" class = "af-body af-standa ...

Caught up: TypeScript not catching errors inside Promises

Currently, I am in the process of developing a SPFx WebPart using TypeScript. Within my code, there is a function dedicated to retrieving a team based on its name (the get() method also returns a promise): public getTeamChannelByName(teamId: string, cha ...

Ways to display varied JSON information on a component in Angular 4

I am facing a challenge with a reusable component that fetches data from a JSON file. I want to customize the data displayed when this component is used as a subcomponent within other components. For example, let's say we have a Banana component: @U ...