简体   繁体   中英

Is there a way to extract package.json from package-lock.json?

I'm working on a project in which the package.json file is missing. The developer has pushed the package-lock.json file without the package.json file.

How can I create a clean package.json from the package-lock.json file in case it is at all possible?

It's not possible to generate full package.json from package-lock.json because the latter doesn't contain all necessary data. It contains only a list of dependencies with specific versions without original semvers. Production and development dependencies are mixed up along with nested dependencies.

Fresh package.json could be generated, then augmented with these dependencies with something like:

const fs = require('fs');
const packageLock = require('./package-lock.json');
const package = require('./package.json');

package.dependencies = Object.entries(packageLock.dependencies)
.reduce((deps, [dep, { version }]) => Object.assign(deps, { [dep]: version }), {});

fs.writeFileSync('./package-new.json', JSON.stringify(package, null, 2));

Nested dependencies could be filtered out by checking requires key, but this can affect project's own dependencies.

Simply run npm init and it will pull all of the current dependencies from package-lock.json if you already have node_modules/ generated. If not, run npm ci to generate the node modules from the package-lock.json and then run npm init to generate the package.json file.

Slightly improved version of accepted answer script. Will pull locked versions out of the package-lock.

const fs = require('fs');
const packageLock = require('./package-lock.json');
const package = require('./package.json');

package.dependencies = Object.keys(package.dependencies)
.reduce((deps, dep) => Object.assign(deps, { [dep]: packageLock.dependencies[dep].version }), {});

package.devDependencies = Object.keys(package.devDependencies)
.reduce((deps, dep) => Object.assign(deps, { [dep]: packageLock.dependencies[dep].version }), {});

fs.writeFileSync('./package-new.json', JSON.stringify(package, null, 2));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM