背景:用vite创建vue3项目叠加ts,访问import.meta中的变量。
问题:代码提示import.meta中只有url,手动访问env会报错:Property 'env' does not exist on type 'ImportMeta',但是浏览器中可以打印。
解决方法(方法1和方法2在我的项目中有用,方法3和方法4大家说可以,可能是环境问题,在我的项目中没有起作用,但是大家说有用,那就记录下来,以后有机会再试一试):
1、忽略类型校验:
//@ts-ignore
console.log('vite', import.meta.env)
2、使用类型断言:
console.log('vite', (import.meta as any).env)
3、在tsconfig.json下的compilerOptions中增加:"types'': [''vite/client'']
{
"compilerOptions": {
"types": ["vite/client"],
}
}
4、在.d.ts文件中声明模块:
declare interface ImpoertMetaEnv {
readonly MODE: string
// readonly VITE_BASE_URL: string
// readonly VITE_TIME_OUT: number
}
declare interface ImpoertMeta {
readonly env: ImpoertMetaEnv
}