Absolute paths in react native version 0.72 typescript

1.1k Views Asked by At

Hey Guys so I'm struggling to set absolute paths in react native I used babel-plugin-module-resolver for that and also set tsconfig.json and 'babel.config.js' as slowed below and VS code isn't giving any error about path but metro server throwing error like this

BUNDLE  ./index.js

error: Error: Unable to resolve module @pages/pokemons/pokemons from D:\Work And Stydy Of IT\ReactNative\RTKTS\src\App.tsx: @pages/pokemons/pokemons could not be found within the project or in these directories:
  node_modules
> 1 | import Pokemons from '@pages/pokemons/pokemons';
    |                       ^
  2 | import React from 'react';
  3 |
  4 | function App(): JSX.Element {
    at ModuleResolver.resolveDependency (D:\Work And Stydy Of IT\ReactNative\RTKTS\node_modules\metro\src\node-haste\DependencyGraph\ModuleResolution.js:139:15)
    at DependencyGraph.resolveDependency (D:\Work And Stydy Of IT\ReactNative\RTKTS\node_modules\metro\src\node-haste\DependencyGraph.js:277:43)
    at Object.resolve (D:\Work And Stydy Of IT\ReactNative\RTKTS\node_modules\metro\src\lib\transformHelpers.js:169:21)
    at Graph._resolveDependencies (D:\Work And Stydy Of IT\ReactNative\RTKTS\node_modules\metro\src\DeltaBundler\Graph.js:473:35)
    at Graph._processModule (D:\Work And Stydy Of IT\ReactNative\RTKTS\node_modules\metro\src\DeltaBundler\Graph.js:261:38)
    at async Graph._addDependency (D:\Work And Stydy Of IT\ReactNative\RTKTS\node_modules\metro\src\DeltaBundler\Graph.js:372:20)
    at async Promise.all (index 2)
    at async Graph._processModule (D:\Work And Stydy Of IT\ReactNative\RTKTS\node_modules\metro\src\DeltaBundler\Graph.js:322:5)
    at async Graph._traverseDependenciesForSingleFile (D:\Work And Stydy Of IT\ReactNative\RTKTS\node_modules\metro\src\DeltaBundler\Graph.js:249:5)
    at async Promise.all (index 0)

// tsconfig.json

{
  "extends": "@tsconfig/react-native/tsconfig.json",
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@app": [
        "app/index"
      ],
      "@app/*": [
        "app/*"
      ],
      "@services": [
        "services/index"
      ],
      "@services/*": [
        "services/*"
      ],
      "@pages": [
        "pages/index"
      ],
      "@pages/*": [
        "pages/*"
      ],
    }
  },
  "include": [
    "src/**/*",
  ]
}

babel.config.js

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      'module-resolver',
      {
        root: ['./src'],
        alias: {
          '@app': ['app/index'],
          '@app/*': ['app/*'],
          '@services': ['services/index'],
          '@services/*': ['services/*'],
          '@pages': ['pages/index'],
          '@pages/*': ['pages/*'],
          underscore: 'lodash',
        },
      },
    ],
  ],
};

Steps that I tried till now:

  1. Delete node_modules and yarn.lock files and re install packages.
  2. yarn start --reset-cache
  3. Delete the old APK which is installed in an emulator.
  4. again install everything.

Before posting this I tried a lot of answers which is available on Google and after that, I'm posting

2

There are 2 best solutions below

2
AmerllicA On BEST ANSWER

I think the TypeScript configuration file and the babel.config.js file needn't index route name, in my case both configurations were like the following examples:

// tsconfig.json
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@api": ["./api"], // this is for importing index file
      "@api/*": ["./api/*"], // this is for importing other files underneath of the api folder 
// babel.config.js
module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    'react-native-reanimated/plugin',
    [
      'module-resolver',
      {
        root: ['./src'],
        extensions: [
          '.ios.ts',
          '.ios.tsx',
          '.android.ts',
          '.android.tsx',
          '.ts',
          '.tsx',
          '.js',
          '.jsx',
          '.json',
        ],
        alias: {
          '@api': './src/api',
        },
      },
    ],
  ],
};

These configurations are working for me.

2
Estevan Maito On

The accepted answer put me in the right direction, but it's missing a few things.

I just started a React Native project from the CLI (react-native: 0.73.1). This is what worked for me:

// tsconfig.json
{
    "extends": "@react-native/typescript-config/tsconfig.json",
    "compilerOptions": {
        "baseUrl": ".", // <- can also use anything, e.g: ./src
        "paths": {
            "@/*": ["./src/*"]
            // "@api": ["./api"] <- would work the same
        }
    }
}

We need to install the module-resolver plugin:

npm install babel-plugin-module-resolver --save-dev

And add it to the Babel config:

// babel.config.js
module.exports = {
    presets: ["module:@react-native/babel-preset"],
    plugins: [
        [
            "module-resolver",
            {
                root: ["."], // <- this is the same as the baseUrl
                extensions: [
                    ".ios.ts",
                    ".ios.tsx",
                    ".android.ts",
                    ".android.tsx",
                    ".ts",
                    ".tsx",
                ],
                alias: {
                    "@": "./src/", // <- this is absolute (different from tsconfig)
                },
            },
        ],
    ],
};

After all this, you may run npm start and still see an Error: Unable to resolve module. If that's the case, run this command to reset the cache:

npm start -- --reset-cache
# or yarn start --reset-cache

A few notes:

  • The baseUrl in the tsconfig should be the same as in root in the babel.config
  • alias in babel.config only works with absolute paths, so: if you have in tsconfig: "@/*": ["./src/*"] you need to transform it to: "@": "./src/"

As a rule of thumb: remove /* from the key, remove * from the value.