通过CRA (create-react-app) 和 craco+craco-alias 创建的typescript模版项目如何设置alias path

2,581 阅读1分钟

问题背景:

使用cra创建的项目每一次重启都会重置tsconfig.json, 导致在tsconfig.json设置的别名失效。

解决方法

方法1

启动项目之后,手动修改tsconfig.json 文件,重新编译 alias生效

craco start

方法2

  1. 创建tsconfig.path.json
  {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@/*": ["src/*"],
          "@svg/*": ["src/assets/svg/*"],
          "@img/*": ["src/assets/images/*"],
          "@icons/*": ["src/assets/icons/*"],
          "@shared/*": ["src/shared/*"],
          "@components/*": ["src/components/*"],
          "@hooks/*": ["src/hooks/*"],
          "@constants/*": ["src/constants/*"],
          "@layout/*": ["src/layout/*"],
          "@services/*": ["src/services/*"]
        }
      }
    }

  1. craco.config.js CracoAlias 配置为
const CracoAlias = require('craco-alias');
...
    {
        plugin: CracoAlias,
        options: {
            source: 'tsconfig',
            baseUrl: '.',
            tsConfigPath: "./tsconfig.path.json"
        }
    }
...
  1. tsconfig.json 文件插入
  "extends": "./tsconfig.path.json",

参考资料

[1] stackoverflow.com/questions/5…

[2] github.com/facebook/cr…