'How to perform tree shaking for lodash in a create-react-app project?
I need to perform tree-shaking to reduce bundle sizes where lodash and some other libraries are being used.
I've converted all lodash imports like this:
import {isEmpty} from "lodash";
But still bundle size is not getting reduced.
To use plugins like 'lodash-webpack-plugin
', we need to configure in webpack.config.js
, which is not possible in a create-react-app project. I tried using react-app-rewired
but getting issues like:
screenshot of error
Following versions are being used in the project:
- react-scripts: 3.4.1
- webpack: 4.42.0
- react: 16.13.1
- lodash: 4.17.15
Solution 1:[1]
Webpack can perform tree shaking automatically when ES6 modules(import/export syntax) are used.
Looks like lodash is built to use Common-JS modules.
So you can use single export and cherry-pick methods to reduce size of bundle:
import isEmpty from "lodash/isEmpty";
With this import, only isEmpty function will be included in your bundle.
Alternatively, you can try to use lodash-es written in ES6
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nazar |