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'
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.
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.
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)
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.
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:
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.
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With