Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid relative path import hell in react-native?

I'm new to react-native coming from vue background, one thing I hate in react is having to use relative path imports in my components, I find myself doing something like:

import HomeScreen from '../../components/screens/HomeScreen'

If my folder structure changes it means I will have to do a search and replace in all of m components using that component, not cool and prone to be a dev hell.

Is it possible to use absolute paths like with node modules, is there a library where I can use aliases or similar, with vue I could import my components in the app.js like Vue.component('home-screen ...) and I could use them without having to import.

like image 880
gabogabans Avatar asked Jul 23 '20 01:07

gabogabans


1 Answers

you can add a package.json file with a name key

{
  "name": "@components"
}

in any folder and metro will recognize it.

You can then import as @components/screens/HomeScreen

If you are using vscode, you can add a jsconfig.json file to your project root to enable import autocomplete.

Here is mine:

{
  "compilerOptions": {
    "baseUrl": "",
    "paths": {
      "@components/*": ["src/components/*"],
      "@helper/*": ["src/helper/*"],
      "@actions/*": ["src/actions/*"],
      "@constants/*": ["src/constants/*"],
      "@primitives": ["src/primitives/index.js"],
      "@graphql": ["src/graphql/index.js"],
      "@services/*": ["src/services/*"],
      "@assets/*": ["assets/*"]
    }
  }
}
like image 190
Steven Bell Avatar answered Sep 29 '22 09:09

Steven Bell