我在我的文件app.spec.ts中有这个导入:

import app from './app';

是什么导致了这个Typescript错误

2:17  error  Unable to resolve path to module './app'  import/no-unresolved

/应用程序。ts确实存在,但我没有将.ts文件编译成.js文件。一旦我把.ts文件编译成.js文件,错误就消失了。

然而,由于eslint应该与typescript一起工作,它应该用.ts而不是.js来解析模块。

我还在eslint配置文件中添加了typescript信息:

"parser": "@typescript-eslint/parser",
"parserOptions": {
    "project": "./tsconfig.json"
}

我如何配置eslint在这样一种方式,它试图解决模块与.ts而不是.js?

编辑# 1

app.ts的内容:

import bodyParser from 'body-parser';
import express from 'express';
import graphqlHTTP from 'express-graphql';
import { buildSchema } from 'graphql';

const app = express();

const schema = buildSchema(`
    type Query {
        hello: String
    }
`);
const root = { hello: () => 'Hello world!' };

app.use(bodyParser());
app.use('/graphql', graphqlHTTP({
    schema,
    rootValue: root,
    graphiql: true,
}));

export default app;

当前回答

如果你已经更新了你的.eslintrc和tsconfig。Json文件的建议在其他答案,你仍然有问题-重新启动vscode。

其他回答

你可以通过在你的.eslintrc.json配置文件中添加以下代码片段来设置ESLint模块的导入分辨率:

{
  "settings": {
    "import/resolver": {
      "node": {
        "extensions": [".js", ".jsx", ".ts", ".tsx"]
      }
    }
  },
  ...
}

有关解析器的更多信息:https://github.com/benmosher/eslint-plugin-import#resolvers。

优秀的人知道如何在2022年通过在线程序解决这个问题:

"rules": {
  "import/extensions": [ "error", "ignorePackages", { "": "never" } ]
}

对于那些使用babel-module的人来说,只要添加扩展,它就会像这样:

      "babel-module": {
        "extensions": [".js", ".jsx", ".ts", ".tsx"],
        "alias": {
          "app": "./app"
        }
      }

这是唯一对我有效的解决办法。

首先,你需要安装这个包:

yarn add -D eslint-import-resolver-typescript

然后将其添加到.eslintrc文件中,以便它可以从tsconfig加载别名设置。json到ESLint:

{
  "settings": {
    "import/resolver": {
      "typescript": {}
    },
  },
}

ts和eslint都在对我吼叫,所以我必须在.eslintrc文件中添加以下内容:

{ 
    ...
    "rules": {
        ....
        "import/extensions": "off"
    },
    "settings": {
        ....
        "import/resolver": {
            "node": {
                "extensions": [".js", ".jsx", ".ts", ".tsx"]
            }
        }
    }
}