Using Path Aliases (Alias) in Next.js

This guide explains how to use path aliases (alias) when importing modules in a Next.js project. Utilizing this feature can enhance code readability and provide flexibility when dealing with project structural changes.

What Is an Alias?

An alias for paths (alias) is a shorthand for specific directories. It allows you to easily reference files or directories by specifying an absolute path when repetitive or confusing relative file paths are a concern.


Configuring Alias in Next.js

In Next.js, you can specify aliases using the Webpack resolve.alias configuration.

  • Name
    Step 1
    Type
    Description

    First, create a next.config.js file in the root directory of your project.

  • Name
    Step 2
    Type
    Description

    Add Webpack configuration.

next.config.js

const path = require('path')

module.exports = {
    webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
        config.resolve.alias['@components'] = path.join(__dirname, 'components')
        config.resolve.alias['@/lib'] = path.join(__dirname, 'src/lib')
        // 필요한 만큼 alias 추가...

        return config
    },
}

Import Using Alias

We have created an alias called @components and associated it with the components directory in the source code. This allows you to import components from anywhere in your source code using the format @components/ComponentName.

  • Name
    Step 1
    Type
    Description

    The path.join(__dirname, 'components') part in the code combines the absolute path of the current file (next.config.js) with the components directory.

  • Name
    Step 2
    Type
    Description

    You can also import using ../../../, but using an alias can improve readability.

components

import MyComponent from '@components/MyComponent'

import MyComponent2 from "../../../components/MyComponent2"

Important Note

Modifying the Webpack configuration that Next.js internally uses can be delicate. It may not be compatible with certain versions of Next.js or could lead to unexpected side effects. Caution is advised, and it should be verified before usage.


Conclusion

Configuring aliases in Next.js allows you to use short and clear aliases when importing files, instead of relying on relative paths. This enhances code readability and provides flexibility when structurally modifying your project. We'll meet again with more Next.js tips in the next session!