TypeScript CDK项目本地ESLint正常,GitLab流水线报'import'解析错误怎么办?
本地执行npm run eslint无错误,但GitLab流水线中执行相同命令时出现错误:
1:1 error Parsing error: The keyword 'import' is reserved
相关配置信息如下:
package.json 的 devDependencies
"devDependencies": { "@types/aws-lambda": "8.10.109", "@types/jest": "27.5.2", "@types/node": "^10.17.27", "@types/node-fetch": "^2.6.2", "@types/prettier": "2.6.0", "@types/yamljs": "0.2.31", "@typescript-eslint/eslint-plugin": "^4.30.0", "@typescript-eslint/parser": "^4.30.0", "eslint-config-prettier": "^8.3.0", "eslint-config-standard": "^16.0.3", "eslint-plugin-import": "^2.24.2", "eslint-plugin-node": "^11.1.0", "eslint-plugin-promise": "^5.1.0", "aws-cdk": "2.67.0", "esbuild": "^0.16.7", "eslint": "^7.32.0", "jest": "^27.5.1", "npm-run-all": "^4.1.5", "prettier": "^2.3.2", "ts-jest": "27.1.4", "ts-node": "10.9.1", "typescript": "~3.9.7" },
npm 脚本
"eslint": "eslint --ext .ts,.tsx .",
.eslintrc.js 配置
module.exports = { env: { es2021: true, node: true, jest: true, }, extends: ["plugin:@typescript-eslint/recommended", "standard", "prettier"], parser: "@typescript-eslint/parser", parserOptions: { ecmaVersion: 12, sourceType: "module", }, plugins: ["@typescript-eslint"], rules: { "no-new": "off", camelcase: "off", "@typescript-eslint/no-non-null-assertion": "off", "@typescript-eslint/no-unused-vars": [ "warn", { argsIgnorePattern: "^_.*" }, ], "no-eq-null": "error", }, };
.gitlab-ci.yml 配置
eslint: stage: static-test image: name: public.ecr.aws/docker/library/node:16-alpine script: - npm install - npm run eslint
请问该如何修复此错误?是否需要将.eslintrc.js改为.eslintrc?
不需要将.eslintrc.js改为.eslintrc,.js格式的配置文件是ESLint合法的配置格式,问题不在配置文件类型上。
问题根源是GitLab流水线中ESLint未正确识别TypeScript文件,或依赖安装版本与本地不一致,可按以下步骤修复:
强制指定TypeScript文件的解析规则
在.eslintrc.js中添加overrides配置,确保所有.ts/.tsx文件使用@typescript-eslint解析器:module.exports = { // 原有配置... overrides: [ { files: ["*.ts", "*.tsx"], parser: "@typescript-eslint/parser", parserOptions: { ecmaVersion: 12, sourceType: "module", project: "./tsconfig.json" // 若项目有tsconfig,添加此配置确保解析对齐 } } ] };统一流水线与本地的依赖版本
将GitLab CI脚本中的npm install替换为npm ci,该命令会严格按照package-lock.json安装依赖,避免版本不一致:eslint: stage: static-test image: name: public.ecr.aws/docker/library/node:16-alpine script: - npm ci - npm run eslint注意:需确保
package-lock.json已提交至仓库。检查并补全tsconfig.json配置
若项目没有tsconfig.json,创建基础配置确保TypeScript模块解析规则与ESLint一致:{ "compilerOptions": { "target": "ES2020", "module": "CommonJS", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["**/*.ts"] }验证依赖兼容性
当前eslint@7.32.0与@typescript-eslint/parser@4.30.0版本兼容,若仍有问题,可将@typescript-eslint系列包升级到4.x分支的最新版本(保持与ESLint 7.x兼容)。
内容的提问来源于stack exchange,提问作者Jatin Mehrotra

