Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to reference a property in package.json

Consider the following package.json:

{
  "name": "expressapp",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {        
    "dev": "./node_modules/.bin/nodemon app.js"
  },
  "author": "me",
  "license": "ISC",
  "dependencies": {
    "express": "^4.13.4",
    "mongodb": "^2.1.7"
  },
  "devDependencies": {
    "nodemon": "^1.9.1"
  }
}

Now I want to rename my app.js to index.js. So I have to edit that name at least in two different places: main property and dev property of scripts. Is it possible to reference the value of main property inside package.json?

like image 684
jstice4all Avatar asked Mar 13 '16 07:03

jstice4all


2 Answers

JSON itself doesn't support variables.

It's up to the program consuming JSON that can decide whether to treat any particular pattern as a variable or to be replaced with some other text somehow.

While other answers have mentioned using the $ or %% notation for variables (that are OS-dependent), I think you can also solve your problem in the following way:

Instead of nodemon app.js you can just write nodemon .:

"main": "app.js",
"scripts": {
  "dev": "nodemon ."
}

. will also automatically resolve to app.js

If you have a "main": "app.js" in package.json (in any folder, be it top level or sub folders) then any node process will identify the app.js file as the default one to load (either in require calls or executing via cli), just like it does index.js automatically.

like image 192
laggingreflex Avatar answered Oct 14 '22 17:10

laggingreflex


You can do it through environment variables

Under Linux

"scripts": {        
    "dev": "./node_modules/.bin/nodemon $npm_package_main"
  },

Under Windows

"scripts": {        
    "dev": "./node_modules/.bin/nodemon %npm_package_main%"
  },
like image 27
zangw Avatar answered Oct 14 '22 16:10

zangw