redux-logger Tree Shaking Not Working

· 1 min read · 195 Words · -Views -Comments

Issue

Even in Webpack production builds, redux-logger sticks around. Since the logger is only needed in development, it should disappear. Let’s see why it doesn’t.

https://static.1991421.cn/2024/2024-09-14-152754.jpeg

Project Setup

"redux-logger": "^3.0.6"

Usage:

import { createLogger } from 'redux-logger';

const logMiddlewares = process.env.NODE_ENV === 'development'
  ? [createLogger({ collapsed: true })]
  : [];

const middleWares = [...logMiddlewares];

const store = createStore(
  createRootReducer,
  compose(applyMiddleware(...middleWares))
);

Looking into redux-logger

  1. "main": "dist/redux-logger.js" points at the distribution build. That’s fine—main can reference either CommonJS or ES modules.
  2. dist/redux-logger.js is a UMD bundle that works in CommonJS and AMD environments. Webpack cannot tree-shake UMD output.

https://static.1991421.cn/2024/2024-09-14-153225.jpeg

Given the UMD build, it’s expected that tree shaking fails.

Trying redux-logger 4.0 Beta

"redux-logger": "4.0.0"

A beta release on npm ships ES modules, so I tried upgrading. Packaging still retained the logger because tree shaking also requires the sideEffects flag.

On the plus side, the import now resolves to an ES module:

https://static.1991421.cn/2024/2024-09-14-153328.jpeg

Bundle size at this stage:

https://static.1991421.cn/2024/2024-09-14-153350.jpeg

Adding sideEffects

To confirm the fix, I republished the package with "sideEffects": false in package.json, then analyzed the build again.

https://static.1991421.cn/2024/2024-09-14-153416.jpeg

"redux-logger": "npm:@stacker/redux-logger@4.0.1"

https://static.1991421.cn/2024/2024-09-14-153451.jpeg

Final Result

With an ES module build and sideEffects declared, Webpack finally drops redux-logger from production bundles.

Reference

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover