错误 运行 示例代码 - Class 在导出的 class - Auth0 with React Node.js

Errors running sample code - Class within an exported class - Auth0 with React Node.js

我正在尝试 运行 用于创建身份验证的教程代码服务到我的 React 项目中。

这是他们希望我使用的代码示例 运行:

// src/Auth/Auth.js

import auth0 from 'auth0-js';

export default class Auth {
  auth0 = new auth0.WebAuth({
    domain:'domain.auth0.com',
    clientID: 'clientId',
    redirectUri: 'http://localhost:3000/callback',
    audience: 'https://myproject.auth0.com/userinfo',
    responseType: 'token id_token',
    scope: 'openid'
  });

  login() {
    this.auth0.authorize();
  }
}

当我 运行 它时,它会抛出有关 'import' 和 export' 关键字的错误。 所以我把它改成这样:

const auth0 = require("auth0-js");

class Auth {
    auth = new auth0.WebAuth({
        domain: 'mydomain.auth0.com',
        clientID: 'clientID',
        redirectUri: 'http://localhost:3000/callback',
        audience: 'https://myproject.auth0.com/userinfo',
        responseType: 'token id_token',
        scope: 'openid'
  });

  login() {
    this.auth.authorize();
  }
}

module.exports = Auth;

但这给了我这个错误:

/Users/myname/my project/app/services/auth.js:4
    auth = new auth0.WebAuth({
         ^


SyntaxError: Unexpected token =
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:616:28)

正确的语法是什么?

instance class fields are only supported in node >= 10 using --harmony flag.

您可以使用 getter 代替,它在没有任何标记的情况下也受支持。

class Auth {

    get auth() {
        if(!this._auth) {
            this._auth = new auth0.WebAuth({ /* ... */ });
        }

        return this._auth;
    }

    login() {
        this.auth.authorize();
    }
}

或者将其设置在 constructor

class Auth {

    constructor() {

        this.auth = new Auth0.WebAuth({ /* ... */ });
    }
}

或者您可以使用 babel 转译您的代码。