Notes

Custom Path mapping (i.e. absolute imports) in React and React Native

Edit on GitHub

ReactJS
2 minutes

The benefit of doing so

  • neater imports and organization
  • when i move components around by copy pasting code, the paths in the import statements don’t change. I know VS Code can auto-update import paths, and it is wonderful, but when it does the path updates you have to go in and save all files where the path was updated. Not having to update any paths to begin with is cool.

You have to update both babel.config.js and tsconfig.json if you’re using TypeScript.

Babel setup

1npm i -D babel-plugin-module-resolver
 1// babel.config.js
 2module.exports = {
 3  plugins: [
 4    [
 5      'module-resolver',
 6      {
 7        root: ['./src'],
 8        extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
 9        alias: {
10          src: './src',
11          tests: ['./tests/'],
12          components: './src/components',
13          // add more here
14        },
15      },
16    ],
17  ],
18}

Typescript setup

 1/* tsconfig.json */
 2{
 3  "compilerOptions": {
 4    "target": "esnext",
 5    "baseUrl": "./" /* Base directory to resolve non-absolute module names. */,
 6    "paths": {
 7      "*": ["src/*"],
 8      "components/*": ["src/components/*"]
 9      /* Add more here */
10    }
11  }
12}

Now you can import like this..

1import { List, Wrapper } from 'components/common' // ../../components/common
2import Lists from 'components/Lists'
3import Tags from 'components/Tags'
4import { Color, Dimension } from 'Theme' // ../../Theme.ts