DEV Community

Cover image for Simplifying Imports in React with Base URL Configuration
dan
dan

Posted on • Updated on

Simplifying Imports in React with Base URL Configuration

Managing imports in a React project can get tricky, especially as your application scales and directories get deeper. Struggling with this myself, I asked chatGPT for some advise and discovered base URLs.

Using a base URL allows you to use absolute paths instead of relative ones, making your code cleaner and easier to maintain.

Why Use a Base URL?

Using complex relative paths like ../../../../components/MyComponent is error-prone and hard to maintain. With a base URL, you can import components using straightforward paths:

import MyComponent from 'components/MyComponent';

Enter fullscreen mode Exit fullscreen mode

How to Set Up a Base URL

You can configure a base URL in your React project by editing the jsconfig.json. (Sidenote: when using 'create-react-app' the file is not automatically created so you will need to create one at the base of your project.)

Here's a simple config for jsconfig.json.

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src/**/*"]
}
Enter fullscreen mode Exit fullscreen mode

This configuration tells your compiler that any imports should be resolved starting from the src directory, simplifying your import statements across the project.

Hope this helps, have a great day!

Top comments (1)

Collapse
 
dcs_ink profile image
dan

updated the jsconfig.json to be recursive.

Old

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}
Enter fullscreen mode Exit fullscreen mode

New

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src/**/*"]
}
Enter fullscreen mode Exit fullscreen mode