babel-plugin-module-resolver: it's can't use in react-native.

when i use it in my react-native project. and set .babelrc by this:

{ "presets": ["react-native"], "plugins": [ [ "module-resolver", { "root": ["./src"], "extensions": [".js", ".ios.js", ".android.js"], "alias": { "app": "./src", "assets": "./src/assets", "components": "./src/components", "containers": "./src/containers", "models": "./src/models", "routes": "./src/routes", "services": "./src/services", "utils": "./src/utils", "underscore": "lodash" }, } ] ] }

my project struct: image

i changed the file of src/index.js and edit ‘import Toast from ‘./utils/toast’;’ to ‘import Toast from ‘utils/toast’;’ but the node console raise some error like this: image

About this issue

  • Original URL
  • State: open
  • Created 7 years ago
  • Reactions: 4
  • Comments: 55 (5 by maintainers)

Most upvoted comments

@meyer-net have you try yarn start -- --reset-cache?

I found a simple solution for react native users and it’s NOT dependent on babel-plugin-module-resolver just create another package.json file under the ./src folder

package.json

{
	"name":  "src"
}

now the below code will work import Button from 'src/components/Button';

It’s not the best solution and I am not happy with it, but it works.

Faced with same problem. Like @meyer-net i’m using yarn(1.3.2) and have following setup:

package.json

"dependencies": {
  ...
  "react": "16.0.0",
  "react-native": "0.50.3"
  ...
}
"devDependencies": {
  ...
  "babel-plugin-module-resolver": "3.0.0"
  ...
}

.babelrc

{
  "presets": ["react-native"],
  "plugins": [
    ["module-resolver", {
      "root": ["./"],
      "alias": {
        "@src": "./src",
        "@util": "./util"
      }
    }]
  ]
}

project layout: .project_root/index.js import App from '@src/App'; .project_root/src/App.js import MyButton from "@util/base/button/Button"; .project_root/util/base/button/Button.js .project_root/util/base/button/Button.native.js

Also i’m using connected via usb physical device. When i run react-native run-android error is thrown, BUT as @maxhungry said, if try to run with yarn start --reset-cache modules begin to resolve. It even work if i choose to “Enable HOT Reloading” in dev menu. Ok, then i stop packager, launched by yarn start --reset-cache and try react-native run-android again. It works for the first application start, and the same exception is thrown after first HOT reload 😭 As a temporary workaround i use react-native run-android --no-packager to compile project and install it on my device, then yarn start --reset-cache. Well, it seems works so far, it’s not the best solution i guess and maybe something may go wrong further, but for simple project skeleton it works.

@Gr1ver see this to make it work with React Native.

In short: none of the maintainers here use React Native. Of course we want to see this fixed, but we don’t have the time to go out of our way and set up a React Native project to investigate this issue.

But this very project (babel-plugin-module-resolver), being open source, welcomes contributions from any person who is willing to help. It’s just that so far nobody came to us with an actual fix for this problem.

Personally, since this problem has been such a long-standing one, it’s interesting that no one from the React Native community has stepped up yet to thoroughly investigate it. But when that person comes, all the glory to them - maybe it could be even you? You’d not only be helping yourself, but the whole community.

Hello all, I’m having the same issue. My .babelrc is copied right from the docs.

{
  "presets": ["react-native"],
  "plugins": [
    ["module-resolver", {
      "root": ["./src"],
      "extensions": [".js", ".ios.js", ".android.js"]
    }]
  ]
}

When I try to import, say, a component like so: import Button from 'components/Button'

…it throws out an error: Module does not exist in the module map, when I try to run for iOS.

I’ve searched for some possible solutions from other issues like resetting the packager cache but to no avail. Any ideas how to resolve this?

i have an example for guys. please read readme guide. https://github.com/hungdev/react-native-alias-example

Hi @ALL, here’s my way to solve this. This may be a little help.

CRNA (create-react-native-app) module resolve & eslint rules check

@meyer-net the reason that it can not resolve the module is the order of plugins in babelrc. If you are using decorator plugin, you have to add it after module-resolver. This is important

react-native run-ios -- --reset-cache is not working, but starting the packager separately yarn start -- --reset-cache is. Would be good to pass --reset-cache from react-native-cli to the packager

i have solved this problem in my project.The reason for this problem is the wrong cwd when translate the relative dir. so there are two ways to solve it. 1、u can use npm run start – --reset-cache,but u must keep the terminal to continue the task. in other word, reset-cache do not work if u open a new terminal. this way is not recommended because it’s not persistent. 2、add a new config “cwd”:“babelrc” in .babelrc config like below(recommended):

{ “plugins”: [ [ “module-resolver”, { “root”: [“./src”], “extensions”: [“.js”,“.ios.js”,“.android.js”], “alias”: { “@”: “./src”, “src”: “./src” }, “cwd”: “babelrc” } ], [“@babel/plugin-proposal-decorators”, { “legacy”: true }], [“import”, { “libraryName”: “antd-mobile” }] ], “presets”: [ “module:metro-react-native-babel-preset” ] } my version is the latest,maybe u should upgrade first.

Hey guys, This is my solution!

.babelrc

{
  "sourceMaps": true,
  "presets": [
    "./.babelrc.js"
  ],
  "env": {
    "development": {
      "plugins": [
        "transform-react-jsx-source"
      ]
    },
    "production": {
      "ignore": ["__tests__", "__mocks__"]
    }
  }
}

.babelrc.js

const path = require('path')
const r = m => require.resolve(m)

function preset() {
  const root = path.join(__dirname, './')
  const sourcePaths = [root]
  return {
    presets: [
      r('babel-preset-react-native-stage-0'),
    ],
    plugins: [
      r('babel-plugin-transform-object-rest-spread'),
      [
        r('babel-plugin-module-resolver'),
        {
          root: sourcePaths,
          alias: {
            src: `${root}/src`,
            __mocks__: `${root}/__mocks__`,
          },
          extensions: ['.js', '.ios.js', '.android.js'],
        },
      ],
    ],
  }
}

module.exports = preset

I have it working just fine on React Native 0.56.1.

package.json

"devDependencies": {
  "babel-plugin-module-resolver": "3.2.0"
}

.babelrc

{
  "plugins": [
    [ "module-resolver", { "root": ["./src"] } ]
  ]
}

index.android.js

import Constants from "Constants";

PLEASE IGNORE THIS COMMENT from ME (@alinz)

Note from the maintainers of this project: this comment was not bringing us closer to solving the actual problem at hand in any way. Please refrain from adding similar comments - they will be removed in the future.

So I see this issue keeps coming back and hunt everyone. I have high respect for the author of this module and here's the final solution for this,
  • instead of this module, install babel-plugin-module-alias@1.6.0
  • make sure the this plugins comes after decorator if you are using it
{
  "presets": ["react-native"],
  "plugins": ["transform-decorators-legacy", ["module-alias", { "src": "./src", "expose": "@app" }]]
}

change @app to anything that you want to be used and load.

@DanielBoa can you show your dev dependencies package.json? I cant run babel-plugin-module-resolver on react native 0.57

@rendomnet I already listed the relevant versions used, the rest of the devDependencies shouldn’t make any difference.

Just to double check, I ran npm ls @babel/core babel-plugin-module-resolver react-native metro-react-native-babel-preset to get:

├── babel-plugin-module-resolver@3.1.1
├── metro-react-native-babel-preset@0.50.0
└─┬ react-native@0.57.7
  ├─┬ fbjs-scripts@1.0.1
  │ └── @babel/core@7.1.6
  ├─┬ metro@0.48.3
  │ ├── @babel/core@7.1.6  deduped
  │ └── metro-react-native-babel-preset@0.48.3
  └─┬ metro-babel-register@0.48.3
    └── @babel/core@7.1.6  deduped

And react-native -v gives me:

react-native-cli: 2.0.1
react-native: 0.57.7

I got it working again. I’m on macOS (10.14), not using Expo, and my relevant module versions are:

  • react-native-cli@2.0.1
  • react-native@0.57.7
  • babel-plugin-module-resolver@3.1.1
  • @babel/code@7.1.6

My .babelrc:

{
  "presets": [
    "module:metro-react-native-babel-preset",
    "module:react-native-dotenv"
  ],
  "plugins": [
    [
      "module-resolver",
      {
        "cwd": "babelrc",
        "root": ["./src"],
        "extensions": [
          ".js",
          ".ios.js",
          ".android.js"
        ]
      }
    ]
  ]
}

I ran the following line first to be safe although not sure it’s necessary: watchman watch-del-all && rm -rf /tmp/metro-bundler-cache-* && rm -rf /tmp/haste-map-react-native-packager-*

Then I start the project using react-native run-ios which results in an error without modules being resolved correctly. I cancel and close the metro bundler instance which opens in its own terminal and then run npm run start -- --reset-cache from the project root. Then everything resolves correctly and subsequent react-native run-ios calls work as expected.

My guess is that it’s really just the --reset-cache for the metro bundler that is required.

I have tried several solutions here but it seems not work… I have a package that I want to use the module resolver for and I have configure babel/eslint/glow but it doesnt seems to work when i am importing form the package… Any help would be great at this point

To anyone having the same problem, please check whether transform-decorators-legacy is before or after module-resolver as @alinz said. Placing it after module-resolver solves the problem.

@skiral the problem with that is you need to run yarn install before every other command and also your code is copied to node_modules every time. You may do that to all folders and add file path packages. Yet you still need to yarn install every time and copy.

We are facing the same issue here, did anyone find a solution? Shall we use another module?

@hendrul thanks for letting me know, I didn’t check my facts.