如何配置react-script以便它不会覆盖'start'上的tsconfig.json

Cod*_*ern 16 typescript reactjs react-scripts create-react-app

我目前正在使用create-react-app我的一个项目来引导它.基本上,我试图在tsconfig.json中设置路径,方法是将它们添加到create-react-app生成的默认tsconfig.json中:

"baseUrl": "./src",
"paths": {
  "interfaces/*": [
    "common/interfaces/*",
  ],
  "components/*": [
    "common/components/*",
  ],
},
Run Code Online (Sandbox Code Playgroud)

但是,每次运行yarn start基本上都运行时react-scripts start,它会删除我的更改并再次生成默认配置.

如何告诉create-react-app使用我的自定义配置?

Gle*_*enn 10

通过使用来自本期的建议,我能够做到这一点

放置配置选项,将react脚本喜欢的脚本删除到一个单独的文件(例如,paths.json)中,并通过extends指令从tsconfig.json中引用它。

path.json:

{
  "compilerOptions": {
  "baseUrl": "./src",
  "paths": {
    "interfaces/*": [ "common/interfaces/*"],
    "components/*": [ "common/components/*"],
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

tsconfig.json

{
  "extends": "./paths.json"
   ...rest of tsconfig.json
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么他们要这么做?实在是太烦人了 @TranquilMarmot 你找到解决方案了吗? (32认同)
  • 看起来唯一的选择是降级或弹出。CRA 维护者对社区表现出的蔑视令人非常沮丧 (11认同)
  • 似乎这不再适用于较新版本的反应脚本 (10认同)
  • 我就是因为这个才被弹出的。任何人都有 PR 或者我应该开始深入研究代码以找到在哪里更改它? (2认同)
  • 看起来它仍然有效,但无论如何都抱怨“不能设置compilerOptions.paths(不支持别名导入)”。 (2认同)

Gen*_*gen 7

你不能,我不确定你什么时候可以。我一直在尝试使用 baseUrl 和路径,这样我就可以避免相对导入,但正如您所看到的,它们是故意删除某些值。“(还)”令人鼓舞,但(叹气)谁知道他们什么时候会正式支持它。我建议订阅这个 github问题,以便在发生变化时/当它发生变化时收到警报。

The following changes are being made to your tsconfig.json file:
      - compilerOptions.baseUrl must not be set (absolute imports are not supported (yet))
      - compilerOptions.paths must not be set (aliased imports are not supported)
Run Code Online (Sandbox Code Playgroud)


Mic*_*cip 5

Create React App当前不支持baseUrl。但是,有一种解决方法...要baseUrl同时为webpack和IDE 进行设置,您必须执行以下操作:

  1. .env使用以下代码创建文件:
NODE_PATH=./
Run Code Online (Sandbox Code Playgroud)
  1. 创建一个tsconfig.paths.json包含以下代码的文件:
{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "src/*": ["*"]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)
  1. 将以下行添加到 tsconfig.json
{
  "extends": "./tsconfig.paths.json",
  ...
}
Run Code Online (Sandbox Code Playgroud)

  • 很高兴你把它解决了。警告是预料之中的,我也明白了。 (2认同)
  • @Microcipcip 我无法在react-scripts v3 或v4 中使用它:( (2认同)