I've written before about configuring React projects to use absolute vs relative path imports. I simply think it's cleaner and less error prone. However, many people responded that they don't like it.
Recently, I've tried doing the same in a brand new React Native project. Unfortunately, the metro bundler just refuses to accept the baseUrl setting in tsconfig.json. So, I stumbled across another way to do this thanks to @ChrisAchard's great React Native course on Egghead.io.
In each directory and subdirectory you want direct access to, you can add a package.json file that simply contains a name property. The name property should be the name of that directory.
{
"name": "src"
}With a directory structure like src/components/Header/... and src/assets/icons, you can enable imports like this:
import Header from 'components/Header/Header'
or
import { house } from `assets/icons`To do that, you need a package.json file in the src, components, and assets directory.
To be honest, this is a bit ugly. I'd really like to just import like I had in my previous post. However, I was tired of fighting the bundler and went this way for a quick win. Down the road, I'll figure out the real issue and just remove the package.json files.
IMPORTANT: This works great except Visual Studio Code will NOT understand this. You'll still have to modify your tsconfig.json file to include a "baseUrl": "src" setting. Then Code will be happy and understand these imports.
UPDATE: My final resolution to this was answered on SO. Now, I no longer need these individual package.json files.