Reputation: 9013
I'm using ViteJS to compile a TS codebase. Vite has no problem transpiling the code but it doesn't handle the types and so I'm trying to use Typescript's tsc to do this and getting errors with every reference to import.meta.env
.
I run the type build with:
npx tsc src/index.ts \
--emitDeclarationOnly \
--module es2020 \
--target es2020 \
--outDir dist/types
Note: changing
es2020
toesnext
also fails in the same way
I the the following error in all places where I'm using the new ES Module syntax:
Property 'env' does not exist on type 'ImportMeta'
but in vs-code the type system is happy and indeed at runtime this does in fact work. Now the reason that vs-code is happy is that there is a src/ImporMeta.d.ts
file which I've created that looks like this:
interface ImportMeta {
env: {
VITE_APP_TITLE?: string;
BASE_URL: string;
MODE: string;
PROD: boolean;
DEV: boolean;
VITE_DEBUG?: boolean;
[`VITE_${string}`]: string;
};
}
For some reason, however, tsc is not seeing this file or refusing to build for some other reason even though the "target" and "module" are both at levels where import.meta
should be allowed.
Can anyone help me with what I'm doing wrong?
I'm using Typescript 4.5.2 and running under node 16.13.0 (also tried node 14.18.1 but same results)
UPDATE: to my surprise, although I'm getting these errors (three of them), it still actually builds the types including for the files where the files originate ... for my CI/CD I need the errors to go away so the issue has not been resolved but now I'm confused why it would build and then fail.
Upvotes: 4
Views: 2751
Reputation: 426
You do not need a custom .d.ts for this, just use the following in tsconfig.json:
{
"compilerOptions": {
"types": ["vite/client"]
}
}
Here is the corresponding docs page: https://vitejs.dev/guide/features.html#client-types
Note that the .d.ts file might not be picked up by tsc because the entry point you specified for the tsc command.
Upvotes: 6