When you install an npm package and use the --save
, --save-dev
or --save-optional
options to write the package into your package.json file in the appropriate dependencies property, the entire file appears to be rewritten with 2-space indentation:
$ cat package.json
{
"name": "my-package"
}
$ npm install --save another-package && cat package.json
{
"name": "my-package",
"dependencies": {
"another-package": "~0.1.5"
}
}
Is there any way to make npm follow the existing format, or to specifiy a custom format (e.g. 4-space indentation) for the package.json file?
I can't find anything in the npm options documentation.
Install the dependencies to the local node_modules folder. In global mode (ie, with -g or --global appended to the command), it installs the current package context (ie, the current working directory) as a global package. By default, npm install will install all modules listed as dependencies in package. json .
npm ci will install packages based on package-lock. json file and if the file does not exist or does not match the packages specified in the package.
json, you can re-run npm init -y and the repository field will be added automatically to your package. json.
All npm packages contain a file, usually in the project root, called package. json - this file holds various metadata relevant to the project. This file is used to give information to npm that allows it to identify the project as well as handle the project's dependencies.
After digging through the npm source, it unfortunately appears the answer to my question is definitely "no". When npm install
is executed with one of the "save" options, the following happens:
fs.readFile(saveTarget, function (er, data) {
try {
data = JSON.parse(data.toString("utf8"))
} catch (ex) {
er = ex
}
// ...
data = JSON.stringify(data, null, 2) + "\n"
fs.writeFile(saveTarget, data, function (er) {
cb(er, installed, tree, pretty)
})
})
The important line is the call to JSON.stringify
. When invoking stringify
with the third argument, the returned string indentation is formatted with the specified number of spaces.
Since there is no way to customise the value used by npm internally, this behaviour is currently non-configurable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With