🔎 Discovering the NPM Lifecycle Event

☝️A useful variable for your npm scripts

Brian Han
2 min readMay 23, 2016

Yes, there’s the NODE_ENV variable for “development” and “production”.

But have you heard of npm_lifecycle_event? 🤔

It’s great because it gives you more options for how you write your npm scripts.

I love npm scripts, I use them all the time in all my projects. Whatever I decide to use as my build tool (gulp, webpack or whatever) will be abstracted to an npm script.

My convention is to have the following scripts in my package.json:

  • npm run build: run build scripts
  • npm run dev: run dev server
  • npm start: run production server

Now let’s talk about this one way to use npm_lifecycle_event — you can use this as a flag for running only certain parts of your code according to what npm script is executed.

Let’s say I have an example.js file that only writes certain strings to my console depending on what script I execute.

Here’s my example.js file:

Here’s my package.json file with my npm scripts:

Now take a look:

I can execute `npm run build` and I’ll only see `Running your build tasks!` printed to my console.

Cool, right?

This is a pretty contrived example but if you want to see this being used to greater effect, head on over to this great webpack tutorial I found: SurviveJS | Developing with Webpack.

You’ll find that it uses a helper called webpack-merge — this enables you to merge webpack configuration objects.

This is very interesting because you can break up a webpack configuration object into many parts and merge them together according to what npm script is being called.

If you’re like me and you’re learning webpack, the SurviveJS tutorial has been the smoothest learrning experience I’ve had as far as webpack resources go.

Hope this was useful for you as it was for me!

Thanks for reading and happy coding! 🎉

--

--

Brian Han

UX Developer @ Indeed // Previously: Accenture, IBM, Carbon Design System