Architecting JS applications can be broken up into two parts: one part clean and scalable code, another part proper distribution. The first part can be a bit subjective depending on your stack and what works best in accordance with the makeup of your team. The latter part, however, is very straightforward. A big part of that is understanding tree shaking.

Tree shaking, made possible by ES2015’s module syntax introduction(import, export, etc.), is a term that encompasses the philosophy that unneeded code should not be included. To make this easier, let’s go straight into some code.

// math.js
export const add = (a,b) => a + b;

export const subtract = (a,b) => a - b;

As you can see above, we have a JS module called Math.js. In this module, we are exporting two methods, add and subtract. In the past, to use either of these methods we would need to import the entire file to have access to them. Today that is not the case. With Tree Shacking we can simply import only the method we need from the module. See below.

// main.js
import { add } from './math';

const testMethod = () => add(1,3);

Because the add method was exported from its module, we have the ability to import it individuallly. Now, this may not seem like much considering the small stature of our code sample, but imagine yourself in an actual project with much more code. Properly exporting and importing methods drastically impacts performance and overall user experience.

Hopefully, this was well explained, and you take this into improving the codebases you’re a team member of.

Happy coding!