What is Tree Shaking ?
In the world of app development, performance is paramount. Users expect fast and efficient applications that load quickly and respond without any hiccups. To achieve this, developers often employ various optimisation techniques to reduce the size of their codebase and minimise the amount of unnecessary code loaded by the application. One such technique is tree shaking, a method that has gained popularity in recent years. In this blog, we’ll explore what tree shaking is, how it works, and why it’s a valuable tool in building leaner and faster apps.
Tree Shaking in Flutter
Flutter Dependency Management: Flutter apps are primarily written in Dart, a language that supports tree shaking. In a Flutter app, you manage your project’s dependencies through the pubspec.yaml
file. This file specifies the packages your app relies on, and Dart’s package manager, pub
, handles the installation and management of these dependencies.
Unused Code Detection: Tree shaking in Dart and Flutter works by detecting and eliminating unused code during the build process. The Dart compiler analyzes your code, starting from the entry point (typically the main.dart
file), and traverses the codebase to determine which functions, classes, or variables are actively used and which ones are not.
Dead Code Elimination: Dead Code Elimination involves the removal of any code that is neither directly nor indirectly accessed from the application’s entry point. This encompasses functions, classes, and variables that have no relevance to the app.
Tree Structure: It signifies the methodology of “tree shaking” as it revolves around navigating the code’s dependency structure. In this process, extraneous branches and leaves of the tree are trimmed, leaving behind only the essential components.
Optimizing Resources: Tree shaking not only applies to Dart code but also to resources like images, fonts, and other assets. Unused assets are also removed from the final build, reducing the app’s size.
Flutter Build System: Flutter’s build system, driven by the flutter build command, is responsible for invoking the Dart compiler and performing the tree shaking process. It generates optimized binary code for the target platform.
Using –tree-shake-icons: In Flutter, you can enable tree shaking for icon assets, which are included in your app through Flutter’s Icons class. By adding the –tree-shake-icons flag to your build configuration, Flutter will only include the icons that your app uses, thus reducing the size of your app bundle even further.
In conclusion, tree shaking is a valuable optimization technique in Flutter, helping developers create efficient and performant applications by automatically removing unused code and assets from the final bundle. When used wisely and in combination with other best practices, tree shaking can lead to smaller, faster, and more maintainable Flutter apps.