Home > Mobile >  cannot find module when using alias with Typescript and Eslint
cannot find module when using alias with Typescript and Eslint

Time:01-13

I have an error when trying to import a ts file using alias.

Cannot find module '@utils/helpers' or its corresponding type declarations.

And also i got no autocompletion is vscode.
I installed tsconfig-paths and eslint-import-resolver-typescript

tsconfig.json file

{
    "compilerOptions": {
        "module": "commonjs",
        "sourceMap": true,
        "target": "es6",
        "esModuleInterop": true,
        "moduleResolution": "node",
        "outDir": "dist",
        "baseUrl": "./src",
        "paths": {
            "@utils": ["utils/*"]
        },
    },
    "include": ["src"],
    "exclude": ["node_modules", "dist"]
}

.eslintrc file

{
    "root": true,
    "parser": "@typescript-eslint/parser",
    "plugins": ["@typescript-eslint", "import"],
    "extends": ["plugin:@typescript-eslint/recommended", "prettier"],
    "rules": {
        
    },
    "settings": {
        "import/parsers": {
            "@typescript-eslint/parser": [".ts"]
        },
        "import/resolver": {
            "typescript": {
                "alwaysTryTypes": true,
                "project": "tsconfig.json"
            }
        }
    }
}

This is my project structure

enter image description here

Build error

enter image description here

CodePudding user response:

  • You have configured eslint - that will lint about the @utils existence
  • You have configured tsconfig - that will auto suggest files inside that directory
  • But you haven't told JS @utils exists and it's types

To do so, install tsconfig-paths package, this will tell js where to look for @utils

Usage is quite simple, you just put tsconfig-paths/register before your nodemon, here's my package.json

"start": "ts-node -r tsconfig-paths/register src/server",
"dev": "ts-node-dev -r tsconfig-paths/register --respawn src/server",

Or you can put it inside tsconfig.json

{
    "compilerOptions": {
        ...
        "baseUrl": "./src",
        "paths": {
            "@utils/*": ["utils/*"]
        },
    },
    "ts-node": {
        "require": ["tsconfig-paths/register"]
    },
    "ts-node-dev": {
        "require": ["tsconfig-paths/register"]
    }
}
  • Related