How to use absolute module import path in next.js with Typescript instead of using complex relative paths?
Using absolute path or custom alias for directories to import modules or components has two benefits mainly.
- It will allow you to work faster since you won’t need to calculate how many levels of directory you have to go up before accessing the file.
- Keep codes clean
For example, comparing with the following two import:
import { myFunction } from "../../../../utils/my-utils"
import { myFunction } from "@utils/my-utils"
💡This tutorial will show you how to setup custom alias for directories in next.js with Typescript
With Next.js version 9, you have built-in Typescript support.
Install babel-plugin-module-resolver dependency
yarn add babel-plugin-module-resolver
This plugin allows you to add new “root” directories that contain your modules. It also allows you to setup a custom alias for directories, specific files, or even other npm modules.
Config path in tsconfig.json
In tsconfig.json, add directory to path option, e.g.
"@components/*": ["components/*"]
This means you can import componentA in components folder with this way in any level.
import componentA from "@components/componentA"
One tsconfig.json example with path option.
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"baseUrl": ".",
"paths": {
"@modules/*": ["modules/*"],
"@components/*": ["components/*"],
"@layout/*": ["layout/*"],
"@actions/*": ["actions/*"],
"@actionTypes/*": ["actionTypes/*"],
"@reducers/*": ["./reducers/*"],
"@sagas/*": ["./sagas/*"],
"@static/*": ["static/*"],
"@store/*": ["store/*"],
"@dummy/*": ["__dummy__/*"]
}
},
"exclude": [
"node_modules"
],
"include": [
]
}
Config module-resolver in babel
In babelrc file, set plugin for module-resolver and set module-resolver alias option as below:
{
"presets": [
[
"next/babel",
{
"preset-env": {
"useBuiltIns": "usage"
}
}
],
],
"plugins": [
[
"module-resolver",
{
"alias": {
"@modules": "./modules",
"@components": "./components",
"@layout": "./layout",
"@actions": "./actions",
"@actionTypes": "./actionTypes",
"@static": "./static",
"@store": "./store",
"@sagas": "./sagas",
"@reducers": "./reducers",
"@dummy": "./dummy"
}
}
]
],
"env": {
"test": {
"presets": [["@babel/preset-env", { "modules": false } ], "next/babel"]
}
}
}
Well, everything is done now. You can use absolute path or custom alias for directories to import modules or components in any directory level.