Infer the import.meta.env type - #415
Conversation
…dencies - Updated the Vite configuration to include the vite-tsconfig-paths plugin for improved path resolution. - Added tsconfig paths in the tsconfig.json file to facilitate module resolution. - Updated package.json to include vite-tsconfig-paths as a dependency. - Modified arkenv.code-workspace to support wildcard tsconfig file associations. - Updated pnpm-lock.yaml to reflect the addition of vite-tsconfig-paths and its dependencies.
- Added TypeScript definitions for enhanced type safety in the Vite environment. - Introduced `ImportMetaEnvAugmented` and `ViteTypeOptions` interfaces to improve type checking for environment variables. - Updated the linter configuration to disable the `noUnusedVariables` rule for TypeScript declaration files.
🦋 Changeset detectedLatest commit: 40d7795 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
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 |
WalkthroughAdds exported typing utilities and a public Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Dev as Developer
participant ViteCfg as vite.config.ts
participant Plugin as arkenv Plugin
participant Types as ImportMetaEnvAugmented
participant MetaEnv as import.meta.env
Dev->>ViteCfg: Define/export Env schema (VITE_* fields)
ViteCfg->>Plugin: arkenvVitePlugin(Env)
Plugin->>Types: Infer types from schema
Types->>Types: FilterByPrefix "VITE_"
Plugin->>MetaEnv: Expose only filtered, typed keys
rect rgb(220,240,220)
Note over Dev,MetaEnv: Usage
Dev->>MetaEnv: Access import.meta.env.VITE_*
MetaEnv-->>Dev: Typed value (autocomplete)
Dev->>MetaEnv: Access import.meta.env.PORT
MetaEnv-->>Dev: Not present / type error
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Possibly related issues
Possibly related PRs
Suggested labels
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
commit: |
📦 Bundle Size Report✅ All size limits passed! |
- Exported the `Env` schema from `vite.config.ts` to enhance type safety for environment variables. - Updated type definitions in `vite-env.d.ts` to utilize the exported `Env` schema, ensuring only VITE_* prefixed variables are included. - Added export for `ImportMetaEnvAugmented` in the Vite plugin to facilitate better type integration.
- Included a reference link in the `ImportMetaEnvAugmented` type documentation to the original implementation by Julien-R44, enhancing clarity and accessibility for users.
- Refactored the `ImportMetaEnv` interface to utilize the `ImportMetaEnvAugmented` type without directly referencing the `Env` schema, enhancing type safety and clarity in the Vite environment type definitions.
- Updated the comment in vite-env.d.ts to clarify that exporting the Env schema from a separate env.ts file is a suggestion rather than a requirement, enhancing documentation clarity.
… import.meta.env - Revised the Vite plugin documentation to clarify the filtering of environment variables and added a note on using non-prefixed variables. - Introduced a new section on making import.meta.env type-safe, with a link to the relevant setup guide. - Updated meta.json to include the new documentation page for typing import.meta.env.
- Introduced the `ImportMetaEnvAugmented` type helper to enhance type safety for `import.meta.env` by augmenting it with a defined environment variable schema. - Updated documentation to reflect the new type and its usage, ensuring full type safety and autocomplete for `VITE_*` environment variables in client code. - Minor adjustments made to existing documentation for consistency in terminology regarding typesafety.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (7)
apps/www/content/docs/vite-plugin/meta.json (1)
6-6: Add new docs route to Playwright navigation test for coverageThe new
"typing-import-meta-env"page looks correct here, buttooling/playwright-www/tests/docs-navigation.test.tsstill only navigates to:const vitePluginPages = [ "/docs/vite-plugin", "/docs/vite-plugin/arkenv-in-viteconfig", ];Consider adding
"/docs/vite-plugin/typing-import-meta-env"to this list so the new page is exercised by the docs navigation E2E test.apps/www/content/docs/vite-plugin/typing-import-meta-env.mdx (2)
51-57: Clarify how the prefix is chosen for ImportMetaEnvAugmentedThe “How it works” bullet 2 says:
Filters to only include variables matching the Vite prefix (defaults to
"VITE_")From the helper type:
export type ImportMetaEnvAugmented< TSchema extends type.Any, Prefix extends string = "VITE_", > = FilterByPrefix<InferType<TSchema>, Prefix>;the compile-time prefix is actually driven by the
Prefixgeneric (defaulting to"VITE_"), not dynamically by Vite’senvPrefixconfig.To avoid confusion for users who change the Vite prefix, consider clarifying that:
- By default it filters to keys starting with
"VITE_".- If they use a custom prefix in Vite, they should pass it as the second generic parameter, e.g.:
type ImportMetaEnvAugmented = import("@arkenv/vite-plugin").ImportMetaEnvAugmented< typeof import("../vite.config").Env, "APP_" >;
61-75: Link to a concrete Vite example and consider less ambiguous type namingThe “Example with separate env file” is great, but two small improvements would make it easier to follow:
Link to a real example
Given you already have a Vite playground/example in this repo, consider adding a short note like:See the Vite example in this repo for a full working setup.
and link to the appropriate example (e.g. the Vite playground) so readers can inspect a complete project structure. Based on learnings
Optional: avoid reusing
Envfor both value and type
In this snippet:export const Env = type({ ... }); export type Env = typeof Env.infer;it’s valid to have a value and type with the same name, but can be slightly confusing in docs. You might prefer something like:
export const Env = type({ ... }); export type EnvType = typeof Env.infer;and then reference
EnvTypein places where only the type is needed.apps/playgrounds/vite/vite.config.ts (1)
22-26: Consider dropping the debugconsole.logfrom the playground configThe
console.log(\${env.VITE_MY_NUMBER} ${typeof env.VITE_MY_NUMBER}`);` is useful while developing the example, but it will run on every dev/build config evaluation.Since the playground already demonstrates the values in
App.tsx, consider removing this log (or gating it behind a debug flag) to keep the sample config minimal:- console.log(`${env.VITE_MY_NUMBER} ${typeof env.VITE_MY_NUMBER}`); return { plugins: [ tsconfigPaths(), reactPlugin(), arkenvVitePlugin(Env), ],packages/vite-plugin/src/index.ts (1)
13-45: JSDoc accurately reflects plugin behavior; consider tying it to the new typing helper.The description and examples line up with the implementation (validation via ArkEnv, filtering by
envPrefix, exposure throughimport.meta.env.*). You might optionally add a short note pointing toImportMetaEnvAugmentedhere so readers immediately see how to get type-safeimport.meta.envaugmentation, especially when using a customenvPrefix.packages/vite-plugin/src/types.ts (2)
1-16: RefineInferTypeto more robustly droptype.errors.If the validator’s return type is a union like
Value | type.errors, the conditionalR extends type.errors ? never : Rwon’t actually removetype.errorsfrom the union. To guarantee you only keep the validated value type, consider:type InferType<T> = T extends ( value: Record<string, string | undefined>, ) => infer R ? Exclude<R, type.errors> : T extends type.Any<infer U, infer _Scope> ? U : never;This keeps the intent while avoiding
type.errorsleaking into the inferredImportMetaEnvshape. It’s also worth double-checking this against the currentarktypetypings so it matches the real validator signature.
28-72:ImportMetaEnvAugmentedcleanly links ArkType schemas toimport.meta.env; consider a small doc tweak.Combining
InferType<TSchema>withFilterByPrefixis a good fit for the plugin’s behavior (validate whole env, then only expose prefixed keys). The examples are clear and align with the public API. You might optionally:
- Call out in the docs that
Prefixshould mirror Vite’senvPrefixwhen customized.- Mention that a union
Prefixcan model multiple prefixes if users configure Vite that way.Otherwise the type surface and examples look solid.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (15)
.changeset/free-oranges-bow.md(1 hunks)apps/playgrounds/vite/package.json(1 hunks)apps/playgrounds/vite/src/vite-env.d.ts(1 hunks)apps/playgrounds/vite/tsconfig.json(1 hunks)apps/playgrounds/vite/vite.config.ts(2 hunks)apps/www/content/docs/vite-plugin/index.mdx(1 hunks)apps/www/content/docs/vite-plugin/meta.json(1 hunks)apps/www/content/docs/vite-plugin/typing-import-meta-env.mdx(1 hunks)arkenv.code-workspace(1 hunks)biome.jsonc(1 hunks)openspec/changes/archive/2025-11-20-add-arkenv-vite-config/specs/vite-config-usage/spec.md(3 hunks)openspec/changes/archive/2025-11-20-add-arkenv-vite-config/tasks.md(1 hunks)openspec/specs/vite-config-usage/spec.md(3 hunks)packages/vite-plugin/src/index.ts(1 hunks)packages/vite-plugin/src/types.ts(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-09-09T17:37:19.650Z
Learnt from: yamcodes
Repo: yamcodes/arkenv PR: 132
File: packages/arkenv/README.md:13-14
Timestamp: 2025-09-09T17:37:19.650Z
Learning: For yamcodes/arkenv project: Runtime support documentation should link to specific examples: Node.js (examples/basic), Bun (examples/with-bun), Vite (examples/with-vite-react-ts).
Applied to files:
openspec/specs/vite-config-usage/spec.mdapps/www/content/docs/vite-plugin/typing-import-meta-env.mdxopenspec/changes/archive/2025-11-20-add-arkenv-vite-config/specs/vite-config-usage/spec.md
🧬 Code graph analysis (7)
.changeset/free-oranges-bow.md (2)
packages/vite-plugin/src/index.test.ts (6)
mockTransformedEnv(135-182)mockTransformedEnv(184-230)mockCreateEnv(232-259)pluginInstance(95-100)vi(81-84)config(39-75)apps/playgrounds/vite/src/App.tsx (1)
App(6-46)
packages/vite-plugin/src/types.ts (3)
packages/arkenv/src/type.ts (1)
type(3-3)packages/vite-plugin/src/index.ts (1)
ImportMetaEnvAugmented(6-6)packages/vite-plugin/src/index.test.ts (3)
mockTransformedEnv(184-230)mockTransformedEnv(135-182)pluginInstance(95-100)
apps/www/content/docs/vite-plugin/typing-import-meta-env.mdx (2)
packages/vite-plugin/src/index.test.ts (3)
mockTransformedEnv(184-230)mockTransformedEnv(135-182)mockCreateEnv(232-259)apps/playgrounds/vite/src/App.tsx (1)
App(6-46)
apps/playgrounds/vite/src/vite-env.d.ts (3)
packages/vite-plugin/src/types.ts (1)
ImportMetaEnvAugmented(69-72)packages/vite-plugin/src/index.test.ts (4)
mockTransformedEnv(184-230)mockTransformedEnv(135-182)mockCreateEnv(232-259)vi(81-84)apps/playgrounds/vite/src/App.tsx (1)
App(6-46)
packages/vite-plugin/src/index.ts (1)
packages/vite-plugin/src/index.test.ts (5)
mockTransformedEnv(184-230)mockTransformedEnv(135-182)mockCreateEnv(232-259)pluginInstance(95-100)error(308-340)
apps/www/content/docs/vite-plugin/meta.json (1)
tooling/playwright-www/tests/docs-navigation.test.ts (1)
vitePluginPages(58-74)
apps/playgrounds/vite/vite.config.ts (2)
packages/vite-plugin/src/__fixtures__/basic/config.ts (1)
Env(3-6)packages/arkenv/src/type.ts (1)
type(3-3)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: test-e2e (e2e)
- GitHub Check: test-e2e (a11y)
🔇 Additional comments (11)
apps/playgrounds/vite/package.json (1)
28-29: Dev dependency updates align with TS path alias usagePointing
viteatnpm:rolldown-vite@latestand addingvite-tsconfig-pathsmatches the TSbaseUrl/pathssetup in the playground; no issues from my side. Please just confirmpnpm dev/buildrun cleanly with this combo in your environment.arkenv.code-workspace (1)
5-5: VS Code association fortsconfig*.jsonlooks goodMapping all
tsconfig*.jsonfiles tojsoncis a nice quality-of-life tweak and has no runtime impact.apps/playgrounds/vite/tsconfig.json (1)
3-8: TSbaseUrl/pathssetup is standard for Vite and matches the plugin usageDefining
baseUrl: "."with an"@/*": ["./src/*"]path alias is a conventional setup and pairs well withvite-tsconfig-paths; the expandedreferencesobjects preserve the original paths. Please just re-runtsc -bfor the playground to confirm project references still build as expected.Also applies to: 10-15
openspec/changes/archive/2025-11-20-add-arkenv-vite-config/specs/vite-config-usage/spec.md (1)
13-13: 'typesafe' terminology normalization in archived spec is consistentUpdating the archived spec to use “typesafe”/“typesafe patterns” keeps wording aligned with the active spec and docs without changing any requirements or scenarios.
Also applies to: 51-52, 57-57, 61-61, 70-71
openspec/changes/archive/2025-11-20-add-arkenv-vite-config/tasks.md (1)
14-15: Checklist wording now matches 'typesafe' terminologyChanging the wrapper requirement note to “typesafe return values” aligns this task file with the spec/docs language; no further changes needed.
biome.jsonc (1)
117-126: DisablingnoUnusedVariablesfor.d.tsis a sensible noise reductionTurning off
correctness.noUnusedVariablesspecifically for**/*.d.tsavoids false positives in declaration files while leaving the main codebase rules intact. Please re-run Biome to ensure the override only affects.d.tsfiles as intended.openspec/specs/vite-config-usage/spec.md (1)
16-16: Active spec now uses 'typesafe' consistently with the archived changeThe shift to “typesafe” in the main
vite-config-usagespec keeps language consistent with the archived spec and related docs while preserving the same constraints around validation and forbidden patterns.Also applies to: 54-54, 60-60, 64-64, 73-73
.changeset/free-oranges-bow.md (1)
1-9: Changeset accurately captures the newImportMetaEnvAugmentedhelperThe patch entry clearly describes the new type helper for a typesafe
import.meta.envand properly attributes the inspiration tovite-plugin-validate-env; this should generate an appropriate patch release for@arkenv/vite-plugin.apps/www/content/docs/vite-plugin/index.mdx (1)
22-27: Note + new typing section read cleanly and match routingThe updated
[!NOTE]and the “Type-safe import.meta.env” section are consistent with the plugin behavior (VITE_ prefix, server-only vars excluded) and correctly link to/docs/vite-plugin/typing-import-meta-env. No changes needed.packages/vite-plugin/src/index.ts (1)
6-6: Public re-export ofImportMetaEnvAugmentedlooks good.Type-only re-export from the plugin entrypoint is a clean DX improvement and has no runtime impact; avoids consumers deep-importing from
"./types".packages/vite-plugin/src/types.ts (1)
21-26: Prefix filter utility is sound and matches the intended env-prefix behavior.
FilterByPrefixcorrectly narrows to keys starting withPrefix, and will naturally support multiple prefixes if callers pass a union (e.g."VITE_" | "PUBLIC_") forPrefix. No changes needed.
…type-safe import.meta.env - Enhanced comments in vite-env.d.ts to explain the strictImportMetaEnv option and its impact on type safety for import.meta.env. - Updated documentation to reflect the streamlined setup process for achieving type safety with ArkEnv, ensuring clarity for users.
This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and the packages will be published to npm automatically. If you're not ready to do a release yet, that's fine, whenever you add more changesets to main, this PR will be updated. # Releases ## @arkenv/vite-plugin@0.0.18 ### Patch Changes - #### `ImportMetaEnvAugmented` type helper for typesafe `import.meta.env` _[`#415`](#415) [`79bef3c`](79bef3c) [@yamcodes](https://github.com/yamcodes)_ Add a new `ImportMetaEnvAugmented` type that augments `import.meta.env` with your environment variable schema. This provides full type safety and autocomplete for all your `VITE_*` environment variables in client code. Implementation inspired by [Julien-R44](https://github.com/Julien-R44)'s [vite-plugin-validate-env](https://github.com/Julien-R44/vite-plugin-validate-env#typing-importmetaenv). Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
TODO
Summary by CodeRabbit
New Features
Documentation
✏️ Tip: You can customize this high-level summary in your review settings.