Why does webpack only fail when executed with 'npm run'?

Configuring and debugging build systems is often time consuming, stressful, and the end is often unsatisfying. If your webpack build is failing but not telling you why, then hopefully I can help you get back to coding. Tl;dr: use the --display flag with the CLI if you need to see output.

In my case, I was building a new React app from scratch, but when I tried to finally build the bare bones of it, I saw this:

That's not very helpful! A bundle.js file was being created, even though webpack failed; of course I had to get to the bottom of this.

The community's workarounds

I came across this discussion on GitHub, Webpack fails only when run through npm run command. The original poster said that the build actually succeeds if run directly from the command line. I tried it, and it seemed to solve the problem - it would create a bundle.js just like before, but this time no error messages!

Additionally, @michaelalbers(https://github.com/michelalbers) had this idea:
"I just added -f to the npm run command. It seems webpack outputs to stderr for some reason and npm interprets that as exit code 2. Weird."

This worked as well, npm happily executed webpack, with just an ominious warning at the beginning,

Though it seems that we're now able to build without errors, both with and without npm, something is amiss. We shouldn't have to force npm to continue through errors, and it still doesn't make sense that webpack would only fail when run through npm. Accepting the use of --force to workaround the webpack build issue would be very dangerous, even more so because we don't even know <i>what</i> errors we are skipping.. Even if you are happy to skip the errors you see today, you may introduce another error in the future, and you might not know right away because npm isn't reporting errors to you anymore.

Finding a flag for build information

I was confused why webpack wasn't giving any kind of output at all, no errors or error log to be found. Luckily, there is a --display flag for the CLI with following options: verbose, detailed, normal, minimal, errors-only, none

Running with the --display flag

Showed me that webpack actually had a good reason for exiting with status 2 before!

After resolving this and other reported errors, webpack was building without complaint from npm. It's important as a developer to have the desire to get to the bottom of an issue, even if you have a solution that seems to work around the issue. Of course, it's typical not to have the freedom to follow your desires. Sometimes these rabbit holes of curiosity can endure longer than a manager's patience.

Leave a Reply

Your email address will not be published. Required fields are marked *