There are two different situations where you run npm install
:
npm install
in your project's root directorynpm install
npm
runs the postinstall
script you specified in your package.json
.
npm
is aware of this difference, that's why it installs your devDependencies
in the first situation and skip them in the second situation.
I need to know about this in my postinstall
script, in order to run different steps for folks working directly on my module's code, rather than using my module as a dependency. Something like:
if (DEPENDENCY_MODE) {
// someone added me to their dependencies
// download a Minimal version of some binary
} else {
// I'm being developed by my maintainer
// download a Verbose version of some binary
}
Is there any Globals / Env variables that I can check to get this details?
I found a few solutions to distinguish between these two cases:
Compare npm_config_local_prefix
and npm_package_json
environment variables.
npm_config_local_prefix
contains the path the command is running at (same as process.env.INIT_CWD
). For example C:\app
.
npm_package_json
contains the path to the package.json
file of the package being installed at the moment. For example C:\app\package.json
OR C:\app\node_modules\my-package\package.json
.
if (process.env.npm_config_local_prefix === process.env.npm_package_json.slice(0, -13)) {
// this is the main project
} else {
// this is a dependency of another package
}
Check for the node_modules
directory, can be inaccurate in some cases.
const fs = require('fs');
if (fs.existsSync('../node_modules')) {
// this is a dependency of another package
} else {
// this is the main project
}