简体   繁体   中英

cannot find module when using alias with Typescript and Eslint

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

在此处输入图像描述

Build error

在此处输入图像描述

  • 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"]
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM