簡體   English   中英

配置 ESLint 解析.ts 和 .tsx 為 Typescript 和.js 和.jsx 為 Ecmascript

[英]Configure ESLint to parse .ts and .tsx as Typescript and .js and .jsx as Ecmascript

我已經安裝了 typescript 以在我的 Create React App 項目中使用。 我想逐步將 ES 文件重構為 TS。

但是 linter 現在也將 .js 和 .jsx 文件解析為 Typescript。

/project/file.js
  19:35  warning  Missing return type on function  @typescript-eslint/explicit-function-return-type
  20:35  warning  Missing return type on function  @typescript-eslint/explicit-function-return-type

是否可以將 .js 和 .jsx 文件解析為 Ecmascript 並將 .ts 和 .tsx 解析為 Typescript?

我的配置是:

./eslintrc

{
  "extends": [
    "airbnb",
    "prettier",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended",
    "prettier/@typescript-eslint"
  ],
  "parser": "@typescript-eslint/parser",
  "rules": {
    "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx", ".tsx", ".ts"] }],
  }
}

./tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}

用於運行的命令:

{
  "scripts": {
    "lint": "node_modules/.bin/eslint --ext=.jsx,.js,.tsx,.ts  ."
  }
}

啊,你應該使用 eslint.rc 中的 overrides 屬性, 如本文所述

"overrides": [
    {
      "files": ["*.ts", "*.tsx"],
      "extends": [
        "plugin:@typescript-eslint/eslint-recommended",
        "plugin:@typescript-eslint/recommended",
        "prettier/@typescript-eslint"
      ],
      "parser": "@typescript-eslint/parser",
      "plugins": ["@typescript-eslint"]
    }
  ]

然后我注意到包含 TS 的 ES 文件沒有找到 .ts 文件:

/project/file.js
  3:26  error  Unable to resolve path to module './AnotherComonent' import/no-unresolved
  3:26  error  Missing file extension for "./AnotherComonent"       import/extensions

可以通過將其添加到.eslintrc (推薦)來解決( source ):

{
  "extends": ["plugin:import/typescript"],
  "rules": {
    "import/extensions": [
      "error",
      "always",
      {
        "js": "never",
        "jsx": "never",
        "ts": "never",
        "tsx": "never"
      }
    ],
}

或者(來源來源):

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

換句話說,手動添加文件的解析器。

並忽略 im/extensions 錯誤。 不理想,但在撰寫本文時似乎是唯一的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM