Recognized by Clutch.co as a top-rated Mobile App Development Company.
folio3-mobile
US 408 365 4638
START YOUR PROJECT
  • Solutions
    • Apps Discovery Services
    • Team Augmentation
    • Enterprise
    • AR/VR
    • IoT
    • Wearables
    • Field Sales
    • On Demand Apps
  • Industries
    • Retail
    • Agriculture
    • Healthcare
    • Pharmaceutical & Life Sciences
    • Manufacturing
    • Automotive
    • Logistics
    • Education
  • Technologies
    • Native Mobile Apps
      • iOS
      • Android
    • Cross Platform Apps
      • React Native
      • Flutter
      • Ionic
      • Xamarin
      • NativeScript
      • Sencha
  • Portfolio
  • Blog
  • Contact Us
  • Solutions
    • Apps Discovery Services
    • Team Augmentation
    • Enterprise
    • AR/VR
    • IoT
    • Wearables
    • Field Sales
    • On Demand Apps
  • Industries
    • Retail
    • Agriculture
    • Healthcare
    • Pharmaceutical & Life Sciences
    • Manufacturing
    • Automotive
    • Logistics
    • Education
  • Technologies
    • Native Mobile Apps
      • iOS
      • Android
    • Cross Platform Apps
      • React Native
      • Flutter
      • Ionic
      • Xamarin
      • NativeScript
      • Sencha
  • Portfolio
  • Blog
  • Contact Us

What is Tree Shaking and Implementation in React

Published by: Muhammad Saqlain | December 2, 2020
SCROLL AND BE AMAZED!
Home > React Native > What is Tree Shaking and Implementation in React

Reduced size of application & improved performance plays an important role in success of a software. Tree Shaking is a concept in development of eliminating dead code or unused code.

Imagine your application as a tree. All the libraries, components, widgets & code represents leaves. All the unused code, imports & dead code represents the dead brown leaves. In order to clear dead leaves from trees you have to shake the tree to let them fall.

By implementing tree shaking practices website performance will get improved and reduce bundle size. Tree shaking depends on the static structure of ES6 module syntax (import & export).

The reason tree shaking is very important is because most packages installed don’t really need all dependencies & this results in importing full packages, however what really needed is a small part of that package.

Lets have an example:

Importing lodash package using CommonJS Module. This import will fetch entire package & all the un required dependencies.

const lodash = require('lodash'); 70.7K (gzipped: 24.7k)

Importing lodash package using ES6 (ES2015) Module. This import will only fetch specific dependency with tree shaking.

import {isArray} from 'lodash'; 1K (gzipped: 505)

As seen in example above the size of bundle is drastically reduced in ES6 import as compared to CommonJS module import.

Tree Shaking in React Application

If your project is built with create-react-app, the latest version has excellent tree shaking, if you are using an old version of react just update react-scripts to version 2.0.4 or higher.

npm install react-scripts@latest --save

In order to implement tree shaking in react application you will need to have a module bundler that will bundle the entire app’s code. You can either use WebPack or RollUp for bundling your application.

Webpack

webpack is an open-source JavaScript module bundler. It is made primarily for JavaScript. Webpack takes modules with dependencies and generates static assets representing those modules. Webpack uses the babel-preset-env package, which bundles your files and transforms the files back to CommonJS module to support tree-shaking.

To achieve tree shaking, webpack requires some configuration. Create a file name webpack.config.js and add below code:

module.exports = {
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: babel-loader,
          options: {
            presets: [
              [ 'es2015', { modules: false }]
            ]
          }
        }
      }
    ]
  }
}

Configure the file in side-effect

A Side-effect is defined as code that performs a special behavior when imported, other than exposing one or more exports. Side effects occur when a function or expression modifies state outside its own context. 

If all of application code does not contain side effects, we can simply mark the property as false to inform webpack that it can safely prune unused exports.

{
  "name": "example-project",
  "sideEffects": false
}

If your code have some side effects, an array can be provided in configuration instead:

{
  "name": "example-project",
  "sideEffects": [
    "./src/file-with-side-effect.js",
    "*.css"
  ]
}

Rollup

Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application. It uses the standardized ES module format for code, instead of previous idiosyncratic solutions such as CommonJS.

If you are using Rollup as your module bundler then by default it supports tree-shaking and does not require any additional configuration. Rollup statically analyzes the code you are importing, and will exclude anything that isn’t actually used. This allows you to build on top of existing tools and modules without adding extra dependencies or bloating the size of your project.

For example, while using CommonJS, the entire tool or library must be imported.

// import the entire utils object with CommonJS
const utils = require( './utils' );
const query = 'Rollup';
// use the ajax method of the utils object
utils.ajax(`https://demoapi.com?search=${query}`).then(handleResponse);

we can just import the one ajax function we need:

// import the ajax function with an ES6 import statement
import { ajax } from './utils';
const query = 'Rollup';
// call the ajax function
ajax(`https://demoapi.com?search=${query}`).then(handleResponse);

Conclusion

By implementing tree shaking practices website performance will get improved and reduce bundle size. Therefore we strongly recommend to implement tree-shaking practices while development.

Do you know any other tip/trick to implement tree shaking in React. Do let us know in comment section.


About msaqlain

A hardworking and dedicated individual, determined on the road to success, ever ready to take on challenges and accomplish what I set out to achieve.

Newsletter

Search

Archives

  • December 2023
  • April 2023
  • March 2023
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • April 2022
  • March 2022
  • February 2022
  • October 2021
  • September 2021
  • May 2021
  • February 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • May 2020
  • April 2020
  • March 2020
  • February 2020
  • January 2020
  • December 2019
  • November 2019
  • October 2019
  • September 2019
  • August 2019
  • July 2019
  • May 2019

Recent Posts

  • Exploring Flutter Navigation: From Basics to Advanced Routes
  • Web UI Test Automation with Pytest-BDD
  • How to fix IOS compass calibration issues
  • Testing Android Applications With Perfect Coverage
  • How to use useRef hook efficiently? – React

Tags

  • android
  • angular-state-management
  • Automation
  • Compass
  • cross-platform
  • css
  • development
  • firebase
  • hooks
  • ios
  • learn-ngrx
  • ngrx-beginner
  • ngrx/store
  • QA
  • react-native
  • reactjs
  • scss
  • stylesheet
  • styling
  • Testing
  • Test Script
  • UI-UX

Newsletter

Newsletter

Post navigation

Previous Vue VS. React – Crowning the King of Web App Development in 2021
Next One codebase to rule them all – Sharing code in mobile & web apps using Flutter
Schedule an Appointment with our Mobile App Development Expert
Footer Menu
  • Company
    • About Us
    • Portfolio
    • Blog
    • Careers
    • Contact Us
  • Solutions
    • Apps Discovery Services
    • Team Augmentation
    • Enterprise App Development
    • AR/VR Application Development
    • IoT Application Development
    • Wearables Apps Development
    • Field Sales
    • On-Demand Apps Development
  • Technologies
    • iOS
    • Android
    • React Native
    • Flutter
    • Ionic
    • Xamarin
    • NativeScript
    • HTML5
    • Sencha
  • Industries
    • Retail
    • Agriculture
    • Healthcare
    • Pharmaceutical
    • Manufacturing
    • Automotive
    • Logistics
    • Education

US Office

Belmont, California – 1301 Shoreway Road, Suite 160, Belmont, CA 94002

Pleasanton, California – 6701 Koll Center Parkway, #250 Pleasanton, CA 94566

Tel: +1 408 365 4638
Support: +1 (408) 512 1812

Mexico Office

Amado Nervo #2200, Edificio Esfera 1 piso 4, Col. Jardines del Sol, CP. 45050, Zapopan, Jalisco, Mexico

Bulgaria Office

49 Bacho Kiro Street, Sofia, 1000, Bulgaria

Canada Office​

895 Don Mills Road, Two Morneau Shepell Centre, Suite 900, Toronto, Ontario, M3C 1W3, Canada

UK Office

Export House, Cawsey Way, Woking Surrey, GU21 6QX

Tel: +44 (0) 14 8361 6611

UAE Office

Dubai, UAE – Dubai Internet City, 1st Floor, Building Number 12, Premises ED 29, Dubai, UAE

Tel: +971-55-6540154
Tel: +971-04-2505173

Pakistan Office

Folio3 Tower, Plot 26, Block B, SMCH Society, Main Shahrah-e-Faisal, Karachi.

First Floor, Blue Mall 8-R, MM Alam Road Gulberg III, Lahore.

Tel: +92-21-3432 3721-4 

© 2025, Folio3 Software Inc., All rights reserved.

  • Privacy policy and terms of use
  • Cookie Policy
Follow us on
Facebook-f Linkedin-in Instagram

Get a free app audit

[contact-form-7 id="3548" title="Float Banner Form"]