简体   繁体   English

如何使用私有方法为 ES6 类正确配置 eslint?

[英]How to configure eslint for ES6 class with private methods correctly?

I was writing ES6 class with private properties/methods in vue project.我正在 vue 项目中编写带有私有属性/方法的 ES6 类。 And using eslint to lint the code.并使用 eslint 对代码进行 lint。 Below is the example class:下面是示例类:

class TestClass {
  constructor(value) {
    this.#privateProperty = value
    this.#privateMethod(this.#privateProperty)
  }

  #privateProperty = undefined

  // lint error raised at below line
  #privateMethod(value) {
    this.e = value
    console.log(this.e)
  }
}

The vue project is created by @vue/cli 4.1.2. vue 项目由@vue/cli 4.1.2 创建。 And here are some configures about the project:以下是有关该项目的一些配置:

babel.config.js: babel.config.js:

module.exports = {
  presets: ['@vue/cli-plugin-babel/preset'],
  plugins: [
    ['@babel/plugin-proposal-class-properties', { loose: true }],
    ['@babel/plugin-proposal-private-methods', { loose: true }]
  ]
}

package.json:包.json:

{
  "name": "demo-project",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "test:unit": "vue-cli-service test:unit",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^0.19.0",
    "cesium": "^1.64.0",
    "core-js": "^3.4.4",
    "mockjs": "^1.1.0",
    "vue": "^2.6.10",
    "vue-router": "^3.1.3",
    "vuex": "^3.1.2"
  },
  "devDependencies": {
    "@babel/plugin-proposal-private-methods": "^7.8.0",
    "@vue/cli-plugin-babel": "^4.1.0",
    "@vue/cli-plugin-eslint": "^4.1.0",
    "@vue/cli-plugin-router": "^4.1.0",
    "@vue/cli-plugin-unit-jest": "^4.1.0",
    "@vue/cli-plugin-vuex": "^4.1.0",
    "@vue/cli-service": "^4.1.0",
    "@vue/eslint-config-prettier": "^5.0.0",
    "@vue/test-utils": "1.0.0-beta.29",
    "babel-eslint": "^10.0.3",
    "copy-webpack-plugin": "^5.1.1",
    "eslint": "^5.16.0",
    "eslint-plugin-prettier": "^3.1.1",
    "eslint-plugin-vue": "^5.0.0",
    "lint-staged": "^9.5.0",
    "node-sass": "^4.12.0",
    "prettier": "^1.19.1",
    "sass-loader": "^8.0.0",
    "vue-template-compiler": "^2.6.10",
    "webpack": "^4.41.5"
  },
  "gitHooks": {
    "pre-commit": "lint-staged"
  },
  "lint-staged": {
    "*.{js,vue}": [
      "vue-cli-service lint",
      "git add"
    ]
  }
}

.eslintrc.js .eslintrc.js

module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: ["eslint:recommended", "plugin:vue/recommended", "@vue/prettier"],
  rules: {
    "no-console": process.env.NODE_ENV === "production" ? "error" : "off",
    "no-debugger": process.env.NODE_ENV === "production" ? "error" : "off"
  },
  parserOptions: {
    parser: "babel-eslint"
  },
  overrides: [
    {
      files: [
        "**/__tests__/*.{j,t}s?(x)",
        "**/tests/unit/**/*.spec.{j,t}s?(x)"
      ],
      env: {
        jest: true
      }
    }
  ],
  globals: {
    'process': true
  }
};

The problem is that eslint always raises lint error Parsing error: This experimental syntax requires enabling the parser plugin: 'classPrivateMethods' at hashtag of #privateMethod .问题是,eslint总是引发皮棉错误Parsing error: This experimental syntax requires enabling the parser plugin: 'classPrivateMethods'在主题标签#privateMethod

I googled a lot but fail to find out what I have missed.我用谷歌搜索了很多,但没有找到我错过了什么。

Please help, and thanks very much.请帮忙,非常感谢。

你只需要安装 babel-eslint 版本v11.0.0-beta.0 ,但正如你所看到的它的 beta 版本,但这应该适用于这种语法。

Okay so I came here to share what I learned as it took me a while to find it.好的,所以我来这里分享我学到的东西,因为我花了一段时间才找到它。 Looking at the picture of the configuration file above, it looks like your doing it by implement individual rules for the support you seek, however, there is a Babel Preset NPM Package that makes it so all ECMAS Stage-3 Proposals are supported, and its a lot less configuration, you just need to know how to do it, which is why I am writing this.查看上面配置文件的图片,看起来您是通过为您寻求的支持实施单独的规则来实现的,但是,有一个Babel Preset NPM 包可以支持所有 ECMAS Stage-3 Proposals,并且它的配置少了很多,你只需要知道怎么做,这就是我写这篇文章的原因。 First I want to say that I can tell you now that this will not be a short answer.首先我想说,我现在可以告诉你,这不会是一个简短的答案。 To explain the process required will take some typing, and effort on my part.解释所需的过程需要一些打字和我的努力。 One reason so many guides fail to successful help people get babel to work in sync with ESLint is because it takes a bit of time to explain the solution in text.许多指南未能成功帮助人们让 babel 与 ESLint 同步工作的原因之一是因为用文本解释解决方案需要一些时间。 Though once it is explained, you will see, it is pretty simple.虽然一旦解释了,你就会看到,它非常简单。



HERE WE GO:开始了:

First Off you will need to make sure you have ESLint, so go ahead and do the following.首先,您需要确保拥有 ESLint,因此请继续执行以下操作。

:~$ npm init
:~$ npm i -D eslint
:~$ eslint --init 

Hopefully your familiar with the above commands.希望您熟悉上述命令。 If you are not then you need to go learn how to configure ESLint first.如果你不是,那么你需要先去学习如何配置 ESLint。 At this point you should have a fresh eslintrc.json file (or the YAML equivalent) that is rule free and plugin'less.此时你应该有一个新的eslintrc.json文件(或 YAML 等效文件),它是无规则且无插件的。 It probably extends Google or Airbnb (I use Google's JS style-guide, but it doesn't matter).它可能扩展了 Google 或 Airbnb(我使用 Google 的 JS 样式指南,但没关系)。 You should also have an a fresh set if NPM package files, though we wont use them.如果 NPM 包文件,你也应该有一个新的集合,尽管我们不会使用它们。 Now we will install BABEL.现在我们将安装 BABEL。 Babel, has really improved. Babel,真的进步了。 Configuring Babel in the past was difficult IMO, but now they have a preset module and it makes configuring Babel much more simple.过去配置 Babel 很困难 IMO,但现在他们有了一个预设模块,这使得配置 Babel 变得更加简单。




There Are 4x NPM Packages That You Will Need to Download:您需要下载 4 个 NPM 软件包:

All the Babel modules you'll need are published as separate npm packages scoped under @babel (since version 7).您需要的所有 Babel 模块都作为单独的 npm 包发布,范围在 @babel 下(自第 7 版起)。 This modular design allows for various tools each designed for a specific use case.这种模块化设计允许使用各种工具,每种工具都是为特定用例设计的。 Here we'll look at @babel/core在这里我们将看看@babel/core

-- BabelJS.io -- BabelJS.io

There are four Downloads from NPM that need to be completed to get support for Private Members, and other ECMAScript Stage-3 Proposals:有四个来自 NPM 的下载需要完成才能获得对私有成员的支持,以及其他 ECMAScript Stage-3 提案:

  1. Babel Itself巴别塔本身

  2. Babel Configuration Module (Makes Life Easy) Babel 配置模块(让生活更轻松)

  3. Babels ESLint Plugin Babels ESLint 插件

  4. Babel-Parser for ESLint用于 ESLint 的 Babel-Parser

