Add absolute paths to app created by “Create React App”

家住魔仙堡 提交于 2021-01-21 10:22:10

问题


I have created an app by Create React App and to be more specific I'm also using typescript.

I can't figerout how to set absolute paths to access to my components, pages, etc..

In a different scenario I would update my tscongig with something like:

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

but I have no idea how to implement this as I'm using react-scripts any idea?


回答1:


Create a tsconfig.json file and add the code below.

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": [
    "src"
  ]
}

Then you can import your components as

import Header from 'components/Header';



回答2:


You should be able to use the same approach if create a jsconfig.json file in your solution, which supports the same baseUrl and rootPath properties as tsconfig.

Alternative is adding an .env file in your solution with the following line:

NODE_PATH=src/

Also, apart from the env file add this to your jsconfig.json

{
  "rootDir": "src",
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "*": ["*"]
    }
  }
}

This should resolve both the compiler being able to find your absolute imports, and linter handling them properly.



来源:https://stackoverflow.com/questions/55219307/add-absolute-paths-to-app-created-by-create-react-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!