Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid very long paths and use absolute paths within a Create React App project?

Is there a babel plugin to avoid long import path in CRA? I've searching a lot on the web but I can't find the best way to achieve this.

Actual:

import MyComponent from '../../../../components/MyComponent'

Expected

import MyComponent from 'components/MyComponent'
like image 293
tolotra Avatar asked Dec 02 '19 21:12

tolotra


People also ask

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.

How do you use relative imports in React?

Select the src folder in the project window and right-click on it. Select the option Mark Directory as and then select the Resources Root option. Now go to Settings -> Editor -> Code Style -> JavaScript and select the Imports tab. Then check the Use paths relative to the project, resource or sources roots.

How to enable absolute path imports in create-react-app application without ejecting?

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)

What's new in create react app 3?

With the release of Create React App 3, we now have the ability to use absolute import paths, without ejecting. Hallelujah. If you’re reading this you probably don’t need me to tell you why this is a good thing.

What is a 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: That seems pretty clean! True, but what if you have a complex folder structure and want to go up in it? you can end up having something like:

How do I use absolute path in jsconfig?

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) If you currently have your application running, you’ll have to restart it to be able to start importing using absolute paths.


1 Answers

In your main root, create file jsconfig.json:

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

Where src is the folder where you store your project files, sometimes it may be /app or /src.

Then you will be able to import your components with an absolute path:

import MyComponent from 'components/MyComponent';
like image 56
kind user Avatar answered Oct 15 '22 13:10

kind user