【问题标题】:tsconfig.json gets reset after yarn start React apptsconfig.json 在纱线启动 React 应用程序后被重置
【发布时间】:2019-04-25 14:03:23
【问题描述】:

我使用create-react-app app_name --typescript 创建了我的 React 应用程序。由于 Typescript 不支持 NODE_PATH。我正在尝试在 tsconfig.json 中使用 baseUrl。

但是,每次在将"baseUrl": "src" 放入"compilerOptions" 之后运行yarn start,baseUrl 都会消失。我觉得yarn start 重置了tsconfig.json

如何阻止它重置文件?

**tsconfig.json**
{
  "compilerOptions": {
    "target": "es6",
    "allowJs": true,
    "skipLibCheck": false,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve"
  },
  "include": ["src"]
}

【问题讨论】:

标签: typescript


【解决方案1】:

不再支持路径别名

但是您现在可以这样做直接导入相对于src 目录的文件

转到您的tsconfig.json 文件添加baseUrl"."

"compilerOptions": {
    "baseUrl":".",
    ...

然后你就可以直接导入相对于src目录的东西了

import Myfile from "src/myfile.js"

这对我有用!

【讨论】:

    【解决方案2】:

    有一个解决方法。

    1. 创建一个新文件,说“base-tsconfig.json”并将 baseUrl 配置和路径放在那里。这些不会被 CRA 覆盖。
    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@/*": ["src/*"]
        }
      }
    }
    
    1. 使用您的自定义配置扩展主 tsconfig.json 文件
    {
      "extends": "./base-tsconfig.json"
    }
    

    更多信息here

    【讨论】:

      【解决方案3】:

      baseUrl 问题已在 create-react-app 3 中修复。它现在支持两个值 - node_modules(默认值)和 src(参考这个 comment

      使用 CHANGELOG 中的说明升级 create-react-app。

      例如:如果你想从 2.1.x 升级到 3.0.0,

      npm install --save --save-exact react-scripts@3.0.0
      

      yarn add --exact react-scripts@3.0.0
      

      注意:我曾经同时拥有jsconfig.jsontsconfig.json,但一开始就报错了。删除 jsconfig.json 解决了这个问题。

      【讨论】:

        【解决方案4】:

        create-react-app 当前删除了 baseUrl 属性,不幸的是,我认为它们目前不支持路径:(

        在此处阅读更多信息https://github.com/facebook/create-react-app/issues/5585

        【讨论】:

        猜你喜欢
        • 2020-11-03
        • 1970-01-01
        • 2021-01-05
        • 2018-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-04
        • 1970-01-01
        相关资源
        最近更新 更多