Can I re-create node_modules from package-lock.json?
I cloned a repository from github which has a package-lock.json (but no package.json). Then in a git bash terminal I go to the directory and run npm install
but I just get a message saying there is no package.json and then everything in package-lock.json gets deleted so it's basically empty except for the project name and version.
I thought running npm install
with a package-lock.json in the directory was enough to re-create node_modules, but am I seriously misunderstanding how this works? By the way I have node 8.12.0 and npm 6.4.1 and am running on Windows 10. Also, I think the package-lock.json was created on a unix system so could there be problems when using package-lock.json on a different OS?
I already tried running npm init
just to get a package.json file and then running npm install
but that still didn't get me a node_modules folder.
Starting from Mar 5, 2018, you can run npm ci
to install packages from package-lock.json.
npm ci bypasses a package’s package.json to install modules from a package’s lockfile.
https://blog.npmjs.org/post/171556855892/introducing-npm-ci-for-faster-more-reliable
package-lock.json
records the exact version and url of packages need to install, thus you can use npm to install them accordingly:
- npm can install from urls that point to tarballs
-
--no-package-lock
option to tell npm to not touchpackage-lock.json
file
For example, to install all packages in package-lock.json
:
cat package-lock.json | jq '.dependencies[].resolved' | xargs npm i --no-package-lock
jq
is a command line tool to pares jq
, you can write a simple JavaScript script to parse it instead (if you do not want to install jq
or learn jq's query syntax).
AFAIK, the package-lock.json
file relies on the presence of a package.json
file, so you'll not be able to recreate your node_modules
folder from the package-lock.json
file alone (happy to be proved wrong here).
Therefore, your best bet is to (mis)use a module like auto-install that is capable of generating the package.json
file based on a project's dependencies, as they appear in the files.
Install it globally (npm install -g auto-install
), then you'll need to generate an empty package.json
file for it to run (use npm init -y
in your project root). Kick things off with the command auto-install
and it should add the dependencies to the package.json
file.
HTH