macros should not throw when running outside of vite
Fixes #19
🦋 Changeset detected
Latest commit: 65fd649e1c3818897350fcd304c9d844eb37f702
The changes in this PR will be included in the next version bump.
This PR includes changesets to release 1 package
| Name | Type |
|---|---|
| vite-env-only | Patch |
Not sure what this means? Click here to learn what changesets are.
Click here if you're a maintainer who wants to add another changeset to this PR
Thinking more about this... I think a better API would be something like:
// script.ts
import { setEnv } from "vite-env-only/macros"
setEnv("server")
// in the future could even set compat for multiple envs:
// `setEnv("server", "client")`
// seems weird now, but with Vite v6 it fits right in
// ..run code that depends on macros..
where setEnv throws if run within Vite and also throws if called more than once in your script.
Then the macros (outside of Vite) can check that an environment was set and that it matches their intended env, otherwise throw.
The benefit here is that you would get an error that points directly to the offending code wrapped by the macro as soon as that definition is accessed. Whereas the current approach only gives you errors when you happen to access things that aren't defined in the env runtime and with stacktraces that point deep into your deps.
The issue with relying solely on the internal usingVite boolean is that it will let both clientOnly$ and serverOnly$ values through. I think the intent is actually for Node scripts to have access to values wrapped by serverOnly$ when running outside of Vite. It would still be nice to throw with a nice error if the script accidentally accessed a clientOnly$ value. That said, without the Vite plugin there won't be any DCE, so if you happen to import a client-only thing and just importing it is what causes Node to error out, then the setEnv stuff won't make that any better.