I keep receiving a TypeScript warning stating that the module cannot be found.
This issue has surfaced while I'm utilizing TypeScript in my NextJS application, particularly when using custom paths. Previously, this problem never arose.
My project structure resembles the following:
/models
|-- index.ts
|-- User.ts
/pages
/api
/users
|-- index.ts
I am attempting to import my Userschema
from the custom path I defined in models
, but encountering an error.
Here is how my index.ts
file within models
appears:
export { default as User } from './User';
This is how I am trying to import it inside api/user/index.ts
:
import { User } from '@/models';
The contents of my tsconfig
file are as follows:
{
"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"
]
}
Importing using custom paths for non-index files like
import dbConnect from '@/utils/dbConnect'
functions properly. However, with index files, I still need to specify the index file name during import to make it work. For example: import { User } from '@/models/index'