Natim
Natim

Reputation: 18092

How to configure Expo to allow global module imports?

I am looking for a way to get rid of these

import { get_records } from ../../../../store/actions/async';

To be honest I tried a lot of tricks:

The same questions goes for assets.

I've seen solution with Webpack and Babel but I don't use them with React Native.

How do you manage to do that?

Upvotes: 1

Views: 2402

Answers (2)

Natim
Natim

Reputation: 18092

Actually I was using Babel without noticing.

npm install --save-dev babel-plugin-module-resolver
npm install --save-dev eslint-import-resolver-babel-module

.babelrc

{
  "presets": ["babel-preset-expo"],
  "env": {
    "development": {
      "plugins": ["transform-react-jsx-source"]
    }
  },
  "plugins": [
    ["module-resolver", {
      "alias": {
        "~mobile": "./src",
        "~assets": "./assets"
      }
    }]
  ]
}

.eslintrc

{
    "settings": {
      "import/resolver": {
        "babel-module": {
          "alias": {
            "~mobile": "./src",
            "~assets": "./assets"
          }
        }
      }
    }
}

Then I use it like that:

import { addToFavorite, removeFromFavorite } from '~mobile/store/actions';

await Font.loadAsync({
  'cabin-reg': require('~assets/fonts/Cabin/Cabin-Regular.ttf'),
  'league-spartan': require('~assets/fonts/LeagueSpartan/leaguespartan-bold.ttf')
 })

Upvotes: 1

Roy Wang
Roy Wang

Reputation: 11260

If you are using Expo, you must be using babel because only ES6 version of the libraries are shipped. Even projects created with react-native init come with babel by default. Check your project folder, it should have a .babelrc file.

You can then use babel-plugin-root-import:

import { get_records } from '~/store/actions/async';

.babelrc:

{
  "presets": ["babel-preset-expo"],
  "plugins": [
    [
      "babel-plugin-root-import",
      {
        "rootPathSuffix": "src"
      }
    ]
  ]
}

Upvotes: 1

Related Questions