60

In order to avoid '../../../../' style relative imports in a TypeScript based React Native app, I would like to configure the app so that I can use absolute imports instead.

It is important that the configuration also supports Jest unit tests.

I created the app using npx react-native init MyTestApp --template typescript

React Native version: 0.60.5

What is the exact configuration I would need to achieve this?

1
  • I've added in the root of my project. the usual tsconfig.json` however if your using Create React App you may want to add an additional file for the paths callled tsconfig.base.json and extend it in you're initial main tsconfig it will loolk like this ``` json { "compilerOptions": { "baseUrl": ".", } } ```
    – undefined
    Commented May 28, 2022 at 1:04

8 Answers 8

83

Requirement

// Meh
import config from '../../../../../../../config';

// Awesome!
import config from '@cuteapp/config';

How To

  1. Add this babel plugin package
yarn add --dev babel-plugin-module-resolver
  1. My babel.config.js
module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      require.resolve('babel-plugin-module-resolver'),
      {
        cwd: 'babelrc',
        extensions: ['.ts', '.tsx', '.js', '.ios.js', '.android.js'],
        alias: {
          '@cuteapp': './app'
        }
      }
    ],
    'jest-hoist'
  ]
};
  1. My tsconfig.json
{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react",
    "lib": ["es2015", "es2015.promise", "es2016.array.include", "dom"],
    "strict": true,
    "moduleResolution": "node",
    "baseUrl": "./",
    "paths": {
      "@cuteapp/*": ["app/*/index", "app/*"]
    },
    "noEmit": true,
    "resolveJsonModule": true,
    "target": "esnext",
    "types": ["jest"]
  },
  "exclude": ["node_modules", "babel.config.js", "metro.config.js"]
}
  1. Restart the IDE.
  2. That's it.
4
  • 2
    One tiny (yet potentially confusing) thing - it's babel-config-js (not json)
    – Barazu
    Commented Aug 9, 2020 at 22:06
  • 2
    also the tsconfig.json jsx key should be react-native per the question.
    – rantao
    Commented Dec 5, 2020 at 22:19
  • 10
    Make sure to run yarn start —reset-cache after setting this :-)
    – incleaf
    Commented Jul 14, 2021 at 13:22
  • working with this approach. thnx @i-putu-yoga-permana I'm using RN 0.71 on Windows 11
    – MishkuMoss
    Commented Oct 21, 2023 at 6:59
40

Summary:

The npm package babel-plugin-module-resolver is needed, as well as some configuration in tsconfig.json and babel.config.js


Step by step:

  1. Install babel-plugin-module-resolver using npm or yarn.

    npm i babel-plugin-module-resolver --save-dev
    
    # Or (If you're using yarn):
    
    yarn add --dev babel-plugin-module-resolver
    
  2. tsconfig.json: Add "baseUrl": "." to compilerOptions

  3. babel.config.js: Add a key named plugins with the following value:

[
    [
      'module-resolver',
      {
        extensions: [
          '.js',
          '.jsx',
          '.ts',
          '.tsx',
          '.android.js',
          '.android.tsx',
          '.ios.js',
          '.ios.tsx'
        ],
        root: ['.']
      }
    ]
  ]

Complete configuration:

tsconfig.json:

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react",
    "lib": ["es6"],
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "target": "esnext",
    "baseUrl": "."
  },
  "exclude": ["node_modules", "babel.config.js", "metro.config.js", "jest.config.js"]
}

babel.config.js:

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      'module-resolver',
      {
        extensions: [
          '.js',
          '.jsx',
          '.ts',
          '.tsx',
          '.android.js',
          '.android.tsx',
          '.ios.js',
          '.ios.tsx'
        ],
        root: ['.']
      }
    ]
  ]
};

This is for a clean new project created using npx react-native init MyTestApp --template typescript on React Native version 0.60.5

2
14

If you do not want to use the babel plugin

  1. create a new package.json file inside the src folder with the following. (change myapp to whatever you want to, it can even be src.)
{
  "name": "myapp"
}
  1. update your tsconfig.json file
{
  "compilerOptions": {
     ...
     "baseUrl": "./",
     "paths": {
       "myapp/*": ["src/*"]
     }
     ...
  }
}
  1. In your.tsx file
