如何使用 Babel 在 JavaScript 类中编写正确的私有方法?

Rar*_*rio 0 javascript node.js babeljs graphql

我正在从 Apollo 服务器做 GraphQL 教程。现在我尝试从这部分添加批处理 - https://www.apollographql.com/docs/apollo-server/features/data-sources/#batching

我知道我可以在 TypeScript 中使用private。但不知道如何在JS中使用。

据我搜索,我安装了两个 babel 插件,class-properties并且private-methods.

// .babelrc

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": "current"
        }
      }
    ]
  ],
  "plugins": [
    ["@babel/plugin-proposal-class-properties", { "loose": true }],
    ["@babel/plugin-proposal-private-methods", { "loose": true }],
    "@babel/plugin-proposal-object-rest-spread",
    "@babel/plugin-proposal-async-generator-functions"
  ]
}
Run Code Online (Sandbox Code Playgroud)

这是代码:

// .babelrc

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": "current"
        }
      }
    ]
  ],
  "plugins": [
    ["@babel/plugin-proposal-class-properties", { "loose": true }],
    ["@babel/plugin-proposal-private-methods", { "loose": true }],
    "@babel/plugin-proposal-object-rest-spread",
    "@babel/plugin-proposal-async-generator-functions"
  ]
}
Run Code Online (Sandbox Code Playgroud)

当我查询单个帖子(findOne)时,它给出错误:

{
  "errors": [
    {
      "message": "Cannot read property 'load' of undefined",
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

此外,eslint 会警告#“无效字符”。

这是我的.eslintrc

// .eslintrc.json

{
  "root": true,
  "parser": "babel-eslint",
  "parserOptions": {
    "sourceType": "module",
    "ecmaVersion": 2018,
    "allowImportExportEverywhere": false,
    "ecmaFeatures": {
      "globalReturn": false
    }
  },
  "plugins": ["babel"],
  "extends": ["eslint:recommended", "prettier"],
  "env": {
    "browser": true,
    "node": true,
    "es6": true,
    "jest": true
  },
  "rules": {},
  "globals": {}
}
Run Code Online (Sandbox Code Playgroud)

请帮忙。

T.J*_*der 5

#字段名称的一部分。所以你需要#在任何使用它的地方使用它:

const post = await this.#postLoader.load(idArg);
// ---------------------^
Run Code Online (Sandbox Code Playgroud)

这是一个使用私有字段(也是私有方法)的简单示例:

class Example {
    #foo = 42;

    publicMethod() {
        console.log("From publicMethod:", this.#foo);
        this.#privateMethod();
    }

    #privateMethod() {
        console.log("From #privateMethod:", this.#foo);
    }
}

const e = new Example();
console.log(e.publicMethod());
Run Code Online (Sandbox Code Playgroud)

生活在 Babel 的 REPL 上


此外,eslint 警告 # 是“无效字符”。

私人领域仍然只是第三阶段的提案,尚未标准化。ESLint 似乎没有支持它们的选项。