5

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

1 Answer 1

7

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)

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

5 Comments

Should be edited to mention that if you need windows support, you will have to use github.com/kentcdodds/cross-env.
instead of creating a whole new script file, you can just prepend environment variables to your npm run command: "build:prod": "NODE_ENV=production webpack"
You're close, but your code should be API_URL: JSON.stringify( process.env.URL ), to correctly answer the question
@DanO Good point. You could definitely put it in the command line of your scripts entry inside package.json to simplify it.
@AndyRay Sorry, was just trying to give a simple working 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.