onoya.dev

Enable Absolute Path Imports in Create React App

In this article, I’ll be showing you how to enable absolute path imports in a create-react-app application without ejecting.

To enable absolute path imports, you just have to configure the baseUrl of your project’s jsconfig.json file. (tsconfig.json if you are using typescript)

{ "compilerOptions": { "baseUrl": "src" }, "include": ["src"] }

If you currently have your application running, you’ll have to restart it to be able to start importing using absolute paths.

// Relative path import import ComponentA from '../../components/ComponentA'; // Absolute path import import ComponentA from 'components/ComponentA';

ESLint

If you are using ESLint, you might see some warnings that says Unable to resolve path to module .... You have to add the following ESLint configurations to your .eslintrc file, or inside your package.json file. In this example, I will be using the .eslintrc file.

{ "settings": { "import/resolver": { "node": { "paths": ["src"] } } } }