javascript - Configure ESLint to parse .ts and .tsx as Typescript and .js and .jsx as Ecmascript
问题描述
I have installed typescript to use in my Create React App project. I want to gradually refactor the ES files to TS.
But the linter now also parses the .js and .jsx files as 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
Is it possible to parse the .js and .jsx files as Ecmascript and the .ts and .tsx as Typescript?
My configuration is:
./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"
]
}
The command used to run:
{
"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
可以通过(source)将其添加到.eslintrc来解决(推荐):
{
"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 错误。不理想,但在撰写本文时似乎是唯一的方法。
推荐阅读
- java - 自定义视图组内的更改未呈现
- javascript - React:如何将数组作为道具传递并渲染图像列表?
- php - 提交带有日期步骤的表单而不重新加载页面
- javascript - @webkit 关键帧不能很好地悬停任何解决方案?
- tensorflow - 如何从数据集中连续获取?
- c# - 测试项目不在 Visual Studio 2019 中的一个解决方案中运行,而是在另一个解决方案中运行
- python - “numpy.int64”对象不支持项目分配
- r - 显示文本的三重维恩图
- mongodb - 如何在实时数据库上添加复合文本索引而不影响依赖现有文本索引的用户?
- angular - 'mat-form-field' 不是已知元素 - Angular 9 和 Material 9.2.0