我在使用 VSCode 时遇到问题,在使用 React、TypeScript 和 SWC 设置新的 Vite 项目后,JS/TS 语言服务反复崩溃。这就是我所做的:
使用yarn create vite my-app创建一个新的Vite项目,并使用以下选项:
Framework: React
Variant: TypeScript + SWC
设置 ESLint 和 Prettier。
重启 VSCode 后,出现错误: JS/TS 语言服务立即崩溃 5 次。该服务将不会重新启动。
我读到这可能是 VSCode 版本问题,所以我检查了一下,我的 VSCode 版本是 1.89.1(最新)。当我将 TypeScript 降级到 4.x 版本时,IntelliSense 似乎可以正常工作。但是,我更喜欢使用 TypeScript 5.x,因为它允许将 moduleResolution 设置为捆绑器。
我的设置:
package.json
{
"name": "vite-app",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/react": "^18.2.66",
"@types/react-dom": "^18.2.22",
"@typescript-eslint/eslint-plugin": "^7.2.0",
"@typescript-eslint/parser": "^7.2.0",
"@vitejs/plugin-react-swc": "^3.5.0",
"eslint": "^8.57.0",
"eslint-config-airbnb": "^19.0.4",
"eslint-config-airbnb-typescript": "^18.0.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-jsx-a11y": "^6.8.0",
"eslint-plugin-react": "^7.34.1",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.6",
"typescript": "^5.1.5",
"vite": "^5.2.0"
},
"packageManager": "[email protected]"
}
tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src", "vite.config.ts"],
"references": [{ "path": "./tsconfig.node.json" }]
}
.eslintrc.cjs
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'airbnb',
'airbnb-typescript',
'airbnb/hooks',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
'prettier'
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
parserOptions: {
project: './tsconfig.json',
tsconfigRootDir: __dirname
},
plugins: [
'react-refresh',
'@typescript-eslint',
'import',
'jsx-a11y',
'react',
'react-hooks'
],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true }
],
'react/react-in-jsx-scope': 'off',
'react/function-component-definition': 'off',
'arrow-body-style': 'off',
'import/extensions': [
'error',
'ignorePackages',
{
js: 'never',
jsx: 'never',
ts: 'never',
tsx: 'never'
}
]
}
};
vscode 的 GH 上有很多问题,这表明 https://github.com/yarnpkg/berry/issues/6270 是原因。
建议的解决方案是将 TS 设置为版本< 5.4.4 (
"typescript": "5.4.3"
)
添加
"typescript.tsserver.experimental.useVsCodeWatcher": false
vscode settings.json 也对我有用。