iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
⛳

[Vite] Declaring Window Object Types in a Type Definition File

に公開

Conclusion

  1. Add type definition to vite-env.d.ts
  2. Add define option to vite.config.ts

Situation

window property does not exist

Property 'ENGINE_DATA' does not exist on type 'Window & typeof globalThis'.

I am using a custom window property named ENGINE_DATA, but it lacks a type definition.

Solution

Type declaration in vite-env.d.ts

vite-env.d.ts
/// <reference types="vite/client" />
declare interface Window { // Added
  ENGINE_DATA: {
    scenes: any[];
    parameter: any;
    frame: number;
    id: number;
  };
}

This alone resolves the error.

Definition in vite.config.ts

vite.config.ts
import { defineConfig } from 'vite';

export default defineConfig({
  define: {
    "window.ENGINE_DATA": JSON.stringify({
      scenes: [],
      parameter: null,
      frame: 0,
      id: 0,
    }),
  },
});

Apparently, this is also done, but I don't quite understand the behavior.

References

https://ja.vitejs.dev/config/shared-options.html#define

Discussion