typescript - create-react-app Typescript 3.5,路径别名

标签 typescript create-react-app

我试图通过将这些值添加到 tsconfig.json 来在我的项目中设置路径别名:

  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "@store/*": ["store/*"]
    },

如果我创建一个导入,IntelliJ 或 VSCode 都不会打扰我:
import { AppState } from '@store/index';

但是当我编译应用程序时,我收到了这个警告:
The following changes are being made to your tsconfig.json file:
  - compilerOptions.paths must not be set (aliased imports are not supported)

它轰炸说它找不到引用:
TypeScript error in C:/xyz.tsx(2,26):
Cannot find module '/store'.  TS2307

是否有任何解决方法或不受 create-react-app --typescript 支持?

最佳答案

解决方法是 react-app-rewire-alias (对于 react-app-rewiredcustomize-cracraco ):
根据文档替换 react-scriptspackage.json并配置下一步:

// config-overrides.js
const {alias, configPaths} = require('react-app-rewire-alias')

module.exports = function override(config) {
  return alias(configPaths('./tsconfig.paths.json'))(config)
}
像这样在 json 中配置别名:
// tsconfig.paths.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "example/*": ["example/src/*"],
      "@library/*": ["library/src/*"]
    }
  }
}
并将此文件添加到 extends主要 typescript 配置文件的部分:
// tsconfig.json
{
  "extends": "./tsconfig.paths.json",
  // ...
}
使用 create-reat-app 4.0 和 typescript 导入文件 NearSrc.tsx 在 src 之外的工作示例演示工作解决方案是 here

关于typescript - create-react-app Typescript 3.5,路径别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57070052/

相关文章:

javascript - 访问 token 和响应数据

typescript - 使用数字管道抛出 InvalidPipeArgumentException(管道 '1' 的无效参数 'DecimalPipe')

javascript - Typescript 日期减法结果为 0,而不是实际的时间差。

node.js - React错误找不到模块 './lib/api/node.js'

reactjs - 创建 React Native 应用程序时出错

angularjs - ngRepeat 暂时显示重复列表

angular - 如果没有用户以 angular 4 登录,标题应该隐藏

javascript - 禁用 create-react-app 的 SKIP_PREFLIGHT_CHECK 有缺点吗?

docker - 无法从 Nginx 反向代理后面的 docker 容器提供静态资源

reactjs - 当 docker 容器内的数据发生更改时,Create-react-app 服务器不会重新编译