本文介绍了create-react-app Typescript 3.5,路径别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to setup Path alias in my project by adding these values to tsconfig.json:

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

如果我创建一个导入,IntelliJ 或 VSCode 都不会打扰我:

And if I create an import, neither IntelliJ or VSCode bother me:

import { AppState } from '@store/index';

但是当我编译应用程序时,我收到此警告:

But when I compile the application I get this warning:

The following changes are being made to your tsconfig.json file:
  - compilerOptions.paths must not be set (aliased imports are not supported)

并且它轰炸说它找不到参考:

And it bombs saying it cannot find the reference:

TypeScript error in C:/xyz.tsx(2,26):
Cannot find module '/store'.  TS2307

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

Is there any workaround or it is not supported by create-react-app --typescript?

推荐答案

解决方案是 react-app-rewire-alias(对于 react-app-重新接线customize-cracraco) :

The solution is react-app-rewire-alias (for react-app-rewired or customize-cra or craco) :

根据文档替换 package.json 中的 react-scripts 并配置下一步:

According docs replace react-scripts in package.json and configure next:

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

module.exports = function override(config) {
  return alias(configPaths('./tsconfig.paths.json'))(config)
}

像这样在 json 中配置别名:

Configure aliases in json like this:

// tsconfig.paths.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "example/*": ["example/src/*"],
      "@library/*": ["library/src/*"]
    }
  }
}

并在主打字稿配置文件的extends部分添加此文件:

And add this file in extends section of main typescript config file:

// tsconfig.json
{
  "extends": "./tsconfig.paths.json",
  // ...
}

使用 create-reat-app 4.0 和 typescript 导入文件 NearSrc.tsx 在 src 之外的工作示例演示工作解决方案是 这里

The worked example using create-reat-app 4.0 with typescript imports file NearSrc.tsx outside of src demonstrate worked solution is here

这篇关于create-react-app Typescript 3.5,路径别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 03:06