npm to create a package.json file out of the packa

2019-06-21 08:39发布

问题:

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?

回答1:

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