搭建TS相关项目框架
1、tsconfig.json 通用配置
{
"compilerOptions": {
"target": "ESNext", // 将代码编译为最新版本的 JS
"module": "ESNext", // 使用 ES Module 格式打包编译后的文件
"moduleResolution": "node", // 使用 Node 的模块解析策略
"lib": ["ESNext", "DOM", "DOM.Iterable"], // 引入 ES 最新特性和 DOM 接口的类型定义
"skipLibCheck": true, // 跳过对 .d.ts 文件的类型检查
"resolveJsonModule": true, // 允许引入 JSON 文件
"isolatedModules": true, // 要求所有文件都是 ES Module 模块。
"noEmit": true, // 不输出文件,即编译后不会生成任何js文件
"jsx": "preserve", // 保留原始的 JSX 代码,不进行编译
"strict": true, // 开启所有严格的类型检查
"noUnusedLocals": true, //报告未使用的局部变量的错误
"noUnusedParameters": true, //报告函数中未使用参数的错误
"noFallthroughCasesInSwitch": true, //确保switch语句中的任何非空情况都包含
"esModuleInterop": true, // 允许使用 import 引入使用 export = 导出的内容
"allowJs": true, //允许使用js
"baseUrl": ".", //查询的基础路径
"paths": { "@/*": ["src/*"], "#/*": ["types/*"] } //路径映射,配合别名使用
},
//需要检测的文件
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
"references": [{ "path": "./tsconfig.node.json" }] //为文件进行不同配置
}
2、修改tsconfig.node.json
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "Node",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}
3、新建 src/typings.d.ts(在src文件夹下新建)
//声明window上自定义属性,如事件总线
declare interface Window {
eventBus: any;
}
//声明.vue文件
declare module "*.vue" {
import { DefineComponent } from "vue";
const component: DefineComponent<object, object, any>;
export default component;
}
提示:遇到ts报错,有些时候是配置未生效,可以重启vscode或ts服务(vscode快捷键 ctrl+shift+p调出命令行,输入Restart TS Server)
4、修改package.json
"scripts": {
"ts": "vue-tsc --noEmit",
},
运行 yarn run ts 即可查看文件是否有ts类型错误