Otherwise, you can't do lookups. And you can't minify class methods because you have to call the methods by their name. And so if you shorten them, they no longer work. This actually means that API design matters a lot, and how you design your programs so that they can be minified more easily can affect your bundle size a lot.
Here's an example of the class methods. On the left is an example API class, something actually we used to use in the Sentry SDK, but I de-Sentryfied it a lot. And on the right here is a minified version. I prettified it so that we kept white space so that it's easier to read. And you can actually see that in the minified version, a lot of the names still state because all of these class methods can't get minified. They're part of the public API of this API class. Even things that we consider private like encoded auth still doesn't get minimized because of how JavaScript works.
So, what are some strategies so we can write more minification-friendly code? Well, first of all, try to avoid deeply nested object lookups and builder patterns. On the left here, you can see that we have this complicated lookup on event.exception.values.type. And we want to make sure that everything exists properly so we do this Boolean operation. But all of these values, exception.values.type, and of course the SentryError here, are completely unminifiable. And so we end up with a lot of redundant information in our bundle. Given that we're already using a try catch, we can just shorten this to a single line. And if we hit a type error, it'll hit the catch block instead.
Another way to write more minification-friendly code is to use config to mangle based on regex. So, for example, if we go back to the class methods example here, if we say, hey, everything that starts with the underscore should be minified, we can suddenly now minify encoded auth and all of its usages here. Most bundlers have config that allow you to set up custom mangling based on some regular expression. Lastly, and this is where the API design component comes in, you can use functions and objects instead of classes. And this means classes, of course, they have their whole public API and every method, public method, can't be minified. But if you use functions and objects, function names can be minified because they're just simply top-level methods and all they care about is where they're called and what they're called with. Even better than objects, because, again, object keys can't be minified, is actually using arrays. So if you have some internal data structure that you know is commonly used, then perhaps making an array instead of an object. React hooks actually does this really well. Things like useState and useReducer return an array. So that these structured array arguments can actually be minified by a bundler. A great example of comparing minification-friendly libraries is Zod versus ValleyBot.
Comments