{"id":14692,"date":"2023-10-17T10:00:27","date_gmt":"2023-10-17T04:30:27","guid":{"rendered":"https:\/\/code4developers.com\/?p=14692"},"modified":"2023-10-16T00:32:22","modified_gmt":"2023-10-15T19:02:22","slug":"demystifying-javascript-tree-shaking","status":"publish","type":"post","link":"https:\/\/code4developers.com\/demystifying-javascript-tree-shaking\/","title":{"rendered":"Demystifying JavaScript Tree Shaking: Boosting Performance and Reducing Bundle Size"},"content":{"rendered":"<p>In the ever-evolving world of web development, optimizing the performance of your JavaScript applications is a key concern. One effective technique to achieve this is called &#8220;tree shaking.&#8221; In this article, we&#8217;ll delve into the concept of tree shaking, explain how it works, and provide a detailed example to illustrate its practical application. Let&#8217;s embark on a journey to understand this crucial aspect of modern web development.<!--more--><\/p>\n<h2 id=\"what-is-tree-shaking\">What is Tree Shaking?<\/h2>\n<p>Tree shaking is a process employed by modern JavaScript bundlers, such as Webpack, Rollup, and Parcel, to eliminate unused code (also known as &#8220;dead code&#8221;) from your application&#8217;s JavaScript bundles. This technique plays a pivotal role in enhancing the performance and reducing the bundle size, which in turn leads to faster load times for your web applications.<\/p>\n<p>Imagine your JavaScript codebase as a vast forest, where each file represents a tree. Some trees are huge, while others are smaller, and not all of them are necessary to display the initial view of your web application. Tree shaking identifies and removes the trees that are not needed, thereby optimizing the bundle size and making your application more efficient.<\/p>\n<h2 id=\"how-does-tree-shaking-work\">How Does Tree Shaking Work?<\/h2>\n<p>Tree shaking operates on the principle of static analysis. It examines the import and export statements in your code to determine the dependencies between different modules. When you build your application, the bundler identifies which modules are actually used by the entry point of your application. It then eliminates the code that is not directly or indirectly referenced by these modules, creating a smaller bundle in the process.<\/p>\n<p>Here&#8217;s a simplified example to illustrate how tree shaking works. Consider the following JavaScript code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\">\/\/ math.js\r\nexport function add(a, b) {\r\n  return a + b;\r\n}\r\n\r\nexport function subtract(a, b) {\r\n  return a - b;\r\n}\r\n<\/pre>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\">\/\/ main.js\r\nimport { add } from '.\/math';\r\n\r\nconsole.log(add(3, 2));\r\n<\/pre>\n<p>In this example, the <code>main.js<\/code> module imports the <code>add<\/code> function from the <code>math.js<\/code> module and uses it. Tree shaking identifies that only the <code>add<\/code> function is used in the application, and it eliminates the <code>subtract<\/code> function during the bundling process, resulting in a smaller bundle size.<\/p>\n<h2 id=\"practical-example\">Practical Example<\/h2>\n<p>Let&#8217;s take a more comprehensive example using Webpack, a popular bundler, to see tree shaking in action.<\/p>\n<p>First, make sure you have Node.js and Webpack installed. If not, you can install them by running the following commands:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"bash\">npm install -g webpack\r\nnpm install -g webpack-cli\r\n<\/pre>\n<p>Next, create a project folder and install a basic set of dependencies:<\/p>\n<div class=\"bg-black rounded-md mb-4\">\n<div class=\"flex items-center relative text-gray-200 bg-gray-800 gizmo:dark:bg-token-surface-primary px-4 py-2 text-xs font-sans justify-between rounded-t-md\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"bash\">mkdir tree-shaking-example\r\ncd tree-shaking-example\r\nnpm init -y\r\nnpm install lodash\r\n<\/pre>\n<p>Now, create two JavaScript files in your project folder:<\/p>\n<div class=\"bg-black rounded-md mb-4\">\n<div class=\"flex items-center relative text-gray-200 bg-gray-800 gizmo:dark:bg-token-surface-primary px-4 py-2 text-xs font-sans justify-between rounded-t-md\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\">\/\/ math.js\r\nexport function add(a, b) {\r\n  return a + b;\r\n}\r\n\r\nexport function subtract(a, b) {\r\n  return a - b;\r\n}\r\n<\/pre>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\">\/\/ main.js\r\nimport { add } from '.\/math';\r\n\r\nconsole.log(add(3, 2));\r\n<\/pre>\n<p>Now, create a <code>webpack.config.js<\/code> file to configure Webpack:<\/p>\n<div class=\"bg-black rounded-md mb-4\">\n<div class=\"flex items-center relative text-gray-200 bg-gray-800 gizmo:dark:bg-token-surface-primary px-4 py-2 text-xs font-sans justify-between rounded-t-md\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\">const path = require('path');\r\n\r\nmodule.exports = {\r\n  entry: '.\/main.js',\r\n  output: {\r\n    filename: 'bundle.js',\r\n    path: path.resolve(__dirname, 'dist'),\r\n  },\r\n  mode: 'production', \/\/ Enables tree shaking in production mode\r\n};\r\n<\/pre>\n<p>In the <code>webpack.config.js<\/code> file, we specify our entry point as <code>main.js<\/code>, and we set the mode to <code>'production'<\/code>, enabling tree shaking.<\/p>\n<p>Finally, build the project using Webpack:<\/p>\n<div class=\"bg-black rounded-md mb-4\">\n<div class=\"flex items-center relative text-gray-200 bg-gray-800 gizmo:dark:bg-token-surface-primary px-4 py-2 text-xs font-sans justify-between rounded-t-md\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"bash\">npx webpack\r\n<\/pre>\n<p>After running the build command, you&#8217;ll find a <code>dist<\/code> folder in your project directory containing the <code>bundle.js<\/code> file. If you examine this file, you&#8217;ll notice that it only includes the <code>add<\/code> function from the <code>math.js<\/code> module, while the <code>subtract<\/code> function is eliminated.<\/p>\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>Tree shaking is a powerful technique for optimizing your JavaScript bundles and improving the performance of your web applications. By eliminating unused code, it reduces bundle size, resulting in faster load times for your users.<\/p>\n<p>In this article, we&#8217;ve explored the concept of tree shaking and provided a practical example using Webpack. As you continue your journey in web development, integrating tree shaking into your build process can be a valuable step toward delivering high-performance web applications.<\/p>\n<p><a href=\"https:\/\/code4developers.com\/category\/javascript\/\">Click Here<\/a> to read more JavaScript articles on <a href=\"https:\/\/code4developers.com\/\">Code4Developers<\/a>. If you are getting started with Angular then I recommend this <a href=\"https:\/\/angular.io\/docs\" target=\"_blank\" rel=\"noopener\">official documentation<\/a> to refer.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In the ever-evolving world of web development, optimizing the performance of your JavaScript applications is a key concern. One effective technique to achieve this is called &#8220;tree shaking.&#8221; In this&hellip;<\/p>\n","protected":false},"author":4,"featured_media":3127,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[2],"tags":[22,1397],"powerkit_post_featured":[],"class_list":{"0":"post-14692","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-javascript","8":"tag-javascript","9":"tag-tree-shaking"},"jetpack_featured_media_url":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p8NAi4-3OY","jetpack-related-posts":[{"id":3150,"url":"https:\/\/code4developers.com\/webpack-introduction-without-code\/","url_meta":{"origin":14692,"position":0},"title":"Webpack: introduction without any code.","author":"Arif Khoja","date":"December 1, 2017","format":false,"excerpt":"There have existed build tools for JavaScript as long as I have been coding with it. I can without doubt say that they are better and easier to understand today than they have ever been. But there are also much more you \u201cneed\u201d to know before you get started. The\u2026","rel":"","context":"In &quot;JavaScript&quot;","block_context":{"text":"JavaScript","link":"https:\/\/code4developers.com\/category\/javascript\/"},"img":{"alt_text":"javascript","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":9279,"url":"https:\/\/code4developers.com\/what-is-new-in-angular-10\/","url_meta":{"origin":14692,"position":1},"title":"What is new in Angular 10?","author":"Yatendrasinh Joddha","date":"June 25, 2020","format":false,"excerpt":"Today Angular Teams has announced Version 10.0.0 of Angular! This release is smaller than typical, but it covers the entire platform, including the framework, Angular Material, and the CLI. What's new here? Optional Stricter Settings ng new --strict Enabling this flag initializes your new project with a few new settings\u2026","rel":"","context":"In &quot;Angular&quot;","block_context":{"text":"Angular","link":"https:\/\/code4developers.com\/category\/angular\/"},"img":{"alt_text":"","src":"https:\/\/miro.medium.com\/max\/60\/0*ruU5G-8_hqEp3UBY?q=20","width":350,"height":200},"classes":[]},{"id":3119,"url":"https:\/\/code4developers.com\/difference-between-javascript-and-ecmascript\/","url_meta":{"origin":14692,"position":2},"title":"What\u2019s the difference between JavaScript and ECMAScript?","author":"Arif Khoja","date":"October 31, 2017","format":false,"excerpt":"I\u2019ve tried googling \u201cthe difference between JavaScript and ECMAScript.\u201d I ended up having to wade through a sea of ambiguous and seemingly conflicting results: \u201cECMAScript is a standard.\u201d \u201cJavaScript is a standard.\u201d \u201cECMAScript is a specification.\u201d \u201cJavaScript is an implementation of the ECMAScript standard.\u201d \u201cECMAScript is standardized JavaScript.\u201d \u201cECMAScript is\u2026","rel":"","context":"In &quot;JavaScript&quot;","block_context":{"text":"JavaScript","link":"https:\/\/code4developers.com\/category\/javascript\/"},"img":{"alt_text":"javascript","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":3216,"url":"https:\/\/code4developers.com\/superstruct\/","url_meta":{"origin":14692,"position":3},"title":"Superstruct","author":"Arif Khoja","date":"January 31, 2018","format":false,"excerpt":"I stumbled upon this GitHub project a few days ago. It\u2019s called Superstruct, and it looks like an awesome way to validate data in JavaScript. Let me explain. You probably want to make sure that you get the kind of data you expect as input in JavaScript, either from your\u2026","rel":"","context":"In &quot;JavaScript&quot;","block_context":{"text":"JavaScript","link":"https:\/\/code4developers.com\/category\/javascript\/"},"img":{"alt_text":"javascript","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":2610,"url":"https:\/\/code4developers.com\/semicolon-in-javascript\/","url_meta":{"origin":14692,"position":4},"title":"Importance of Semicolon [;] In JavaScript","author":"Yatendrasinh Joddha","date":"June 19, 2017","format":false,"excerpt":"It is said that in JavaScript semicolons are not compulsory. It's true, because JavaScript automatically inserts a semicolons at required place and it is know as \"Automatic Semicolon Insertion\". This behavior of JavaScript confuses us a lot. This article is written for those who have just started writing JavaScript and\u2026","rel":"","context":"In &quot;JavaScript&quot;","block_context":{"text":"JavaScript","link":"https:\/\/code4developers.com\/category\/javascript\/"},"img":{"alt_text":"javascript","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":6955,"url":"https:\/\/code4developers.com\/transpiling-in-javascript\/","url_meta":{"origin":14692,"position":5},"title":"Transpiling in JavaScript","author":"Yatendrasinh Joddha","date":"April 29, 2020","format":false,"excerpt":"Transpiling is a term used for taking source code written in one language and converting or transforming it into another language. All the browsers does not support JavaScript code written in ES6. It is a big challenge for every new gen developers. Now converting this ES6 code to ES5 is\u2026","rel":"","context":"In &quot;JavaScript&quot;","block_context":{"text":"JavaScript","link":"https:\/\/code4developers.com\/category\/javascript\/"},"img":{"alt_text":"javascript","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=700%2C400 2x"},"classes":[]}],"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/posts\/14692","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/comments?post=14692"}],"version-history":[{"count":2,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/posts\/14692\/revisions"}],"predecessor-version":[{"id":14694,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/posts\/14692\/revisions\/14694"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/media\/3127"}],"wp:attachment":[{"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/media?parent=14692"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/categories?post=14692"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/tags?post=14692"},{"taxonomy":"powerkit_post_featured","embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/powerkit_post_featured?post=14692"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}