How to create shared package.json for multiple npm repositories

Unfortunately npm doesn't support specifying parent package.json file. Such feature was proposed some time ago, but npm maintainers come to conclusion that it should be achieved by external tools.

Of course you can write such tool yourself. There is one of possible aporaches:

  1. Create library which contains package.json file with all shared dependencies. In this example it will be called shared-deps.

  2. Create merge.js script which adds shared dependencies to local package.json file, and add it to shared-deps library:

    const fs = require('fs')
    
    const localPackageJson = require('../../package.json')
    const sharedPackageJson = require('./package.json')
    
    Object.assign(localPackageJson.dependencies, sharedPackageJson.dependencies)
    
    fs.writeFileSync('../../package.json', JSON.stringify(localPackageJson, null, 2))
    
  3. Add to package.json of app which will be using this shared dependencies following post-install hook:

    "scripts": {
       "postinstall": "node ./node_modules/a/merge.js"
    }
    
  4. Now, when you run npm install, your shared dependencies will be installed together with shared-deps library, and your package.json will be updated afterwards.



What if you create a new repository shared-dependencies with a package.json including all shared dependencies, then publishing it in npm.

After that you would be able to do npm i shared-dependencies on each main project therefore you'll have access to all shared dependencies.

Tags:

Node.Js

Npm