Variables in package.json

10-31-2018

As a general rule of thumb for me, anytime I have to declare something more than a couple of times or change a value regularly I look to create a variable to hold that value. It helps me be consistent and reduce errors. It’s not often but sometimes my package.json could benefit from variables. Here’s how you can add variables to your package.json.

Let’s start with a simple package.json file.

package.json

1
2
3
4
5
6
7
8
9
10
11
{
"name": "my-test-app",
"version": "1.0.0",
"description": "",
"scripts": {
"client": "URL=http://192.168.1.120 PORT=9092 node client.js",
"server": "URL=http://192.168.1.120 PORT=9092 node server.js"
},
"author": "joe bag",
"license": "ISC"
}

I have two npm script commands that help me start a node process. Both commands pass the same URL and PORT environment variables. Since the values are the same and could potentially change in the future I want to abstract those into variables. To do that we can create a separate object in our package.json to hold the values called config. That object looks something like this:

package.json

1
2
3
4
5
...
"config": {
"port": "9092",
"url": "192.168.1.120"
}

To reference the variable contained in our new config object we need to first append $npm_package_ to the reference, then using _ we call drill down to the individual nested values. For example, to reference the port value we would call $npm_package_config_port.

Let’s take a look at the new package.json with the variables being used.

package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"name": "my-test-app",
"version": "1.0.0",
"description": "",
"scripts": {
"client": "URL=http://$npm_package_config_url PORT=$npm_package_config_port node client.js",
"server": "URL=http://$npm_package_config_url PORT=$npm_package_config_port node server.js"
},
"author": "joe bag",
"license": "ISC",
"config": {
"port": "9092",
"url": "192.168.1.120"
}
}