Eduardo Sousa
Eduardo Sousa

Reputation: 1075

Typescript path resulting in wrong import

I am using Typescript (4.1.3) and I started using custom paths in tsconfig.json. Ever since, when I import any .ts file, if I dont use the whole path , I get the error:

Error:(138, 33) TS2307: Cannot find module 'pages/foo/bar' or its corresponding type declarations.

To fix that I must add the prefix 'src/', so I get 'src/pages/foo/bar'. The project itself works fine, even with this TS Error.

Here is my tsconfig.json file

{
"compilerOptions": {
    "allowJs": true,
    "sourceMap": true,
    "target": "es6",
    "strict": true,
    "declaration": false,
    "noImplicitAny": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "module": "esnext",
    "moduleResolution": "node",
    "strictNullChecks": false,
    "baseUrl": ".",
    "paths": {
        "foo": [
            "bar.js"
        ]
    },
    "types": [
        "quasar",
        "node",
        "cypress"
    ],
    "lib": [
        "es2018",
        "dom"
    ]
},
"exclude": [
    "node_modules"
],
"extends": "@quasar/app/tsconfig-preset"

}

Upvotes: 0

Views: 7447

Answers (3)

Khalid Rafik
Khalid Rafik

Reputation: 49

Just add "typescript-path-fix" into your task runner pipeline or call it just before compiling your code

Use this package to resolve your issue: https://www.npmjs.com/package/typescript-path-fix

Upvotes: 0

Riad Baghbanli
Riad Baghbanli

Reputation: 3319

compilerOptions.baseUrl is being prefixed to path specified in import statement to create path relative to the location of tsconfig.json file.

In your case the path to module bar.js in relation to tsconfig.json file is src/pages/foo/bar. So you either specify ./src in compilerOptions.baseUrl or specify that complete path in import statement.

Upvotes: 4

Pavan
Pavan

Reputation: 858

This seems to be issue with your config baseUrl:"." , this means that js module resolution happens from current dir that's why your imports complaints to add src dir.

Make sure you point this config to src dir then all import resolution takes place from that dir. Example: baseUrl:"./src"

More details : https://www.typescriptlang.org/tsconfig#baseUrl

Upvotes: 1

Related Questions