Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make npm install follow a certain package.json format?

Tags:

node.js

npm

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.

like image 717
James Allardice Avatar asked Sep 02 '13 10:09

James Allardice


People also ask

Does npm install modify package json?

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 .

Does npm install look at 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.

Does npm install automatically add to json?

json, you can re-run npm init -y and the repository field will be added automatically to your package. json.

How does npm work with 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.


1 Answers

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.

like image 159
James Allardice Avatar answered Nov 02 '22 12:11

James Allardice