babel-plugin-module-resolver icon indicating copy to clipboard operation
babel-plugin-module-resolver copied to clipboard

it's can't use in react-native.

Open meyer-net opened this issue 6 years ago • 55 comments

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

meyer-net avatar Oct 23 '17 05:10 meyer-net

try to change root value to './'?

smalltwo avatar Oct 23 '17 10:10 smalltwo

@smalltwo the same,it's still can't working, do u have the correct configuration file?

meyer-net avatar Oct 23 '17 10:10 meyer-net

try to uninstall react-native and install react-native

smalltwo avatar Oct 23 '17 12:10 smalltwo

same config, in my project, it can run, but in my partner project, it can not run, and then he reinstall react-native, it works

smalltwo avatar Oct 23 '17 12:10 smalltwo

it's yarn remove react-native && yarn add react-native?

meyer-net avatar Oct 23 '17 12:10 meyer-net

i've tried it already, it's still can't working.

meyer-net avatar Oct 23 '17 13:10 meyer-net

@meyer-net, it seems to work with the create react native app scaffolding. I think there maybe an issue with your .babelrc file. Try reading the following post, it may clear up your issue.

https://medium.com/@sterlingcobb/adding-alias-to-create-react-native-app-crna-in-2-minutes-45574f4a7729

bsubedi26 avatar Oct 30 '17 05:10 bsubedi26

@bsubedi26 er, but it's not created by crna,just a clean sys。i want a right demo to compare my projects.

thanks.

meyer-net avatar Oct 31 '17 08:10 meyer-net

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

maxhungry avatar Nov 01 '17 22:11 maxhungry

@maxhungry yes, i did it already,and tried create a new clean env, but it can't work, the error still open: image

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

meyer-net avatar Nov 02 '17 03:11 meyer-net

have the same issue with react-native

tarasywe avatar Nov 06 '17 07:11 tarasywe

Which version are you using ?

MatthieuLemoine avatar Nov 08 '17 09:11 MatthieuLemoine

^2.7.1

tarasywe avatar Nov 08 '17 13:11 tarasywe

It was fixed by #205 which is available in ^3.0.0

MatthieuLemoine avatar Nov 08 '17 13:11 MatthieuLemoine

i use it by ^3.0.0-beta.5

meyer-net avatar Nov 09 '17 06:11 meyer-net

i'm so crazy, it's still can't map....

meyer-net avatar Nov 09 '17 07:11 meyer-net

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 avatar Nov 14 '17 19:11 Gr1ver

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

MatthieuLemoine avatar Nov 15 '17 08:11 MatthieuLemoine

@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

alinz avatar Dec 06 '17 04:12 alinz

@MatthieuLemoine I also have this problem when I use 'react-native run-android' in the cmd window. But, it works ok when I debug in the VSCode with its React Native tools extention. It's quite odd since they are the same settings in the same project. Is it because the React Native tools extention uses a special command script instead of 'react-native run-android' witch bypass the problem?

entronad avatar Dec 22 '17 03:12 entronad

@entronad yep,i've resolved it by create a new react-native project。but i don't know why the same config and the project can't work.

meyer-net avatar Dec 23 '17 14:12 meyer-net

@alinz thanks.

meyer-net avatar Dec 23 '17 14:12 meyer-net

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?

jayprado avatar Jan 24 '18 09:01 jayprado

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

lanlin avatar Mar 12 '18 07:03 lanlin

ok, thanks for your help.

meyer-net avatar Mar 29 '18 01:03 meyer-net

when I try it ok, I'll close the ticket.

meyer-net avatar Mar 29 '18 01:03 meyer-net

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

Gregoirevda avatar Apr 18 '18 08:04 Gregoirevda

I think this issue have not been solved, we have a work around, but been forced to reset the packager cache each time is not exactly the ideal.

hendrul avatar Apr 22 '18 21:04 hendrul

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 [email protected]
  • 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.

alinz avatar May 07 '18 05:05 alinz

@alinz that's a deprecated version of this lib, no way i'm gonna use it in my project. By the way I try it and it doesn't work, maybe I missuse it. No one working to fix this issue?, is it a won't fix?

hendrul avatar May 14 '18 15:05 hendrul

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.

fatfisz avatar May 14 '18 16:05 fatfisz

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

alinz avatar May 15 '18 15:05 alinz

If anyone is willing to setup a testcase using the react-native bundler, this might also help us catching these issues specific to react native

tleunen avatar Jul 31 '18 16:07 tleunen

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

skiral avatar Aug 10 '18 03:08 skiral

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.

skiral avatar Aug 10 '18 03:08 skiral

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.

