Dan Stroot Headshot

Easier Imports

1 min read

Published

Let’s assume you have a folder structure like this in your project:

  
  
       
  
  my-app /
── pages /
│   ├── about.jsx
│   ├── analytics.jsx
│   ├── index.jsx
── hooks /
│   ├── useHasMounted.js
│   ├── useIntersectionObserver.js
│   ├── useMediaQuery.js
│   ├── usePageView.js
│   └── useViewCount.js
├── lib /
│   ├── constants.js
│   ├── sortPosts.js
│   └── utils.js

This is how your imports will typically look:

  
  
       
  
  import { SortByDate } from '../lib/sortPosts'

And it’s gonna be even worse if you are importing in a file that is nested deeply.

  
  
       
  
  import { SortByDate } from '../../../lib/sortPosts'

To solve this, you can add a jsconfig.json (or tsconfig.json if you have a TypeScript project) and then add the following to it.

  
  
       
  
  {
    "baseUrl": ".",
    "paths": {
        "@/*": ["./*"]
    }
}

This configuration will now essentially allow you to import folders like @/components, @/utils or @/hooks etc from anywhere in the codebase.

Now your imports will look like this:

  
  
       
  
  import { SortByDate } from '@/lib/sortPosts'