Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've been using create-react-app package for creating a react website. I was using relative paths throughout my app for importing components, resources, redux etc. eg, import action from '../../../redux/action

I have tried using module-alis npm package but with no success. Is there any plugin that I can use to import based on the folder name or alias i.e. an absolute path?

Eg., import action from '@redux/action' or import action from '@resource/css/style.css'

like image 852
Prem Avatar asked Jul 20 '17 11:07

Prem


People also ask

How can Webpack help you avoid relative path imports?

React emphasises on modular code and component architecture. Dividing the app into presentational and container components makes the code more readable and also reusable.

What is relative path in React?

By default, relative paths are the supported way of importing modules to React and other frameworks. You will usually see or write something like: import MyModule from './MyModule'; That seems pretty clean!

How do you use absolute path in React?

When initializing React Project with create-react-app, we can configure our React application to support importing modules with absolute paths. Note: We can create the jsconfig. json file if it doesn't exist. Now we have the working absolute imports setting with src folder as custom base directory.


2 Answers

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.

like image 105
Dan Abramov Avatar answered Sep 26 '22 03:09

Dan Abramov


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"] } 

Once you have 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' 
like image 42
Ben Smith Avatar answered Sep 26 '22 03:09

Ben Smith