Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables from NPM Scripts to Webpack

I have a production build with Webpack that uses node's process.env to set environment variables:

webpack.prod.babel.js:

const DefinePlugin = new webpack.DefinePlugin({
  'process.env': {
    NODE_ENV: JSON.stringify('production'),
    API_URL: JSON.stringify('https://myprodurl.com'),
  },
});

packge.json:

"scripts: {
  "build:prod": "webpack"
}

It's working fine, but I need something different.

I need to set the production url as variable in the NPM Script.

So, instead of this:

npm run build:prod

I need this:

npm run build:prod --URL https://myprodurl.com
like image 949
Matheus Lima Avatar asked Mar 11 '23 14:03

Matheus Lima


1 Answers

How about defining your environment variable in the command line, like:

URL=https://myprodurl.com npm run build:prod

I tested this with a simple script and was able to print out the URL.

"scripts": {
  "test": "./myTest.js"
},

myTest.js:

#!/usr/local/bin/node

'use strict'

console.log(process.env.URL);
console.log('Done!');

then:

$ URL=https://whatever.com npm run test

> [email protected] test /Test/my-test
> ./myTest.js

https://whatever.com
Done!

EDIT: As mentioned by @RyanZim, see the following for Windows: https://github.com/kentcdodds/cross-env
(disclaimer: I don't use Windows and have never tried this lib)

like image 111
Jeff Kilbride Avatar answered Mar 19 '23 15:03

Jeff Kilbride