Include CLI input into JavaScript variable within the Webpack build process

I am currently attempting to incorporate a variable into my app.js file during the build process. For instance:

//app.js
var myvar = {{set_from_cli}};

Afterwards, I would like to execute something such as webpack -p --myvar='abc' which would produce the following output:

//bundle.js
var myvar = 'abc';

I have conducted some research but so far have not been able to find the right solution or terminology to achieve this. Any help is greatly appreciated.

Answer №1

To access the variable myvar in your webpack.config.js file, you can do so using this code snippet (assuming you have installed minimist):

var argv = require('minimist')(process.argv.slice(2));
console.log(argv.myvar);

If you want to include it in your bundle, you can utilize the DefinePlugin. This is how you would define it within your plugin:

plugins: [
    new webpack.DefinePlugin({
      MYVAR: JSON.stringify(argv.myvar)
    })
]

Then in your code, you can access the variable like this:

var myvar = MYVAR;

Make any necessary adjustments as needed.

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

Unveiling the method to fetch the emitted value from a child component and incorporate it into the parent component's return data in Vue

How can I retrieve the title value passed by the Topbar component and incorporate it into the data() return section? I attempted to create a method to pass the value, but was unsuccessful despite being able to successfully log the value in the parent file. ...

Issue with jquery .click function not triggering after CSS adjustment

In the process of creating a fun game where two players take turns drawing on a grid by clicking <td> elements. Currently, I have implemented the functionality to toggle the background color of a <td> element from black to white and vice versa ...

Linking the value of an expression to ngModel

There is a specific scenario where I need the ng-model property to bind to a value retrieved from the database as part of the business logic. To illustrate this concept, I have set up an example function TodoCtrl($scope) { $scope.field1 = "PropertyFr ...

The Concept of Long Polling and How it Impacts Server Function

After spending a significant amount of time working with PHP, I recently discovered the concept of long polling as an alternative to sending periodic ajax requests. I've realized that sending periodic ajax can be resource-intensive, especially when c ...

What could be causing the issue of why the null check in JavaScript isn't functioning properly

function getProperty(property) { console.log(localStorage[property]) //Displays “null” if(localStorage[property] == null) { console.log('Null check') return false; } return localStorage[property]; } The log outputs "nu ...

Creating a Copy of an Object in JavaScript that Automatically Updates When the Original is Changed

I am in the process of developing a planner/calendar website with a repeat feature. var chain = _.chain(state.items).filter({'id': 1}).head().value(); console.log(chain); After filtering one object, I am wondering how to create a duplicate of c ...

Is there a way to link Dom $(this) from a different function?

Could you please review this code and advise on how I can bind $(this) in an external function within a DOM event? $(".adder").on("click", function(){ updateText(); }); function updateText(){ $(this).next(".mapper").html("Got You!"); } <scrip ...

Creating a button that integrates an image within a single div element

Currently, I understand the code: $('#leftDev').css("background-image", "url(img/1.png) "); will set the entire background of my leftDiv to display "1.png". However, I would like to position this image as a regular picture within the div and no ...

The property 'caseSensitive' is undefined and cannot be read

After creating a simple code, I am puzzled by an error message that seems to be case sensitive. However, the code appears correct based on my understanding. Here is the code snippet: App.js const express = require('express'); const path = requir ...

Transform User's Regex Output into Uppercase

My nodejs program allows users to input text and apply their own regular expressions for editing. I want users to have the option to capitalize or lowercase text as well. For example, if a user enters "StackOverflow is great!" with the regex (.) set to be ...

Error encountered in Angular $injector:unpr while attempting to initialize uibModal

I followed the ui-bootstrap tutorial to create my code. On my homepage, there is a button that triggers a modal window to open using ng-click. However, when I check the dev tools, I encounter the following error: Error: [$injector:unpr] Unknown provider: ...

When there are numerous websocket connections in Google Chrome, Socket.io can encounter issues and break down

I am encountering an issue where I create 60 client connections to a socket.io server using Google Chrome browser. The server sends screenshots to the clients at specific times, but some of the websocket connections, which are subprotocols of socket.io, ge ...

Are there any guidelines or rules outlining what is still considered valid JSONP?

I am looking for information on how to properly parse JSONP messages in .NET and extract the JSON data they contain. Is there a current specification that outlines what constitutes a valid JSONP message? During my research, I came across a blog post from ...

Can you explain the distinction between Vue's 'v-on' directive and vue.$on method?

If I have two sibling components set up like this: <div id="root2"> <some-component>First</some-component> <some-component>Second</some-component> </div> ... and these components are coded as follows: Vue.comp ...

Angular image source load test encountered an error

<div class="col-xs-4 col-sm-4 col-md-4"> {{jsonData[current].profilepic}} <div ng-if=IsValidImageUrl(jsonData[current].profilepic)> <img id="pic" ng-src="{{jsonData[current].profilepic}}" alt=""/> </div> < ...

What is the technique for incorporating FontAwesome icons onto an HTML 5 canvas?

I am encountering an issue while trying to use FontAwesome icons within my HTML 5 canvas. Here is what I have attempted: ct.fillStyle = "black"; ct.font = "20px Font Awesome"; ct.textAlign = "center"; var h = 'F1E2'; ct.fillText(String.fromCha ...

What is the method for specifying a JSON object within a DOM element's `data` attribute?

In an attempt to store JSON data within a dataset attribute, I encountered the following HTML structure: The appearance of the HTML is as follows <div data-switch="true" data-json="{'key1': 'value 1'}, {'key2': 'valu ...

Choosing a single random key-value pair from a specific attribute within a JSON schema

Is there a way to generate a new JSON schema based on the existing one, but with only one key-value pair chosen randomly from the "properties" attribute? The new schema should retain the "title" and "type" attributes as well. { "title": "animals object" ...

Ways to position loading animation in the center and create a lightbox effect for the rest of the page

I have implemented a custom loader in CSS with the following styles: .loader { border: 16px solid #f3f3f3; /* Light grey */ border-top: 16px solid #3498db; /* Blue */ border-radius: 50%; width: 80px; height: 80px; animation: spin 2s linear inf ...

Display JSON on the screen so it can be easily copied and pasted

I have a unique challenge where I need to output some Javascript code on the browser screen for easy transfer to another program. Currently, I am utilizing JSON.stringify() from the json2.js library. However, this method is not correctly escaping characte ...