配置ESLint以将.ts和.tsx解析为Typescript并将.js和.jsx解析为Ecmascript

时间:2020-07-17 11:34:49

标签: javascript reactjs typescript eslint

我已经安装了要在我的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  ."
  }
}

1 个答案:

答案 0 :(得分:1)

啊,您应该使用eslint.rc as described in this post中的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

可以通过(source)将其添加到 .eslintrc (推荐)中来解决:

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

或(sourcesource):

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

换句话说,手动为文件添加解析器。

并忽略im / extensions错误。这不是理想的方法,但在撰写本文时,这似乎是唯一的方法。