Search code examples
reactjsecmascript-6es6-module-loader

Scope with ES6 classes and module system


I'm having a problem due to scope/hoisting/load order. In the following the Auth0Lock is defined inside the if block on line 6, but not immediately outside of it, or within the class. Does anyone know why??

import { EventEmitter } from 'events';
import { isTokenExpired } from './jwtHelper';

console.log('in');
const isClient = typeof window !== 'undefined';
if (isClient) {
  let Auth0Lock = require('auth0-lock').default;
  console.log('isClient');
  console.log('Auth0Lock inner', Auth0Lock);
}
  console.log('Auth0Lock outer', Auth0Lock);
export default class AuthService extends EventEmitter {
  constructor(clientId, domain) {
    super();
    console.log('happening');
    if (!isClient) {
      console.log('returning');
      return false;
    }
    // Configure Auth0
    this.lock = new Auth0Lock(clientId, domain, {});
    // Add callback for lock `authenticated` event
    this.lock.on('authenticated', this._doAuthentication.bind(this));
    // Add callback for lock `authorization_error` event
    this.lock.on('authorization_error', this._authorizationError.bind(this));
    // binds login functions to keep this context
    this.login = this.login.bind(this);
  }

 // curtailed
}

Solution

  • The let keyword is block scoped: https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Statements/let

    let x = "hey";
    { let x= "hi"; }
    

    The outer let x is not being overwritten because it is in it's own scope. To come back at your question. Your let Auth0Lock exists only in the if block.