jrs
jrs

Reputation: 175

Error: Unable to resolve module ... could not be found within the project or in these directories: node_modules

Error: Unable to resolve module navigation/stack-routes from /Users/jacksaunders/gymzoo/src/navigation/tabs/MainTabs.tsx: navigation/stack-routes could not be found within the project or in these directories: node_modules

Hello there! I have just tried to set up absolute imports (using navigation/stack instead of ../../../navigation/stack)

I am not sure what is happening because it looks to be okay in my IDE but my metro is flagging the following error.

error

Here is my tsconfig for context:

tsconfig

I have tried deleting my node modules, npm i and pod install but theres no luck.

Please throw your suggestions at me! Or advise me on how to solve this.

All the best, Jack :)

Upvotes: 0

Views: 4966

Answers (1)

Daruda
Daruda

Reputation: 186

You need to update your babel.config.js to understand the root imports you're using here, because your .tsconfig only takes care about the code before it's transcompiled.

You can use the babel-plugin-root-import to achieve this. npm package: https://www.npmjs.com/package/babel-plugin-root-import

Example babel.config.js could look like this:

module.exports = {
    presets: ['module:metro-react-native-babel-preset'],
    plugins: [
        [
            'babel-plugin-root-import',
            {
                paths: [
                    {
                        rootPathSuffix: './src',
                        rootPathPrefix: 'src',
                    },
                    {
                        rootPathSuffix: './src/navigation',
                        rootPathPrefix: 'navigation',
                    },
                ]
            },
        ],
    ],
};

It's not an only option though, you can also use babel-plugin-module-resolver, which is more popular (https://www.npmjs.com/package/babel-plugin-module-resolver).

Upvotes: 3

Related Questions