Hi*_*bo 31 node.js express typescript eslint
在其他线程中,我读到当 eslint 和 tsconfig.json 不在同一工作文件夹中时可能会出现问题,但我在项目的根文件夹中拥有所有文件。不知何故,初始化项目后,抛出的错误似乎尝试在项目的父文件夹中(因此,在项目外部)查找 tsconfig.json:
假设项目位于:'\parentFolder\ProjectRoot' tsconfig 位于路线中:'\parentFolder\ProjectRoot\tsconfig.json
我得到的 eslint 错误(位于 index.ts 的顶部)如下:
解析错误:无法读取文件“ parentFolder \tsconfig.json”
\parentFolder\ProjectRoot 的内容是:
达到这一点的步骤是:
.eslintrc:
{
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-requiring-type-checking"
],
"plugins": ["@typescript-eslint"],
"env": {
"browser": true,
"es6": true
},
"rules": {
"@typescript-eslint/semi": ["error"],
"@typescript-eslint/explicit-function-return-type": 0,
"@typescript-eslint/no-unused-vars": [
"error", { "argsIgnorePattern": "^_" }
],
"@typescript-eslint/no-explicit-any": 1,
"no-case-declarations": 0
},
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "./tsconfig.json"
}
}
Run Code Online (Sandbox Code Playgroud)
tsconfig.json
{
"compilerOptions": {
"target": "ES6",
"outDir": "./build/",
"module": "commonjs",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"esModuleInterop": true
}
}
Run Code Online (Sandbox Code Playgroud)
package.json(看起来像将“main”中的index.js更改为index.ts没有任何作用)
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"tsc": "tsc",
"dev": "ts-node-dev index.ts",
"lint": "eslint --ext .ts ."
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/express": "^4.17.9",
"@typescript-eslint/eslint-plugin": "^4.9.0",
"@typescript-eslint/parser": "^4.9.0",
"eslint": "^7.14.0",
"ts-node-dev": "^1.0.0",
"typescript": "^4.1.2"
},
"dependencies": {
"express": "^4.17.1"
}
}
Run Code Online (Sandbox Code Playgroud)
index.ts (我在 req 和 res 中遇到隐式错误,我想这是由于找不到 tsconfig 造成的)。
const express = require('express');
const app = express();app.use(express.json());
const PORT = 3000;
app.get('/ping', (_req, res) => {
res.send('pong');
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Run Code Online (Sandbox Code Playgroud)
编辑:
我在全球范围内安装了打字稿(也作为这些项目中的开发依赖项)。我认为这可能是问题所在,因此卸载了全局版本的打字稿。
当使用 npm list -g --depth 0 检查所有全局包时,我得到以下信息:
我不知道这是否与该问题有关。
Jos*_*ggs 55
对我有用的是您要添加的文件夹的 .eslintrc :
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname // <-- this did the trick for me
}
Run Code Online (Sandbox Code Playgroud)
Joa*_*ves 28
我把这个答案放在这里作为一种防白痴措施。如果您在错误的文件夹中打开项目,也可能会发生这种情况。当我打开项目的父目录而不是项目目录本身时,出现此错误。我有一个项目GitLab -> projectFolder并打开了 GitLab。我收到错误消息说tsconfig.json无法读取。
我在我的子项目中遇到了非常相似的问题,解决我的问题的是修改parserOptions我的子项目中的.eslintrc.json:
{
"globals": {
"__dirname": true
},
"overrides": [{
"parserOptions": {
"project": "**/tsconfig.json",
"sourceType": "module"
},
}]
}
Run Code Online (Sandbox Code Playgroud)