12

How can I tell npm to use another package.json when running "npm install" ?

All I need is npm install -f packages-win32.json Or is there a trick or another approach to achieve the same?

Because not all npm modules are cross-platform and I'd like to use other packages per platform.

Ajay2707
  • 5,690
  • 6
  • 40
  • 58
xamiro
  • 1,391
  • 1
  • 16
  • 32
  • 1
    You can install all the dependencies in all the platform, and inside your code and require them based on the platform. Another option, is to install them inside your code like [This Example](http://stackoverflow.com/questions/27722576/can-i-specify-optional-module-dependencies-in-npm-package-json). Or to use dev-dependencies. – Ziki Nov 20 '15 at 12:43
  • 1
    I think the cleanest approach would be to publish a package to npm that contains the logic of using one package or the other based on the platform. That said you can just save both package.json files and use a source control hook that renames the correct one based on the platform. – Benjamin Gruenbaum Nov 20 '15 at 12:56
  • 2
    Possible duplicate of [Use different filename for npm than "package.json"](http://stackoverflow.com/questions/25991082/use-different-filename-for-npm-than-package-json) – ishandutta2007 May 14 '17 at 20:19
  • Looks like duplicated by https://stackoverflow.com/questions/15176082/npm-package-json-os-specific-dependency/26069595 – popigg May 25 '17 at 15:47

2 Answers2

2

You cannot specify a different package.json file as the specs are literally only for a file called package.json.

If you have some issues with packages that only work on either os try them out with

try {
  thing = require('thing');
}
catch( error ) {
  thing = require('other');
}

You can also sniff out the os via:

const _isWin = /^win/.test( process.platform );

Or use os.platform() if you don't have to support node <= 5...

Maybe that helps?

Dominik
  • 6,078
  • 8
  • 37
  • 61
1

The npm command doesn't allow specifying a specific package.json file but here's work-around to install specific or all package.json files:

Create npm-install.sh file with the source below and run with this command:

source npm-install.sh

or:

bash npm-install.sh

#!/bin/bash
set +ex;

cp -f package.json temp;
echo "Installing all package-*.json...";

for File in *.json; do
  echo -e "\nFile: $File";
  mv -f $File package.json;
  npm install;
done

cp -f temp package.json;
rm -f temp;
#EOF
Dee
  • 7,455
  • 6
  • 36
  • 70