Search code examples
node.jsnpmnode-gyp

npm package.json OS specific dependency


Is there a way to specify OS specific dependencies in a npm package.json file?

For example, I would only want to install 'dbus' (https://npmjs.org/package/dbus) as a dependency for my module if the user is running Linux. I would have a different dependency for Mac and Windows.


Solution

  • There's a possible good way of doing this, depending on your setup.

    npm package.json supports an os key,

    and also optionalDependencies

    • os can be used to specify which OS a module can be installed on.
    • optionalDependencies are module dependencies that if they cannot be installed, npm skips them and continues installing.

    In this way you can have your module have an optional dependency for each OS, and only the one which works will be loaded/installed ^.^

    EDIT: As @Sebastien mentions below, this approach is dangerous. For any given OS, at least one of your dependencies is "required" and the rest "optional". Making all versions of the dependency optional means that if your installation fails for a legitimate reason, it will silently skip installation and you will be missing a dependency you really need.