Hemanth's Scribes

node

npm --save to Create package.json

Author Photo

Hemanth HM

Thumbnail

Until npm automatically creates package.json with --save, add this to your shell’s rc file:

function npms() {
  [[ -f ./package.json ]] || echo {} > package.json && npm install --save $*
}

This adds to package.json in the current directory, creating one if not found.

The Problem

Currently, npm install --save adds the dependency to the nearest package.json, searching up the directory tree. This can lead to dependencies accidentally being added to the wrong package.json.

npm also uses the real directory when handling symlinks, so if you’re calling npm install --save from inside a symlinked dir, it’ll find and add the dep to the package.json in the parent real directory.

The suggestion of calling npm init on missing package.json makes a lot of sense if install logic always just looked in the current working directory.

#node#npm
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.