How do I configure absolute paths for imports in TypeScript based React Native apps?

前端 未结 5 2057
生来不讨喜
生来不讨喜 2020-12-29 07:27

In order to avoid \'../../../../\' style relative imports in a TypeScript based React Native app, I would like to configure the app so that I can use absolute imports instea

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-29 08:30

    All of the other answers didn't work for me with a freshly created React Native + Typescript project.

    What worked for me was setting both baseUrl and paths in tsconfig.json:

    {
        "baseUrl": ".",
        "paths": {
          "NAME_IN_PACKAGE_JSON/*": ["./*"]
        }
    }
    

    Replace NAME_IN_PACKAGE_JSON with your package.json's name field. E.g. if the name field is myapp you can do:

    import HomeScreen from "myapp/screens/HomeScreen";

提交回复
热议问题