How to Use 'Absolute Import' in Next Js Application
π€ Why do we need this?
Well! You must have experience if you have built some components and have used them in any other component and later you want to shift from one place to another (they can be nesting), the compiler will ask you to change the location of that component in import by adding ../
or removing extra dots.
So to avoid that problem, we can use absolute import, which helps in auto-import as well.
π File Structure
πroot
πlayout
πPageGutter.tsx
πpages
πcheckout.tsx
π« Problem (Using Relative Import)
This is the actual component that is being used on every page
// layout/PageGutter
import { Box, BoxProps } from '@chakra-ui/react'
import React, { FC } from 'react'
interface Props extends BoxProps {}
const PageGutter:FC<Props> = ({ ...restProps }) => {
return (
<Box py="16" {...restProps} />
)
}
export default PageGutter
This is the checkout page that uses relative import ../layout/PageGutter
// pages/checkout
import React from 'react'
import PageGutter from '../layouts/PageGutter'; // pain point π₯
const checkout = () => {
return (
<PageGutter />
)
}
export default checkout
π Solution (Using Absolute Import)
The
baseUrl
configuration option allows you to import directly from the root of the project.// tsconfig.json or jsconfig.json { "compilerOptions": { "baseUrl": "." } }
Importing same
PageGutter.tsx
component incheckout.tsx
page using absolute import.// pages/checkout import React from 'react' import PageGutter from 'layouts/PageGutter'; // Omit dots π const checkout = () => { return ( <PageGutter /> ) } export default checkout
Using an Alias (Optional)
Using paths
allows you to configure module aliases. For example @/components/*
to components/*
.
- Configuration using an alias.
// tsconfig.json or jsconfig.json { "compilerOptions": { "baseUrl": ".", "paths": { "@/layouts/*": ["layouts/*"] } } }
Importing same
PageGutter.tsx
component incheckout.tsx
page using absolute import but with alias.// pages/checkout import React from 'react' import PageGutter from '@layouts/PageGutter'; const checkout = () => { return ( <PageGutter /> ) } export default checkout
π― Conclusion
- Open
tsconfig.json
orjsconfig.json
file in the root of your project. - Configure
tsconfig.json
orjsconfig.json
file by addingbaseUrl
andpaths
. - Start using absolute imports.
ππ½ Hope you enjoyed it, comment section is open, you are welcome, let's communicate there π€