Using absolute imports with VSCode and create-react-app

Felipe Lima
Felipe Lima
Sep 23, 2018 - React
Using absolute imports with VSCode and create-react-app

I’m currently refactoring a big React app, and it’s being a huge pain to move and rename files and folders.

Today all imports are relative, which leads to imports being referenced like this:

# Component B
import ComponentA from '../../../folder/ComponentA';

# Component C
import ComponentA from '../folder/ComponentA';

In that case you can’t simply move files, do a full text search and replace those paths. You have to open all the files and change them, one by one.

If the imports were absolute, they would be like this:

# Component B
import ComponentA from 'components/folder/ComponentA';

# Component C
import ComponentA from 'components/folder/ComponentA';

In that case, you just need to do a full text search for 'components/folder/componentA' and replace it for the new path.

Configuring create-react-app

Just create a .env file and add the NODE_PATH variable pointing to src/. This tells node scripts to look for modules at 'src/' folder if they are not found elsewhere.

# .env

NODE_PATH=src/

Configuring VSCode

If you have a jsconfig.json in your project, at "compilerOptions", add the "baseUrl" configuration pointing to “./src”. Otherwise, create a jsconfig.json like this:

# jsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2016",
    "jsx": "preserve",
    "checkJs": true,
    "baseUrl": "./src"
  },
  "exclude": ["node_modules", "**/node_modules/*"]
}

Configuring VSCode Auto Import

At the Project Workspace Settings file (.vscode/settings.json), you have to specify that you want to use "non-relative" imports on auto import. Also it's nice to always have the imports updated on file moves:

#.vscode/settings.json

{
  "javascript.updateImportsOnFileMove.enabled": "always",
  "javascript.preferences.importModuleSpecifier": "non-relative"
}

Relative imports will also work, but when you try to auto import another file, it will import with it's non-relative import: