Dan Stroot

Easier Imports

Import from folders like /components, /utils or /hooks from @/anywhere in your codebase.

Date:


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:

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

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

example.ts
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.

example.ts
{
    "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:

example.ts
import { SortByDate } from '@/lib/sortPosts'

Sharing is Caring

Edit this page