[Next.js] Absolute path

2024-05-15 hit count image

Let's see how to use absolute path to import components in Next.js with TypeScript.

Outline

In this blog post, I will introduce how to use absolute path to import components in the TypeScript base Next.js project.

You can see the full source code of this blog post on the following link.

Blog list

This blog post is a series. If you want to check other blog posts of the series, see the links below.

Create Next.js project based on TypeScript

To see how to use absolute path to import components in the TypeScript base Next.js project, execute the following command to create a Next.js project with TypeScript.

npx create-next-app --typescript my-app

Modify tsconfig.json

To use absolute path to import components in the TypeScript base Next.js project, you need to modify tsconfig.json. Open the tsconfig.json file and add the baseUrl like the below.

{
  "compilerOptions": {
    ...
    "baseUrl": "./"
  },
  ...
}

Done! now you’re ready to use absolute path to import components.

Import components with absolute path

To check the configuration of absolute path, open the pages/index.tsx file and modify it like the below.

...
import styles from 'styles/Home.module.css'

const Home: NextPage = () => {
  return (
    ...
  )
}

export default Home

In this way, you can add components based on the root folder without ../ anymore.

Execute

To check absolute path working well, execute the following command.

npm run dev

If you configured well, the browser is opened with http://localhost:3000 automatically, and you can see the screen like the below.

create-next-app first app

Completed

Done! we’ve seen how to configure absolute path in the TypeScript base Next.js project and how to use it. Now, you can import the components easier and understand them from where easier.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts