Previously we talked about refactoring lying TypeScript type assertions into real assertions. But we left out one critical piece.
The assertions have done their job by the time the code path was run during development. If there was any violation, the assertion would have already tripped. This means it is safe to remove them from the production build.
We are not relying on assertions for correctness, only to detect issues. Issues which are no longer possible in production.
Here is a short example that highlights the problem. Our sample problem contains a single usage of
After Vite performs a build, we can inspect the output. Note, minification has been turned off to make it easier to understand what Vite is doing.
assertInstanceOf is still present.
Vite will tree shake dead code, thus we need to some how turn
assertInstanceOf into dead code. The simplest way to achieve this is to use Vite environment variables.
We can use
import.meta.env.PROD which is
false during development and
When we add this single one line at the beginning of
When Vite does a production build,
import.meta.env.PROD is statically replaced into
true. Thus the code becomes:
import.meta.env.PROD doesn't actually exist at runtime!
This means in a production build, the rest of the body of
assertInstanceOf is dead code. Furthermore, we can see the entire
assertInstanceOf function is dead code, therefore we can remove calls to it as well!
Finally, a fully tree shaken code becomes:
Are you interested in optimizing production builds? You're in luck, Battlefy is hiring.