Vue3项目中TypeScript(TS)相关配置

兼容JS

TS中是不允许使用JS,如果是新开发的也建议都用TS,但是有可能我们要用一些之前的JS,这就需要设置一下

tsconfig.app.jsoncompilerOptions内添加

1
"allowJs": true,

类型定义文件

在 TypeScript 中,如果你有一个类型定义文件(通常是以 .d.ts 为扩展名的文件)。

个人建议类型定义都放在src/assets/types/文件夹下。

全局使用

注意

命名要防止和其他地方冲突。

如果你的类型定义文件不使用模块系统,而是定义了全局类型,你可以直接在 TypeScript 项目的 tsconfig.json 文件中通过 include 来包含这些类型定义文件。

TypeScript 编译器会自动识别并将其应用于整个项目。

我这里把全局使用的类型定义都放在了src/types/下。

全局定义的名称不能重复,全局定义的类型不需要导出(export)

1
2
3
4
interface ZUser {
name: string;
age: number;
}

我的项目是引用了tsconfig.app.json,所以我在该文件中添加:

1
2
3
4
5
6
7
8
{
"include": [
"env.d.ts",
"src/**/*",
"src/**/*.vue",
"src/types/*.d.ts"
],
}

配置过后,可能需要重启IDEA才能生效。

引用方式使用

user.d.ts

1
2
3
4
export interface User {
name: string;
age: number;
}

使用

1
2
3
4
5
6
import type { ZUser } from '@/assets/types/user'

const person: User = {
name: 'Alice',
age: 30
};

扩展window属性

window是全局唯一的对象,在JS中我们可以方便的添加任何我们想全局访问的属性,但是在TS中不行。

我们需要扩展 Window 接口

添加一个全局的定义文件 globals.d.ts

1
2
3
interface Window {
loginUser?: ZLoginUser
}

这样我们就可以在TS中使用了

1
window.loginUser = {name:"张三"}

格式化与规则配置

格式化使用Prettier来替代ESLint格式化代码,格式化会更快。

详细查看

https://www.psvmc.cn/article/2025-05-13-vue3-eslint-prettier.html

格式化配置

.prettierrc.json

1
2
3
4
5
6
7
8
9
{
"$schema": "https://json.schemastore.org/prettierrc",
"semi": false,
"tabWidth": 2,
"singleQuote": true,
"printWidth": 100,
"trailingComma": "none",
"endOfLine": "auto"
}

ESLint配置

eslint.config.ts

这里主要是配置了 允许使用any,格式化使用Prettier来替代ESLint格式化代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { globalIgnores } from 'eslint/config'
import { defineConfigWithVueTs, vueTsConfigs } from '@vue/eslint-config-typescript'
import pluginVue from 'eslint-plugin-vue'
import skipFormatting from '@vue/eslint-config-prettier/skip-formatting'
import eslintConfigPrettier from '@vue/eslint-config-prettier' //添加这一行代码

export default defineConfigWithVueTs(
{
name: 'app/files-to-lint',
files: ['**/*.{ts,mts,tsx,vue}']
},

globalIgnores(['**/dist/**', '**/dist-ssr/**', '**/coverage/**']),

pluginVue.configs['flat/essential'],
vueTsConfigs.recommended,
skipFormatting,
eslintConfigPrettier, //添加这一行代码
// 可以自定义配置,例如:
{
rules: {
'@typescript-eslint/no-unused-vars': 0, //允许未使用的变量
'@typescript-eslint/no-explicit-any': 0, //允许使用any类型
'@typescript-eslint/no-unused-expressions': 0, //允许未使用的表达式
'vue/block-lang': 0 //允许使用vue/block-lang
}
}
)

IDEA

IDEA中Actions on Save中建议使用Run Prettier,关闭Run eslint --fix

当然只使用Run eslint --fix也可以。

image-20250513140541926

详细配置

image-20251021123654667

默认不格式化JSON,这里也添加上

1
**/*.{js,ts,jsx,tsx,vue,astro,json}