A few months ago, I started working on a Rails project for a client in the fintech industry and transitioning their legacy AngularJS codebase to React. The frontend consists of multiple different apps that share some common functionality so the structure can get pretty deep.

Relative imports are good for smaller apps, but it gets annoying having to track how many directory levels you have to exit.

import { fetchResource } from '../../common/actions/api';

It'd be much better to just reference top level folders directly.

import { fetchResource } from 'common/actions/api';

Base setup

The first thing we need to do is create a jsconfig.json file at the root of the project with the following config:

{
  "compilerOptions": {
    "baseUrl": "./app/javascript",
    "target": "es6",
    "module": "commonjs",
    "jsx": "preserve",
    "paths": {
      "*": ["./*"]
    }
  }
}

Since I'm using Rails with Webpacker my JavaScript source is nested under app/javascript. In case you're using create-react-app you can change baseUrl to ./src.

ESLint Integration

First we need to add eslint-plugin-import to our dev dependencies and add the following configuration to .eslintrc.json:

"settings": {
  "import/resolver": {
    "node": {
      "paths": ["./app/javascript"]
    }
  }
}

On some setups I've experienced the loss of ability to command/ctrl click imports and go straight to that file. In order to fix that I had to install the VSCode extension path-intellisense. The extension uses the baseSrc setting from jsonconfig.json and combined with the paths mapping we set up, that's all the configuration we need to make it work.