vite: importMetaEnv doesn't work.
Describe the bug
I used the intellisense function as per the guide, but it doesn’t work.
/src/env.d.ts
interface ImportMetaEnv {
VITE_API_TIMEOUT: number,
VITE_MOCKUP: boolean
}
.env
VITE_API_TIMEOUT=3000
VITE_MOCKUP=true
And, when import.meta.env is printed from main.ts to the console…
BASE_URL: "/"
DEV: true
MODE: "development"
PROD: false
SSR: false
VITE_API_TIMEOUT: "3000"
VITE_MOCKUP: "true"
VITE_SET: "900"
Intellisense does not work for .env settings. It only comes in string type.
Reproduction
I want it to be converted to the type applied in intellisense (env.d.ts
).
System Info
package.json
"devDependencies": {
"@antfu/eslint-config": "^0.6.5",
"@iconify/json": "^1.1.347",
"@intlify/vite-plugin-vue-i18n": "^2.1.2",
"@types/nprogress": "^0.2.0",
"@typescript-eslint/eslint-plugin": "^4.24.0",
"@vitejs/plugin-vue": "^1.2.2",
"@vue/compiler-sfc": "^3.0.11",
"@vue/server-renderer": "^3.0.11",
"cross-env": "^7.0.3",
"eslint": "^7.27.0",
"https-localhost": "^4.6.5",
"markdown-it-prism": "^2.1.6",
"npm-run-all": "^4.1.5",
"pnpm": "^6.4.0",
"sass": "^1.34.0",
"typescript": "^4.2.4",
"vite": "^2.3.3",
"vite-plugin-components": "^0.9.1",
"vite-plugin-icons": "^0.5.1",
"vite-plugin-md": "^0.6.7",
"vite-plugin-pages": "^0.12.1",
"vite-plugin-pwa": "^0.7.3",
"vite-plugin-vue-layouts": "^0.3.1",
"vite-plugin-windicss": "^0.15.10",
"vite-ssg": "^0.11.1",
"vue-tsc": "^0.1.4"
}
Used package manager: pnpm
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 23 (14 by maintainers)
Recommended in docs way to add types causes build problem:
This works
@imShara I can confirm this 👍
Correct would be without
extends Readonly<Record ...
and maybe I think with the///ref
Could you try
@erdemtuna I used “?” on the env variable name. As mentioned here:
https://stackoverflow.com/questions/66039933/typescript-types-for-import-meta-env
I don’t think the types are converted by default. You have to do it yourself.
I think the
env.d.ts
is just a way to fight annoyance ofimport.meta.env
values being typed asstring | boolean | undefined
, when it mostly should bestring | undefined
. Sadly, it’s because there areDEV
andPROD
keys inimport.meta.env
that are booleans. I think there could be fix introduced, but it’s not yet done - anyway, it would just make the defining ownImportMetaEnv
unnecessary, the values still would bestring | undefined
.Anyway, the solution is to convert the types by yourself.
If you want some inspiration for now, I use it like this in my project:
config.ts
, website sources:env.d.ts
:My code base imports
Config
where necessary, it have types nicely converted.