How to compile test-only code with webpack


5 weeks ago


49 time


I have a few private methods that I want to write unit tests for. However, since these are private methods, they are not exported.

This article shows how you can use grunt to wrap a code in comments and this code will be excluded from compiling if you are compiling for production.

Is there a similar thing for Webpack? Basically I want something so I can do something like

/* test-only */
export {_myPrivateMethod};
/* end-test-only */

And this code will be excluded from the final compiled, but will be included when running tests.

1 answers


Ideally, you would not test private functions directly. It is better to gain the coverage of those functions by executing them via your public API.

However, if you really wanted to, you could perform a production build to optimize out the code that you wanted to omit. It would look something like this:

if (process.env.NODE_ENV !== 'production') {
    // this code will not appear in a production build

This works because webpack automatically defines process.env.NODE_ENV when you do a production build and will be optimized out of the bundle. If you wanted to get fancy, you could define your own variables using the DefinePlugin and do a similar check.

You can read more here: and here: