Skip to main content

别名

引言

记录一次给nextjs设置别名.

由于项目的复杂性增加, 项目中多了许多../../../的路径, 看起来难看而且还增加了维护成本,由于是第一次在next.js用配置别名. 以往在webpack以及vite的使用中知道肯定是要配置相应的配置文件的,但是不能光凭直觉去想,先去看看官方的文档吧.

官网文档是这样介绍[1],官网文档写的很简单: // tsconfig.json or jsconfig.json


{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/components/*": ["components/*"]
}
}
}

只需要配置ts的配置文件tsconfig.json就可以了,连webpack.config(next.js是基于webpack)配置都不用写,居然是如此简单,在感叹next.js 强大的同时按照去做了,但是next.js却给我这样的报错:

![[Pasted image 20220803193849.png]] 无法解析此导入

果然还得自己写配置文件, 在查阅了官网的文档以及在stackoverflow上提问( 虽然没有帮助)之后,自己就找,在翻阅官网以及搜索当中,我找到了答案,以下是自己摸索得到的解决方式:

前置条件

本项目是next.js的TypeScript版本,创建时就集成了ts,默认包含tsconfig.json,如果是js项目,理论只需要配置next的配置文件next.config即可,如果是js项目转成ts的,那么就需要手动添加tsconfig.json

1. 配置别名

  1. next.config.js配置文件添加别名的配置:
// next.config.js
const path = require('path')
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
}

module.exports = {
...nextConfig,
webpack: (config,
{ buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }) => {
config.resolve.alias = {
...config.resolve.alias,
'@': path.resolve(__dirname),
'@/components': path.resolve(__dirname, 'components'),
}
return config
},
}

2. 配置IDE解析

// tsconfig.json


{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"baseUrl": ".",
"paths": {
"@/components/*": [
"./components/*"
],
"@/images/*": [
"./public/images/*"
]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules"
]
}

本文的next.js版本是12.2.3

参考资料:

[1] https://nextjs.org/docs/advanced-features/module-path-aliases