JavaScript Modules with Tree Shaking Techniques
Tree Shaking:
Write a JavaScript program to create a module with multiple exports and import only the functions needed.
Tree shaking is a technique for eliminating unused code in JavaScript. In this exercise, we’ll create a module with multiple exports and demonstrate importing only the required functions.
Solution-1: Using Named Exports with Direct Imports
Code:
File: mathUtils.js
This file defines multiple mathematical utility functions.
// mathUtils.js
// Exporting multiple functions from mathUtils.js
export const add = (a, b) => a + b; // Adds two numbers
export const subtract = (a, b) => a - b; // Subtracts two numbers
export const multiply = (a, b) => a * b; // Multiplies two numbers
export const divide = (a, b) => a / b; // Divides two numbers
File: main.js
This file imports only the required functions.
// main.js
// Importing only the required functions
import { add, multiply } from './mathUtils.js';
// Using the imported functions
console.log(add(4, 3)); // Logs 7
console.log(multiply(5, 6)); // Logs 30
Output:
7 30
Explanation:
- mathUtils.js defines and exports four mathematical utility functions using named exports.
- main.js imports only the add and multiply functions, leaving the unused exports (subtract and divide) untouched.
- This selective import ensures that only the required functions are included in the final bundle during tree shaking.
Solution-2: Combining Tree Shaking with Default Export
Code:
File: mathUtils.js
This file exports a single utility object containing multiple functions.
// mathUtils.js
// Exporting a utility object containing multiple functions
const mathUtils = {
add: (a, b) => a + b, // Adds two numbers
subtract: (a, b) => a - b, // Subtracts two numbers
multiply: (a, b) => a * b, // Multiplies two numbers
divide: (a, b) => a / b, // Divides two numbers
};
export default mathUtils;
File: main.js
This file destructures and uses only the required functions.
// main.js
// Importing the default export and destructuring only the required functions
import mathUtils from './mathUtils.js';
const { add, divide } = mathUtils;
// Using the destructured functions
console.log(add(8, 2)); // Logs 10
console.log(divide(20, 4)); // Logs 5
Output:
10 5
Explanation:
- mathUtils.js exports all functions within a single object using a default export.
- In main.js, the utility object is imported, and only the add and divide functions are destructured and used.
- This approach can still benefit from tree shaking if the build tool understands unused properties of the object.
Improve this sample solution and post your code through Disqus
Previous: Exporting and Extending Classes in JavaScript.
Next: JavaScript: Using Custom Aliases for Default Exports.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics