Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Npm: Run postinstall script only when installed as dependency

I developed a npm package ("node_commons") which is included in my other project like this:

package.json (other project)

"node-commons": "git+ssh://[email protected]:7999/npm/libs/node_commons.git"

The node_commons package is written in ES6 but this version is not supported later, therefore I use a postinstall script to transpile it with babel.

package.json (node_commons)

"postinstall": "babel src -d src"

This works fine. When the package is included as dependency in my project, the files are transpiled.

My problem: When I develop the node_commons package I use npm install to install the internal dependencies. But then I do not want to transpile it. I only want to transpile, when the package is installed as dependency (e.g. in my other project). Is there a way to do this?

Something like this:

package.json (node_commons)

"postinstall-as-dependency": "babel src -d src"
like image 390
Kewitschka Avatar asked Jan 16 '19 07:01

Kewitschka


2 Answers

In my case, I had a postinstall script that I only wanted to run when the package was NOT installed as a dependency.

Here is the package.json script I used:

{
    [...]
    "scripts": {
        "@comment_postinstall": "Behavior of the node-js subscript below: if '.git' doesn't exist under my-lib, it's installed as a dep, so do nothing -- else, return error-code 1, causing patch-package to run.",
        "postinstall": "node -e \"let myLibAsDep = !require('fs').existsSync('.git'); if (!myLibAsDep) process.exit(1);\" || patch-package"
    },
    [...]
}

You can of course just reverse the if (!myLibAsDep) if you want your script to run only when installed as a dependency.

like image 98
Venryx Avatar answered Nov 04 '22 19:11

Venryx


If I understand correctly, you want your package to run a postinstall script only if user install it as a dependency (npm install node-common)?

When your postinstall script runs, it has the npm_config_save_dev available to it, which is 'true' when users install the package with the --save-dev flag:

"postinstall": "! [ $npm_config_save_dev ] && echo \"Installed as a dependency\" || \"Installed as a dev dependency\""
like image 23
Derek Nguyen Avatar answered Nov 04 '22 17:11

Derek Nguyen