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?
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.
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.
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, ' '));
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