且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

npm从package-lock.json文件中创建一个package.json文件?

更新时间:2021-11-07 22:17:52

package-lock.json 包含的信息不足以生成一个准确的 package.json 文件。它包含已安装的所有软件包的列表和版本,但它还包括列表中的子依赖项。

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.

您可以阅读信息并创建一个新的依赖项列表,但最终会得到所有依赖项的列表,包括您不直接依赖的子依赖项。 依赖项 devDependencies 之间也没有区别。

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.

有趣的是,npm似乎能够记住在给定目录中安装了哪些软件包一段时间(它可能在某处缓存)。如果锁文件最初是在您的机器上创建的,那么一个简单的 npm init 可能为您提供准确的 package.json file。

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.

如果你真的想要生成一个JSON格式的所有包的列表,你可以使用这样的脚本:

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