tsconfig配置的paths路径别名启动项目后被移除无法生效如何解决
项目配置路径别名时tsconfig.json paths字段被自动移除问题
在项目中配置路径别名时遇到如下问题:启动应用后,tsconfig.json中的paths对象会被自动移除,所有路径别名均无法生效。
初始tsconfig.json配置如下:
{ "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", "baseUrl": "src", "paths": { "@styles/*": ["styles/*"], "@components/*": ["components/*"] } }, "include": [ "src" ] }
启动项目后配置被自动修改为:
{ "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", "baseUrl": "src" }, "include": [ "src" ] }
控制台报错如下:
尝试过的未生效方案
- 方案1:将paths配置单独抽离到tsconfig.paths.json,在主tsconfig.json中通过extends字段继承该配置,对应配置如下:
// tsconfig.json { "extends": "./tsconfig.paths.json", "compilerOptions": { ... "baseUrl": "src" } }
// tsconfig.paths.json { "compilerOptions": { "paths": { "@styles/*": ["./styles/*"], "@components/*": ["./components/*"] } } }
- 方案2:使用craco配置别名,未生效。
最终解决方案
重启VS Code和开发服务,配合craco配置即可解决该问题。
内容的提问来源于stack exchange,提问作者MrDeibl
相关产品推荐
相关产品推荐

