redux-logger tree shaking not working

Issue

In projects using redux-logger, redux-logger still exists after packaging in Webpack production mode.

Theoretically, the logger should only be used in the development environment, so it should be removed after packaging. Therefore, with this question in mind, let’s analyze the problem.

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

Code Details

1
"redux-logger": "^3.0.6"

The relevant usage code is as follows:

1
2
3
4
5
6
7
8
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)));

Inside redux-logger

  1. "main": "dist/redux-logger.js".

Here are the main points to the entry file. The Main can point to an ES or CJS file, so this configuration is OK.

  1. The redux-logger.js file follows the UMD specification, which is compatible with CommonJS and AMD. Tree shaking under Webpack does not support UMD.

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

Based on the above situation, redux-logger cannot be tree-shaken, so the phenomenon meets expectations.

Upgrading redux-logger

1
"redux-logger": "4.0.0",

After checking NPM, we find that redux-logger has a beta 4.0 version that supports the ES specification, so let’s try it here.

If we only upgrade the package version and perform packaging tests, we’ll find it still doesn’t work, because Tree Shaking also requires sideEffects.

However, please note that the imported file has been changed to ES.

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

The package size is as follows:

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

Fixing redux-logger

To verify the effect, we manually added "sideEffects": false to the package’s package.json, republished the package, and then analyzed the packaging. The result is as follows.

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

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

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

At the end

At this point, the problem brought by redux-logger in production packaging has been solved.

Docs