0

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"

}

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I see, but why this happens only if I add the "paths" configuration in tsconfig?
Not working, w/ tsc or w/ ts-loader.
1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.