- Published on
Absolute Paths in Create React App
- Authors
- Name
- Yair Mark
- @yairmark
I recently read an article about how newer versions of Create React App support using absolute paths to import dependencies from within your project.
For example without this you normally would have to write something like:
import Loader from '../../components/Loader'
After setting up your project to support absolute imports you can change the above to:
import Loader from 'components/Loader'
The article also recommends chaning top level folders in your projects src
folder to start with uppercase letters (AKA pascal case) so that you can easily differentiate your project's imports from those that you are getting from a node depedency. So using this convention the above would become:
import Loader from 'Components/Loader'
Using this approach is much better as your imports look consistent no matter how deep different components that use them are. This also means that you can easily copy paste imports from one file into another without having to change anything.
As per the article setting this up was as simple as ensuring I had a new enough version of Create React App and then adding a file called jsconfig.json
in the root of my project (the same level as your package.json
file). This file has the following contents:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}