項(xiàng)目代碼同步至碼云 weiz-vue3-template
關(guān)于tsconfig的配置字段可查看其他文檔,如 typeScript tsconfig配置詳解
tsconfig.json
文件修改如下:
{
"compilerOptions": {
"target": "ESNext", // 將代碼編譯為最新版本的 JS
"useDefineForClassFields": true,
"module": "ESNext", // 使用 ES Module 格式打包編譯后的文件
"lib": ["ESNext", "DOM", "DOM.Iterable"], // 引入 ES 最新特性和 DOM 接口的類型定義
"skipLibCheck": true, // 跳過對(duì) .d.ts 文件的類型檢查
"esModuleInterop": true, // 允許使用 import 引入使用 export = 導(dǎo)出的內(nèi)容
"sourceMap": true, // 用來指定編譯時(shí)是否生成.map文件
"allowJs": false, // 是否允許使用js
"baseUrl": ".", // 查詢的基礎(chǔ)路徑
"paths": { // 路徑映射,配合別名使用
"@/*": ["src/*"],
"@build/*": ["build/*"],
"#/*": ["types/*"]
},
/* Bundler mode */
"moduleResolution": "node", // 使用 Node/bundler 的模塊解析策略
"allowImportingTsExtensions": true,
"resolveJsonModule": true, // 允許引入 JSON 文件
"isolatedModules": true, // 要求所有文件都是 ES Module 模塊。
"noEmit": true, // 不輸出文件,即編譯后不會(huì)生成任何js文件
"jsx": "preserve", // 保留原始的 JSX 代碼,不進(jìn)行編譯
/* Linting */
"strict": true, // 開啟所有嚴(yán)格的類型檢查
"noUnusedLocals": true, // 報(bào)告未使用的局部變量的錯(cuò)誤
"noUnusedParameters": true, // 報(bào)告函數(shù)中未使用參數(shù)的錯(cuò)誤
"noFallthroughCasesInSwitch": true // 確保switch語句中的任何非空情況都包含
},
"include": [ // 需要檢測的文件
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue",
"mock/*.ts",
"types/*.d.ts",
"vite.config.ts"
],
"exclude": [ // 不需要檢測的文件
"dist",
"**/*.js",
"node_modules"
],
"references": [{ "path": "./tsconfig.node.json" }] // 為文件進(jìn)行不同配置
}
tsconfig.node.json
修改文件如下:
{
"compilerOptions": {
"composite": true, // 對(duì)于引用項(xiàng)目必須設(shè)置該屬性
"skipLibCheck": true, // 跳過對(duì) .d.ts 文件的類型檢查
"module": "ESNext", // 使用 ES Module 格式打包編譯后的文件
"moduleResolution": "Node", // 使用 Node/bundler 的模塊解析策略
"allowSyntheticDefaultImports": true // 允許使用 import 導(dǎo)入使用 export = 導(dǎo)出的默認(rèn)內(nèi)容
},
"include": ["vite.config.ts"]
}
類型定義
新建文件夾 types
,用來存放類型定義。比如新建 index.d.ts
:
type TargetContext = "_self" | "_blank";
type EmitType = (event: string, ...args: any[]) => void;
type AnyFunction<T> = (...args: any[]) => T;
type PropType<T> = VuePropType<T>;
type Writable<T> = {
-readonly [P in keyof T]: T[P];
};
type Nullable<T> = T | null;
type NonNullable<T> = T extends null | undefined ? never : T;
interface Fn<T = any, R = T> {
(...arg: T[]): R;
}
interface PromiseFn<T = any, R = T> {
(...arg: T[]): Promise<R>;
}
后續(xù)也可以新增其他文件,比如 global.d.ts
存放全局定義,router.d.ts
存放路由定義等
類型檢查命令
修改 package.json
,新增以下命令:文章來源:http://www.zghlxwxcb.cn/news/detail-746074.html
"scripts": {
"type-check": "vue-tsc --noEmit"
},
保存后,運(yùn)行 npm run type-check
,即可項(xiàng)目中是否有類型錯(cuò)誤文章來源地址http://www.zghlxwxcb.cn/news/detail-746074.html
到了這里,關(guān)于Vite4+Typescript+Vue3+Pinia 從零搭建(2) - ts配置的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!