背景: spa单页面应用的index.html,设置了变量aaa,如果想在*.vue文件中或者是main.ts使用该变量,则提示ts的类型检查,找不到该变量。这时候就需设置类型声明文件,声明文件中用到了declare
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Vue + TS</title>
</head>
<body>
<div id="app"></div>
<script>
let aaa = "nice";
</script>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
设置类型文件有多种方式
- 如果是vite模式可到vite-env.d.ts(如果存在该文件)中设置,vite-env.d.ts中优先级比在types中设置的高
/// <reference types="vite/client" /> 表示依赖一个全局变量的声明文件
- 到src目录下新建types文件夹,然后到tsconfig.json中配置paths
- 到package.json 中配置types
declare就是中xxx.d.ts用到
declare var 声明全局变量
declare function 声明全局方法
declare class 声明全局类
declare enum 声明全局枚举
declare interface 声明全局接口
declare module 声明module
declare namespace 声明命名空间
其中declare module 用来做一些第三方库没有支持ts的,通过declare module,让我们在代码中可以import进来,从而使用它。 可以让单页面文件可以通过import aaa from 'AAA.vue
引用,否则只能import AAA.vue
xxx.d.ts
declare module "test" {
export var value: number;
export function hello(str: string): String;
}
declare namespace mySpace {
interface ITest {
id: number;
}
}
// 这样子我们在文件中 import 那个没有支持ts的库就不会报错了,
// 而且还会提示 库暴露出来的属性/方法,
// 否则只能import "test";
import test from "test";
test.hello('123');
test.value;
window.D2 = "hello";
const obj: mySpace.ITest = {id: 1};
// 上面的例子只有 declare module 才是定义一个模块,才能被 import,其他的用法如上