androidreact-nativealiasbabeljsbabel-plugin

Unable to resolve module when building react-native .apk, babel-plugin-module-resolver aliases


I am using babel-plugin-module-resolver to deal with ../../../ hell. In my .babelrc I have:

{
  "presets": [
    "react-native",
    "babel-preset-react-native-stage-0/decorator-support",
    "react-native-dotenv"
  ],
  "env": {
    "development": {
      "plugins": [
        ["module-resolver", {
          "cwd": "babelrc",
          "extensions": [
            ".js",
            ".ios.js",
            ".android.js"
          ],
          "alias": {
            "@assets": "./src/assets",
            "@features": "./src/features",
            "@common": "./src/common",
            "@config": "./src/config",
            "@services": "./src/services"
          }
        }],
        "transform-react-jsx-source"
      ]
    }
  }
}

Example usage: import { Text } from '@common'

And this is all working great in development mode, however when I try to release an Android .apk file with cd android && ./gradlew assembleRelease && cd .. I get an error:

Unable to resolve module @common from /home/ppozniak/Projects/project-name/src/Root.js: Module does not exist in the module map

It seems that gradlew isn't using my .babelrc?

versions

   "babel-plugin-module-resolver": "^3.0.0",
   "babel-preset-react-native": "^4.0.0",
   "react-native": "0.50.3",
   "react": "16.0.0",

Thanks in advance.


Solution

  • Okay it was just me being silly a little bit. Looking at my .babelrc you can

    "env": {
        "development": {
    

    And that was issue. After this some other bugs popped out with Android but eventually I've managed to fix all of them.

    So lesson for future: watch for your envs.

    My babelrc now:

    {
      "presets": [
        "react-native",
        "babel-preset-react-native-stage-0/decorator-support",
      ],
      "plugins": [
        "transform-react-jsx-source", ["module-resolver", {
          "extensions": [
            ".js",
            ".ios.js",
            ".android.js"
          ],
          "alias": {
            "@assets": "./src/assets",
            "@features": "./src/features",
            "@common": "./src/common",
            "@config": "./src/config",
            "@services": "./src/services"
          }
        }]
      ]
    }