如何解决VS Code中tsconfig.json的模式匹配报错问题
如何解决Visual Studio Code中显示的TypeScript模式匹配报错
问题现象
开发TypeScript+React应用时,tsconfig.json文件抛出报错,提示**/*模式匹配规则无法找到index.ts文件:
应用本身通过Webpack可以正常编译运行,报错仅在VS Code中显示。项目使用Webpack作为构建工具,配置入口文件为index.tsx,不存在index.ts文件,相关配置如下:
webpack.config.js配置:
const path = require('path'); module.exports = { entry: './src/main/ts/index.tsx', module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/, }, ], }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, output: { path: __dirname, filename: './src/main/resources/static/built/bundle.js' }, };
package.json依赖配置:
"dependencies": { "@types/lodash": "^4.14.182", "@types/react": "^18.0.14", "@types/react-dom": "^18.0.5", "react": "^18.2.0", "react-dom": "^18.2.0", "rest": "^1.3.1", "sockjs-client": "^1.0.3", "stompjs": "^2.3.3" }, "devDependencies": { "@babel/core": "^7.1.0", "@babel/preset-env": "^7.1.0", "@babel/preset-react": "^7.0.0", "babel-loader": "^8.0.2", "ts-loader": "^9.3.0", "typescript": "^4.7.4", "webpack": "^5.73.0", "webpack-cli": "^4.10.0" }
问题原因
该报错和Webpack构建逻辑无关:Webpack通过ts-loader编译时,只会从配置的index.tsx入口递归解析依赖文件,不会全量扫描tsconfig.json中include字段指定的所有文件;但VS Code内置的TypeScript语言服务会严格读取tsconfig.json配置做全量文件扫描校验,当配置的通配规则和实际存在的文件后缀/路径不匹配时,就会抛出该提示。
解决步骤
按以下优先级操作即可消除报错,不需要修改现有Webpack和依赖配置:
- 修正
tsconfig.json配置
打开项目根目录的tsconfig.json,首先检查files字段:如果该字段为空,或填写了不存在的index.ts路径,直接删除该字段。
随后修改include字段,不要使用无差别的**/*通配规则,明确指定需要扫描的文件后缀,参考配置如下:{ "compilerOptions": { // 保留原有compilerOptions配置即可,例如jsx、target、moduleResolution等 "jsx": "react-jsx", "target": "ES6", "module": "ESNext", "moduleResolution": "node", "strict": true }, "include": [ "src/main/ts/**/*.ts", "src/main/ts/**/*.tsx" ], "exclude": ["node_modules", "src/main/resources/static/**/*"] } - 切换VS Code使用项目本地的TypeScript版本
VS Code内置的TypeScript版本和项目本地安装的typescript@4.7.4版本存在兼容差异时,也会出现扫描错误,切换方式:- 按
Ctrl+Shift+P(Mac系统按Cmd+Shift+P)打开命令面板 - 输入并选择
TypeScript: Select TypeScript Version - 选择
Use Workspace Version,即项目node_modules中安装的TypeScript版本
- 按
- 重启TS服务清缓存
配置修改完成后如果报错未消失,打开命令面板,输入并选择TypeScript: Restart TS Server,等待服务重启完成后报错就会消除。
内容的提问来源于stack exchange,提问作者Socrates
相关产品推荐
相关产品推荐

