WittCode💻

package.json Variables

By

Learn how to use variables in the package.json file using the configs key. We will also learn how to set environment variables with package.json.

Table of Contents 📖

npm Variables

npm allows us to use variables in package.json scripts. This is done with the config key.

{
  "name": "npm-variables",
  "version": "1.0.0",
  "description": "",
  "main": "./src/index.js",
  "type": "module",
  "config": {
    "main": "./src/index.js"
  },
  "scripts": {
    "start": "node $npm_package_config_main"
  }
}

INFO: We can access the variable with $npm_package_config_VARIABLE where VARIABLE is the key in the config object.

Here, we setting the main entry point of our application as a variable. The config object is used to set configuration parameters in package scripts.

Practical Example

These parameters also get set as environment variables.

{
  "name": "npm-variables",
  "version": "1.0.0",
  "description": "",
  "main": "./src/index.js",
  "type": "module",
  "config": {
    "main": "./src/index.js",
    "cheese": "gouda"
  },
  "scripts": {
    "start": "node $npm_package_config_main"
  }
}
console.log(process.env.npm_package_config_main);
console.log(process.env.npm_package_config_cheese);
npm start
./src/index.js
gouda

This can be very useful for loading environment variables such as server locations.

{
  "name": "npm-variables",
  "version": "1.0.0",
  "description": "",
  "main": "./src/server.js",
  "type": "module",
  "config": {
    "main": "./src/server.js",
    "host": "localhost",
    "port": 3000
  },
  "scripts": {
    "start": "node $npm_package_config_main"
  }
}
import http from 'http';

const HOST = process.env.npm_package_config_host;
const PORT = process.env.npm_package_config_port;

const server = http.createServer((req, res) => {
  res.end('Hello, World!');
});

server.listen(PORT, HOST, () => {
  console.log(`Server running at http://${HOST}:${PORT}/`);
});