create-react-app启动时自动覆盖tsconfig.js的处理

2,258 阅读1分钟

问题

create-react-app创建的项目,引入了ts,在tsconfig.json中配置了path别名后,重新启动时,会重新自动生成一个tsconfig.json,覆盖tsconfig.json中配置的path。

原因:CRA为了保持“正常”工作,从而限制某些功能。

解决办法

  1. 创建tsconfig-extend.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}
  1. tsconfig.json中添加配置extends
{
  "compilerOptions": {
    "target": "es5",
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",
    "noImplicitAny": false
  },
  "include": [
    "src"
  ],
  "extends": "./tsconfig-extend.json"  // 指定扩展的配置的路径
}
  1. 重启服务npm start,运行后看到一个警告:compilerOptions.paths must not be set (aliased imports are not supported), 可知alias是不被支持的,但不影响正常使用。

参考: