Reputation: 1948
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?
Upvotes: 13
Views: 8372
Reputation: 3688
As of NPM 7 you can do it natively using npm-pkg.
e.g.
"start": "nodemon `npm pkg get main | tr -d '\"'`",
npm pkg get main
will give you "app.js"
tr -d '\"'
will remove the "quotes"Upvotes: 0
Reputation: 34667
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.
Upvotes: 5
Reputation: 75
Yes, you can reference to any field value from package.json
when executing scripts.
But there is a difference, when you run script under windows, you should use %npm_package_field%
and with unix based OS you should use $npm_package_field
.
Where field
is field name from package.json
.
Under windows, you can use:
"dev": "./node_modules/.bin/nodemon %npm_package_main%"
Under unix:
"dev": "./node_modules/.bin/nodemon $npm_package_main"
Upvotes: 1
Reputation: 48476
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%"
},
Upvotes: 16