JS Class 中使用static声明属性 ESLint 报错

出现问题的代码

class Ani{
    constructor(name,age){
        this._name = name;
        this._age = age;
    }  
    static displayName = '??' // `这里出错`
}

环境

VSC 配置的Nodej环境

下面是VSC版本信息:

Version: 1.59.0
Commit: 379476f0e13988d90fab105c5c19e7abc8b1dea8
Date: 2021-08-04T23:14:40.191Z
Electron: 13.1.7
Chrome: 91.0.4472.124
Node.js: 14.16.0
V8: 9.1.269.36-electron.0
OS: Darwin x64 19.6.0

package.json


{
  "name": "ln",
  "version": "1.0.0",
  "description": "why",
  "main": "app.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node ./src/app.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "koa": "^2.13.1",
    "koa-body": "^4.2.0",
    "koa-router": "^10.0.0",
    "koa-static": "^5.0.0",
    "koa-views": "^7.0.1"
  },
  "devDependencies": {
    "@babel/core": "^7.15.0",
    "@babel/eslint-parser": "^7.15.0",
    "@babel/plugin-proposal-class-properties": "^7.14.5",
    "@babel/preset-env": "^7.15.0",
    "es-checker": "^1.4.2",
    "eslint": "^7.32.0",
    "eslint-config-airbnb-base": "^14.2.1",
    "eslint-plugin-import": "^2.23.4"
  }
}

下面是eslintrc.json信息:

{
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "ecmaVersion": 12,
        "sourceType": "module"
    },
    "rules": {
    }
}

错误信息

ESLint: Parsing error: Unexpected token =

补充

注意:package.json type:module;也就是说Node中我使用的ES模块导入;

阅读 6.4k
1 个回答

如果需要直接初始化类字段的声明的话,需要支持ES2022.

看你的 ESLint 配置中没有配置解析器,那 ESLint 就会使用默认的解析器.
ESLint 中使用的默认解析器是Espree,你可以用yarn list --pattern espree或者npm list espree看下你本地的Espree版本,目前一般都是7.3.1版本,只支持到部分ES2021,还不支持ES2022.

如果需要支持类字段声明的话,可以使用@babel/eslint-parser解析器,然后通过插件@babel/plugin-proposal-class-properties来实现支持.

安装依赖

yarn add -D @babel/core @babel/preset-env @babel/eslint-parser @babel/plugin-proposal-class-properties
#or
npm install @babel/core @babel/preset-env @babel/eslint-parser @babel/plugin-proposal-class-properties --save-dev

Babel 配置

// babel.config.js

/**
 * @type {import('@babel/core').TransformOptions}
 */
module.exports = {
  presets: ['@babel/env'],
  plugins: ['@babel/plugin-proposal-class-properties'],
}

ESLint 配置

/**
 * @type {import('eslint').Linter.Config} config
 */
const eslintConfig = {
  env: {
    browser: true,
    es2021: true,
  },
  parser: '@babel/eslint-parser', // 这里配置解析器
  extends: 'eslint:recommended',
  parserOptions: {
    ecmaVersion: 12,
    sourceType: 'module',
  },
  rules: {},
}

module.exports = eslintConfig

这样就配置好了

如果是在 VSCode 中的话,有可能需要重启 ESLint 插件,按快捷键Ctrl(Mac Cmd) + Shift + p在弹出的提示框中输入Restart Eslint Server,或者直接重启 VSCode 也可以.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题