I am trying to import Module using relative path in react-native , my project structure is like this :
-Project
--Components
--- adapter.js
--src
---screen
----Main.js
--App.js
I want to use adapter.js in my Main.js , so in the Main.js
i use : import adapter from '/../Components/adapter'
this will throw the following error :
Module not found: Can't resolve '/../Components/adapter' in 'E:\reactjs\learn\Project\src\screens'
I am trying to import Module using relative path in react-native , my project structure is like this :
-Project
--Components
--- adapter.js
--src
---screen
----Main.js
--App.js
I want to use adapter.js in my Main.js , so in the Main.js
i use : import adapter from '/../Components/adapter'
this will throw the following error :
Share Improve this question asked Jul 15, 2020 at 21:04 anehmeanehme 5661 gold badge7 silver badges19 bronze badges 1Module not found: Can't resolve '/../Components/adapter' in 'E:\reactjs\learn\Project\src\screens'
- stackoverflow.com/questions/57032522/… – saisriram manchella Commented May 7, 2021 at 9:04
3 Answers
Reset to default 16You can use https://github.com/tleunen/babel-plugin-module-resolver, it's a good module to have alias with import.
You have to specify a babel.config.js in React Native and a configuration:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['./src'],
alias: {
components: './src/components',
_main: './src/components/_main',
screens: './src/screens',
config: './src/config',
navigations: './src/navigations',
utils: './src/utils',
actions: './src/state/actions',
constants: './src/state/constants',
contexts: './src/state/contexts',
reducers: './src/state/reducers',
assets: './src/assets/',
hooks: './src/hooks',
data: './src/data',
},
},
],
],
};
And after, you can import your module like this :
import HomeFeed from 'components/Home';
Note: that VSCode will detect the import
You need to add a tsconfig.js
file
The next line
"baseUrl": "src"
Since your file Main.js
is inside src/screen
and adapter.js
is inside Components
, you need to go two levels down from Main.js
to get out of screen
, src
and then enter Components
.
You will end up with something like ../../Components/adapter
.