Quiet version of `$inspect` for tree-shaking
Opened this issue · 7 comments
Describe the problem
The ability to have dev-only code that is completely removed in production builds is a valuable tool beyond logging. To take advantage of this without logging, I can write:
$inspect(expensiveDebugAssertion()).with(() => {})This works, but .with(() => {}) is clunky and the usage is not obvious either to the reader or to developers who could use this technique.
Describe the proposed solution
An $inspect.by variant would be an elegant solution with similar usage as $derived.by:
// accepts function with no parameters
$inspect.by(expensiveDebugAssertion)Importance
nice to have
My recommendation for this would be to use esm-env -- that's basically what it's built for.
Am I right to understand that esm-env is a module-level conditional? It seems like a much coarser tool than the proposal.
Am I right to understand that esm-env is a module-level conditional? It seems like a much coarser tool than the proposal.
You can import DEV from it and wrap it in an if...I would be curious to know which expensive operation is dev only AND doesn't log. Feel like a very niche use case.
You can import DEV from it and wrap it in an if
That could work (assuming the code doesn't end up in the prod build), but it's definitely more verbose.
The goal is to do sanity checking and maintain invariants in dev builds without having it affect production builds. It's pretty common in other languages, typically as asserts.
I mostly agree with the request, but there's a problem: What if I wanted to retain $inspect (even just one out many) in production? How would one achieve this?
Doing if (!DEV) wouldn't work since the production build will mute the output. A second $inspect. I bet Rich Harris will say "hell no" to that. 😄
So maybe the best to do is create your own inspect that encapsulates the IF logic. Unless someone can think of a better solution?
Wait, can $inspect be wrapped in a function outside a component? I ask because it might be a rune that cannot be used in .svelte.ts files.
Anyway, I'll leave this to the experts now.
That could work (assuming the code doesn't end up in the prod build), but it's definitely more verbose.
This would depend on how your build pipeline works. If you're using anything that does treeshaking (you probably are) then they'd get stripped completely.
You'd have to experiment to make sure it works, but you might be able to create a function abstraction around this as well -- it just depends on how smart the treeshaking is.
Doesn't import.meta.env.DEV solves this?