1

I'm trying to add a variable to my app.js at the time of build. For example:

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

then I want to run something like webpack -p --myvar='abc' which would result in this:

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

I've searched and maybe I'm just not looking in the right places or using the right terms, but can't figure out how to do this.

1 Answer 1

1

You can access myvar at webpack.config.js like this (assuming minimist):

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

To get it to your bundle, you can use the DefinePlugin. You would need to have something like this at your plugin definition:

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

Then at code

var myvar = MYVAR;

Adjust as necessary.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank for the reply, I added those first two codeblocks to my webpack.config.js but now when I try to run webpack -c tester I get: Error: Cannot resolve module 'tester'
nevermind, had to add it at the right place (updated your example)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.