5

Let's say I have something like:

{
  "scripts": {
    "clean": "some-clean-script",
    "prebuild": "npm run clean",
    "build": "some-build-script"
  }
}

Inside my some-clean-script (which is written in NodeJS), I want to know if the script is running as part of the prebuild or was called directly.

How do I do that?

0

1 Answer 1

7

There is a variable under env.process called npm_lifecycle_event that stores the key indicating the name of the script in package.json. So in your case, you can just check if process.env.npm_lifecycle_event === 'clean'.

For example, I run the following configuration:

{
  "name": "npm-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "pretest": "node test.js",
    "test": "node index.js", 
    "posttest": "node test.js"
  },
  "author": "",
  "license": "ISC"
}

test.js content:

console.log(process.env.npm_lifecycle_event)

and the output of the command npm test:

> [email protected] pretest /Users/bartlomiejgladys/Desktop/programming/npm-test
> node test.js

pretest

> [email protected] test /Users/bartlomiejgladys/Desktop/programming/npm-test
> node index.js

hi

> [email protected] posttest /Users/bartlomiejgladys/Desktop/programming/npm-test
> node test.js

posttest
Sign up to request clarification or add additional context in comments.

3 Comments

That did not work; I tried npm run clean and npm run build and in both cases, the process.env. npm_lifecycle_event which is inside some-clean-script, it printed clean.
ohh, now i see - It's gonna work only if you define your prebuild as "prebuild":"some-clean-script" instead of "prebuild":"npm run clean".
Thanks, ya that does answer the question. I've marked this as a solution. Thanks for your help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.