Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

npm to create a package.json file out of the package-lock.json file?

I've got a project which happens to have a full node_modules directory, and a package-lock.json file, but no package.json file.

so I ran npm init to create a new package.json file, but now I'm struggling to make it contain the dependecies of the project.

Is there a way to make npm read the node_modules directory or the package-lock.json and create a matching package.json file?

like image 392
Efrat Levitan Avatar asked Dec 19 '18 20:12

Efrat Levitan


People also ask

Does package json generate package lock?

package-lock. json is automatically generated for any operations where npm modifies either the node_modules tree, or package. json . It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.

Does npm build use package lock json?

The package-lock. json file stores the version information of each installed package unchanged, and npm will use those package versions when running the npm install command.


1 Answers

The package-lock.json does not contain enough information to produce an accurate package.json file. It contains a list of all the package that are installed, and the version, but it also includes sub-dependencies in the list.

You could read the information and create a new dependencies list, but you would end up with a list of all the dependencies, including sub-dependencies you don't directly depend on. There would also be no distinction between dependencies and devDependencies.

Interestingly, npm does seem to be able to remember which packages were installed in a given directory for some amount of time (it's probably cached somewhere). If the lock file was originally created on your machine, a simple npm init might give you an accurate package.json file.

If you really want to produce a list of all the packages in a JSON format, you could use a script like this:

var dependencies = require('./package-lock.json').dependencies;
var list = {};

for (var p of Object.keys(dependencies)) {
    list[p] = dependencies[p].version;
}
console.log(JSON.stringify(list, null, '  '));
like image 146
Alexander O'Mara Avatar answered Oct 25 '22 01:10

Alexander O'Mara