How to avoid using relative path imports (/../../../redux/action/action1) in create-react-app How to avoid using relative path imports (/../../../redux/action/action1) in create-react-app reactjs reactjs

How to avoid using relative path imports (/../../../redux/action/action1) in create-react-app


Create a file called .env in the project root and write there:

NODE_PATH=src

Then restart the development server. You should be able to import anything inside src without relative paths.

Note I would not recommend calling your folder src/redux because now it is confusing whether redux import refers to your app or the library. Instead you can call your folder src/app and import things from app/....

We intentionally don't support custom syntax like @redux because it's not compatible with Node resolution algorithm.


The approach in the accepted answer has now been superseded. Create React App now has a different way to set absolute paths as documented here.

To summarise, you can configure your application to support importing modules using absolute paths by doing the following:

Create/Edit your jsconfig.json/tsconfig.json in the root of your project with the following:

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

Alternatively:

If you're using TypeScript, you can configure the baseUrl settinginside the compilerOptions of your project's tsconfig.json file.

Once you've done this you can then import by specifying subdirectories of "src" (in the following example, components is a subdirectory of src) e.g.

import Button from 'components/Button'


After you try Ben Smith's solution above if you find eslint complains about importing absolute path add the following line to your eslint config:

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

replace 'src' with your folder if you use your own boilerplate with your folder's name.