Kausta avatar Aug 11 '18 11:08 Kausta

This works for me with android

{
  "presets": [
    "react-native"
  ],
  "plugins": [
    ["module-resolver", {
      "alias": {
        "Components": "./src/Components",
        "Comp": "./src/Components/Comp"
      }
    }]
  ]
}

guitar9 avatar Aug 12 '18 13:08 guitar9

At first, I config like you all

{
    "presets": ["react-native"],
    "plugins": [
        [
            "module-resolver", {
                "alias": {
                    "app":"./src/app",
                    "com":"./src/component",
                    "utils":"./src/utils"
                },
                "extensions": [
                    ".js",
                    ".ios.js",
                    ".android.js"
                ]
            }
        ]
    ]
}

It always came out with error shows 'Can not find module in /node_modules/react-native.....', so I guess the Babel's working dictionary is /node_modules/react-native . So, I changed the configuration as below:

{
    "presets": ["react-native"],
    "plugins": [
        [
            "module-resolver", {
                "alias": {
                    "app":"../../src/app",
                    "com":"../../src/component",
                    "utils":"../../src/utils"
                },
                "extensions": [
                    ".js",
                    ".ios.js",
                    ".android.js"
                ]
            }
        ]
    ]
}

and it works. But the wired things is when changed the configuration back to the beginning, it works too. I don't know why, buy you guys can have a try like this. Maybe change the root option can work, but the root option seems not work for me.

@fatfisz Sorry for that I can not solve the problem, but I hope it could give a little inspiration to fixed the problem.

luweiCN avatar Aug 28 '18 09:08 luweiCN

Still not work in my RN project, but my partner is OK, tried all solutions searched, give it up finally.

donnior avatar Sep 20 '18 07:09 donnior

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

stunstunstun avatar Sep 22 '18 04:09 stunstunstun

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

Quadriphobs1 avatar Oct 07 '18 11:10 Quadriphobs1

same here. tried different configs, none of them work. But sure, the issue is react-native specific and depends on the initial setup, so I think it should be closed.

LexSwed avatar Oct 07 '18 17:10 LexSwed

same here +1

FE-xiaoJiang avatar Oct 11 '18 02:10 FE-xiaoJiang

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.

FE-xiaoJiang avatar Oct 11 '18 15:10 FE-xiaoJiang

I found that its not resolving index files automatically for example if you change

import {some} from 'src/component' to import {some} from 'src/component/index.ts' it works

imerkle avatar Dec 01 '18 11:12 imerkle

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

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.

DanielBoa avatar Dec 01 '18 15:12 DanielBoa

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

rendomnet avatar Dec 20 '18 19:12 rendomnet

@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:

├── [email protected]
├── [email protected]
└─┬ [email protected]
  ├─┬ [email protected]
  │ └── @babel/[email protected]
  ├─┬ [email protected]
  │ ├── @babel/[email protected]  deduped
  │ └── [email protected]
  └─┬ [email protected]
    └── @babel/[email protected]  deduped

And react-native -v gives me:

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

DanielBoa avatar Dec 20 '18 19:12 DanielBoa

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

hungdev avatar Jan 05 '19 17:01 hungdev

Hi, I have been having this issue for a while now. For me I think I have finally figured out what was happening on my machine. It might not work on yours. But it sure sounds like its the same problem. It turns out to be quite simple. For the people running into this problem, I am assuming you are running yarn iOS or npm start iOS and letting react-native launch the metro bundler. If you do that, it turns out the working directory is set to node_modules/react-native and not the root of your project. So, every alias will be prepend with node_modules/react-native and you will get that nasty error. All you need to do is to run the metro bundler (usually with a npm start on your project or react-native start. Then on a separate terminal run npm iOS or yarn iOS or android. This way the working directory will be set at your project root and not react-native. It'd be nice if someone figures out how to let react-native launch the bundler and set the working directory at your project root.

billtlee avatar Mar 08 '19 08:03 billtlee

Does it work with React Native 0.59 now?

gluons avatar Mar 19 '19 07:03 gluons

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";

joshuapinter avatar Mar 19 '19 14:03 joshuapinter

Thanks @maxhungry. You helped me a lot!

IgorMing avatar May 09 '19 00:05 IgorMing

I would suggest using this with React Native: https://medium.com/beqode/fixing-import-path-hell-react-native-eslint-vs-code-3d04de9762b6

dclipca avatar Nov 27 '19 19:11 dclipca

This is OK : image

I thought it was a plugin error until I found my code error :

image

625781186 avatar Feb 18 '20 17:02 625781186