import { MyThing } from 'myapp/MyThing';
7
  • 1
    This is the best solution in my opinion. The only downside is you have a package.json at each level you need it.
    – jrs
    Commented Jul 10, 2022 at 9:27
  • It does not immediately appear that you even need the compilerOptions, although I haven't yet compiled my app for a Production release. I'm not sure yet if it is "getting compiled" in my current Debug release.
    – Steven
    Commented Jul 25, 2022 at 17:33
  • Best solution without installing an extra dependency on node modules hole. Commented Aug 26, 2022 at 10:54
  • How to put more than one name in the package.json please?
    – Tomus
    Commented Sep 18, 2022 at 15:15
  • Can you elaborate a little more on this @Tomus? If your looking to have multiple paths, then you need a separate package.json file in each folder with a single name property. Commented Sep 19, 2022 at 17:42
9

2023 Update

1.Create a package.json in your src folder.And add {"name":"src"} in it.

2.Update your tsconfig.json file like this,

{
  "compilerOptions": {
     ...
     "baseUrl": "./",
     "paths": {
       "src/*": ["src/*"]
     }
     ...
  }
}

3.Restart your ide.

Now you can import like this,

import MyComponent from 'src/components/MyComponent';
1
  • That's working also in 2023 with "react-native": "^0.71.7"
    – Michael
    Commented Apr 20, 2023 at 16:40
5

For anyone who uses TypeScript and just wants to use import with absolute paths without aliases.

Assuming all of your code folders are inside of src.

Insert "baseUrl": "src" in compilerOptions object inside tsconfig.json.

Now you can use absolute paths in imports.

1
  • 22
    This will only get the type checking working, will not help in the compile
    – mufasa
    Commented Nov 25, 2020 at 2:02
4

All you have to do if you have a "src" file on your project root is to add a package.json file in it and write { "name": "src" } in it. Then every import named "src/..." resolves beautifully.

I found this solution in this video.

3

All of the other answers didn't work for me with a freshly created React Native + Typescript project.

What worked for me was setting both baseUrl and paths in tsconfig.json:

{
    "baseUrl": ".",
    "paths": {
      "NAME_IN_PACKAGE_JSON/*": ["./*"]
    }
}

Replace NAME_IN_PACKAGE_JSON with your package.json's name field. E.g. if the name field is myapp you can do:

import HomeScreen from "myapp/screens/HomeScreen";

1
  • When I try to set "paths", I get this at build time: The following changes are being made to your tsconfig.json file: - compilerOptions.paths must not be set (aliased imports are not supported), but apparently just the "baseUrl" setting is enough now. At least for me, it works fine.
    – natiiix
    Commented Nov 26, 2020 at 12:34
-3

You can solve it using 5 simple steps withou eject:

Step 1: Adding react-app-rewired into your devDependencies.

yarn add -D react-app-rewired or npm intall react-app-rewired --save-dev

Step 2: After installation, you'll be able to change package.json default ReactsJS scripts to:

"scripts": {  
  "start": "react-app-rewired start",  
  "build": "react-app-rewired build",  
  "test": "react-app-rewired test",  
  "eject": "react-app-rewired eject" 
}

Step 3: Creates a new file called tsconfig.paths.json on root path, with content like:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "services/*": ["./src/shared/services/*"],
      "interfaces/*": ["./src/shared/interfaces/*"]
    }
  }
}

Tip 1: you can choose which path you want to use, like: @services, @interface, @src, ~, @, etc just by changing the keys inside "paths": {}

The same is applied to it's value: ["src/shared/services/"], ["src/shared/interfaces/"], ["src/*"], use the relative path here.

Step 4: Into tsconfig.json, before "compilerOptions" you need to extends the tsconfig.paths.json you just created.

Like this:

{
  "extends": "./tsconfig.paths.json",
  ...//rest of file infos compilerOptions, include... whatever
}

Step 5: Creates a new file config-overrides.js, adding your alias and relative paths on it:

const path = require('path');

module.exports = function override(config) {
  config.resolve = {
    ...config.resolve,
    alias: {
      ...config.alias,
      'services': path.resolve(__dirname, 'src/shared/services'),
      'interfaces': path.resolve(__dirname, 'src/shared/interfaces')
    },
  };

  return config;
};

Tip 2: If you're using eslint, remember to have an .eslintignore file and add config-overrides.js within it.

Restart your IDE or text editor, in my case VSCode.

It's DONE!. Now just run yarn start or npm run start

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.