Drew Drew - 1 year ago 90
Javascript Question

add variable to js from cli in webpack build

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

var myvar = {{set_from_cli}};

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

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.

Answer Source

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

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download