ESLint9无法识别类静态成员?如何调整eslint.config.mjs配置
问题诊断与解决方案
你的类静态成员定义完全正确,符合ES2022标准语法,报错的核心原因是ESLint配置中的sourceType设置错误,导致解析器无法正确识别ES模块+类静态字段的组合。
问题根源
你在页面对象代码中使用了ES模块语法(export default),但配置里的sourceType被设为了"commonjs"。ESLint会基于这个配置用CommonJS的规则解析代码,从而无法识别ES2022的类静态字段语法,抛出Unexpected token =错误。
修复步骤
修改eslint.config.mjs中的languageOptions.sourceType为"module",匹配你的代码模块类型:
import { FlatCompat } from '@eslint/eslintrc' import mochaPlugin from 'eslint-plugin-mocha' import globals from "globals"; const compat = new FlatCompat() export default [ { languageOptions: { ecmaVersion: 2022, sourceType: "module", // 修正为module globals:{ ...globals.browser } }, }, mochaPlugin.configs.flat.recommended, { rules: { 'mocha/no-exclusive-tests': 'error', 'mocha/no-skipped-tests': 'error', 'mocha/no-mocha-arrows': 'off' } }, ...compat.config( { extends: ['plugin:cypress/recommended'], rules: { 'cypress/no-unnecessary-waiting': 'off' } }) ]
额外说明
ESLint 9默认使用的Espree解析器完全支持ES2022的类静态字段特性,所以只要修正sourceType配置,就能解决解析错误。不需要额外安装或配置其他解析器(除非你有特殊的Babel转译需求)。
内容的提问来源于stack exchange,提问作者Jeroen
相关产品推荐
相关产品推荐

