NextJS 与 TypesScript index.ts 文件未使用路径别名解析

Jul*_*rra 2 typescript next.js

我收到一条 TypeScript 警告,指出无法找到该模块。

我在我的 NextJS 应用程序上使用 TypeScript,这只是在我使用自定义路径并且之前没有遇到过这个问题的时候发生的。

我有这个结构示例

/models
  |-- index.ts
  |-- User.ts
/pages
   /api
     /users
       |-- index.ts
Run Code Online (Sandbox Code Playgroud)

我正在尝试Userschemamodels我设置的自定义路径导入,但它给了我一个错误

这就是我的index.ts样子models

export { default as User } from './User';
Run Code Online (Sandbox Code Playgroud)

这就是我将其导入内部的方式api/user/index.ts

import { User } from '@/models';
Run Code Online (Sandbox Code Playgroud)

我的tsconfig文件看起来像这样

{
    "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": {
            "@/components/*": [
                "./components/*"
            ],
            "@/types/*": [
                "./types/*"
            ],
            "@/utils/*": [
                "./utils/*"
            ],
            "@/middlewares/*": [
                "./middlewares/*"
            ],
            "@/models/*": [
                "./models/*"
            ],
            "@/lib/*": [
                "./lib/*"
            ]
        }
    },
    "include": [
        "next-env.d.ts",
        "**/*.ts",
        "**/*.tsx"
    ],
    "exclude": [
        "node_modules"
    ]
}
Run Code Online (Sandbox Code Playgroud)

使用索引文件以外的自定义路径进行导入是 import dbConnect from '@/utils/dbConnect'可行的,但对于索引文件,我仍然必须在导入时指定索引文件名才能使其工作。 import { User } from '@/models/index'

Jul*_*rra 6

我通过将路径别名替换为

...
"baseUrl": ".",
"paths": {
    "@/*": [ "./*" ]
 }
Run Code Online (Sandbox Code Playgroud)

我没有为每个文件夹指定单独的别名,而是使用上面的别名,现在它可以正常工作。