如何配置VSCode实现React Native自动导入且无TypeScript错误
解决方案
1. 调整jsconfig.json配置(核心)
checkJs是VSCode提供JS智能导入提示的必要依赖不能关闭,我们只需要屏蔽掉不需要的TypeScript类型校验报错即可,修改后的配置参考:
{ "compilerOptions": { "target": "ES6", "module": "commonjs", "allowSyntheticDefaultImports": true, "checkJs": true, "jsx": "react-native", // 新增以下配置关闭不必要的严格校验 "strict": false, "noImplicitAny": false, "noImplicitThis": false, "strictNullChecks": false, "allowJs": true, // 屏蔽常见的无类型报错码,可根据自己遇到的报错码补充 "diagnostics": { "ignoredCodes": [2304, 2307, 7006, 7005, 2554] } }, "exclude": ["node_modules"], "include": ["src/**/*"] }
上面的错误码对应场景:
- 2304:找不到变量
- 2307:找不到模块
- 7006:参数隐式为any
- 7005:变量隐式为any
- 2554:参数个数不匹配
2. 补充VSCode settings.json配置
新增关闭JavaScript内置校验的配置项,修改后参考:
{ "workbench.iconTheme": "material-icon-theme", "editor.fontFamily": "JetBrains Mono", "editor.fontLigatures": true, "editor.fontSize": 13, "editor.formatOnSave": true, "git.autofetch": true, "git.confirmSync": false, "[javascript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "terminal.external.osxExec": "iTerm.app", "typescript.validate.enable": false, // 新增这一行关闭JS内置校验 "javascript.validate.enable": false, "javascript.suggestionActions.enabled": true }
3. 可选:添加全局类型声明文件
如果还是存在第三方模块无类型的报错,在项目根目录新增declarations.d.ts文件,写入以下内容即可:
// 声明所有未知模块都不会触发类型报错 declare module '*';
配置完成后重启VSCode或者重载窗口(快捷键Ctrl+Shift+P/Cmd+Shift+P,输入Reload Window执行)即可生效,此时既保留智能导入提示,也不会出现多余的TypeScript报错。
内容的提问来源于stack exchange,提问作者Ale
相关产品推荐
相关产品推荐