To give this answer the best chance at giving you the solution you need, I am going to go through each NPM module separately, and Ill give you a link to the documentation in case something isn't working right.为了给这个答案最好的机会为您提供您需要的解决方案,我将分别介绍每个 NPM 模块,如果出现问题,我会给您一个指向文档的链接。 Every Development Environment varies, and this configuration can, and likely will, very on the Development Environment you are using.每个开发环境都各不相同,并且此配置可以并且很可能非常适合您正在使用的开发环境。 For example I format with prettier which posed another set of challenges to make it work after I switched the parser that ESLint was using.例如,我使用 prettier 进行格式化,这在我切换 ESLint 使用的解析器后带来了另一组挑战以使其工作。 If you use the resources put forward.如果使用资源提出。 There is no reason you shouldn't be able to get Babel working with eslint, and get ESLint configured properly so that Private-Members, and every other Stage-3 ECMAScript Proposal, do not through errors when you lint your documents.您没有理由不能让 Babel 与 eslint 一起工作,并正确配置 ESLint,以便 Private-Members 和所有其他 Stage-3 ECMAScript Proposal 在您对文档进行 lint 时不会出现错误。



(NPM DL #1) (NPM DL #1)

Install Babel:安装巴别:

In order TO GET BABEL Copy and paste the following command into your Terminal.为了获得BABEL ,将以下命令复制并粘贴到您的终端中。

:~$ npm i -D @babel/core 

Babel/core is self explanatory as the core functionality of Babel resides at the heart of the @babel/core module. Babel/core 是不言自明的,因为 Babel 的核心功能位于@babel/core 模块的核心。



(NPM DL #2) (NPM DL #2)

Install Babel's Preset Module安装 Babel 的预设模块

:~$ npm i -D @babel/preset-env

Without any configuration, this preset will include all plugins to support modern JavaScript.无需任何配置,此预设将包含支持现代 JavaScript 的所有插件。 It also includes support for all stage-3 ECMAScript Proposals.它还包括对所有第 3 阶段 ECMAScript 提案的支持。 The whole issue that caused us to need Babel's parser is that ESLint's default parser and core rules only support the latest final ECMAScript standard syntax and do not support experimental syntax.导致我们需要 Babel 解析器的整个问题是 ESLint 的默认解析器和核心规则仅支持最新的最终 ECMAScript 标准语法,不支持实验性语法。



(NPM DL #3) (NPM DL #3)

Install Babel Parser For ESLint为 ESLint 安装 Babel 解析器


:~$ npm

ESLint allows for the use of custom parsers. ESLint 允许使用自定义解析器。 When using this plugin, your code is parsed by Babel's parser (using the configuration specified in your Babel configuration file) and the resulting AST (For those who don't know AST is an Abstract Syntax Tree) is transformed into an ESTree-compliant structure that ESLint can understand.使用这个插件时,你的代码会被 Babel 的解析器解析(使用你在 Babel 配置文件中指定的配置),并且生成的 AST(对于那些不知道 AST 是抽象语法树的人)被转换成符合 ESTree 的结构ESLint 可以理解。 All location info such as line numbers, columns is also retained so you can track down errors with ease.还保留所有位置信息,例如行号、列,以便您可以轻松追踪错误。


Note: ESLint's core rules do not support experimental syntax and may therefore not work as expected when using @babel/eslint-parser.注意: ESLint 的核心规则不支持实验性语法,因此在使用 @babel/eslint-parser 时可能无法按预期工作。 Please use the companion @babel/eslint-plugin plugin for core rules that you have issues with.对于您遇到问题的核心规则,请使用配套的 @babel/eslint-plugin 插件。

-- Babel-ESLint-Parser README.md Document -- Babel-ESLint-Parser README.md 文档



(NPM DL #4) (NPM DL #4)

Install Babel's ESLint Plugin:安装 Babel 的 ESLint 插件:

:~$ npm i -D @babel/eslint-plugin

Companion rules for @babel/eslint-parser. @babel/eslint-parser 的配套规则。 @babel/eslint-parser does a great job at adapting eslint for use with Babel, but it can't change the built-in rules to support experimental features. @babel/eslint-parser 在调整 eslint 以与 Babel 一起使用方面做得很好,但它无法更改内置规则以支持实验性功能。 @babel/eslint-plugin re-implements problematic rules so they do not give false positives or negatives. @babel/eslint-plugin 重新实现了有问题的规则,因此它们不会给出误报或否定。

-- The @babel/eslint-plugin Repository -- @babel/eslint-plugin 存储库



The Following is DEPRECATED, and THEREFORE, WRONG!以下内容已被弃用,因此是错误的!

npm install eslint babel-eslint --save-dev

If you see a solution using the above, or any other NPM packages that don't have "@babel/..." in the NPM Package name, then that solution is deprecated and probably will not work.如果您看到使用上述解决方案的解决方案,或任何其他 NPM 包名称中没有“@babel/...”的 NPM 包,则该解决方案已被弃用,并且可能无法正常工作。



Configure the '.babelrc' & '.eslintrc' Files配置“.babelrc”和“.eslintrc”文件

First I will show you what the .eslintrc file should look like, and explain it through comments.首先,我将向您展示 .eslintrc 文件应该是什么样子,并通过注释进行解释。

{
  "env": {
    //  Make sure your environment is configured properly
    "es2021": true,
    "commonjs": true,
    "node": true,
    "browser": false
  },

  "extends": ["google"],
  "plugins": [
    "prettier",
    "@babel" // This is where you inform ESLint that you want to use @babel/eslint-plugin. If you have other plugins use an array.
  ],

  "parser": "@babel/eslint-parser", // He is where you communicate to ESLint that you want to use the @babel/eslint-parser.

  "parserOptions": {
    "ecmaVersion": 2021, // 12 or 2021 is the most current ECMAS Version

    "sourceType": "module", // For use with JS Modules set to module, otherwise it can be set to script

    "allowImportExportEverywhere": false, // When set to true this configuration allows import and export declarations to be placed where ever a statement can be made. Obviously your Env must support the Dynamic placement of the import/export statements for it to work.

    "ecmaFeatures": {
      "globalReturn": false // allow return statements in the global scope when used with sourceType: "script".
    }
    
  },

  "rules": {
    "require-jsdoc": "off",
    "arrow-body-style": "off",
    "prefer-arrow-callback": "off",
    "no-unused-expressions": "warn",
    "no-unused-vars": "warn",

    // These are all the rules that Babel-Plugin has support for. If the plugin will implement a rule, you should have it do so instead of using ESLint's equal rule.
    "@babel/new-cap": "error",
    "@babel/no-invalid-this": "error",
    "@babel/no-unused-expressions": "error",
    "@babel/object-curly-spacing": "error",
    "@babel/semi": "error",

    /* 
    I Omitted this rule because @Babel-Plugin offers this rule. 
    "semi": ["error", "always"],    */
   
  }
}

Finally We Can Create a ".babelrc" File now!现在我们终于可以创建一个“.babelrc”文件了!

I don't know all the mechanics behind everything we are doing in this answer, and I won't pretend to.我不知道我们在这个答案中所做的一切背后的所有机制,我不会假装。 I tried, about 8 months ago, when doing somthing else with Babel, to get a .babelrc file to work, and I could not.大约 8 个月前,当我用 Babel 做其他事情时,我尝试让 .babelrc 文件工作,但我不能。 I had to use babelrc.js.我不得不使用 babelrc.js。 For some reason the configuration I am explaining makes it so the file we must use is .babelrc, which makes me very happy.出于某种原因,我正在解释的配置使得我们必须使用的文件是 .babelrc,这让我很高兴。

So with that said, in Your Projects Root Directory create the file .babelrc .话虽如此,在您的项目根目录中创建文件.babelrc After you create the "...ProjectRoot/.babelrc" configuration file, the rest of this answer is very simple, as you can see below.创建“...ProjectRoot/.babelrc”配置文件后,此答案的其余部分非常简单,如下所示。

  • In your .babelrc file paste the following:在您的 .babelrc 文件中粘贴以下内容:
{
  "presets": [
    [
      "@babel/preset-env",
      {
        "shippedProposals": true,
        "ignoreBrowserslistConfig": true
      }
    ]
  ]
}


And that is it!就是这样!



If this answer doesn't get Babel working with eslint, to be able to lint private-class-members, or other ECMAS Stage-3 Proposals, Message me or comment below and I will reply guaranteed.如果这个答案没有让 Babel 与 eslint 一起工作,为了能够 lint 私人班级成员,或其他 ECMAS Stage-3 提案,请在下面给我留言或评论,我会保证回复。

Thats all folks!这就是所有人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM