最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using relative paths with react-native - Stack Overflow

programmeradmin1浏览0评论

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 :

Module not found: Can't resolve '/../Components/adapter' in 'E:\reactjs\learn\Project\src\screens'

Share Improve this question asked Jul 15, 2020 at 21:04 anehmeanehme 5661 gold badge7 silver badges19 bronze badges 1
  • stackoverflow.com/questions/57032522/… – saisriram manchella Commented May 7, 2021 at 9:04
Add a comment  | 

3 Answers 3

Reset to default 16

You 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.

发布评论

评论列表(0)

  1. 暂无评论