Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gatsby build error - window is not defined #657

Closed
4 tasks done
davistran86 opened this issue Sep 29, 2020 · 6 comments · Fixed by #749
Closed
4 tasks done

Gatsby build error - window is not defined #657

davistran86 opened this issue Sep 29, 2020 · 6 comments · Fixed by #749
Assignees
Labels
bug Something isn't working

Comments

@davistran86
Copy link

davistran86 commented Sep 29, 2020

Before you start - checklist

  • I followed instructions in documentation written for my React-PDF version
  • I have checked if this bug is not already reported
  • I have checked if an issue is not listed in Known issues
  • If I have a problem with PDF rendering, I checked if my PDF renders properly in Mozilla Firefox

Description

I just updated react-pdf to version 5.0.0 and got error when using gatsby build to build my project. I have no error when using version 4.2.0

Environment

  • React-PDF version [e.g. 3.0.4]: 5.0.0
  • React version [e.g. 16.3.0]: 16.12.0

Error Log

$ gatsby build
success open and validate gatsby-configs - 0.041s
success load plugins - 1.130s
success onPreInit - 0.005s
success delete html and css files from previous builds - 0.013s
success initialize cache - 0.008s
success copy gatsby files - 0.149s
success onPreBootstrap - 0.022s
success createSchemaCustomization - 0.010s
success source and transform nodes - 1.134s
success building schema - 0.300s
success createPages - 0.388s
success createPagesStatefully - 0.087s
success updating schema - 0.052s
success onPreExtractQueries - 0.003s
success extract queries from components - 0.769s
success write out requires - 0.008s
success write out redirect data - 0.003s
success onPostBootstrap - 0.010s
info bootstrap finished - 7.579s
success Downloading remote files - 0.283s - 15/15 53.03/s
success run static queries - 0.589s - 3/3 5.09/s
success Building production JavaScript and CSS bundles - 11.826s
success Rewriting compilation hashes - 0.008s
success run page queries - 1.487s - 42/42 28.25/s
[============================]   13.962 s 31/31 100% Generating image thumbnails
[                            ]   0.001 s 0/42 0% Building static HTML for pages
(node:21076) UnhandledPromiseRejectionWarning: ReferenceError: window is not defined
    at C:\work\aavn-portal-workspace\packages\client\public\render-page.js:19640:3
    at new Promise (<anonymous>)
    at Object.../../node_modules/pdfjs-dist/lib/web/ui_utils.js (C:\work\aavn-portal-workspace\packages\client\public\render-page.js:19639:26)
    at __webpack_require__ (C:\work\aavn-portal-workspace\packages\client\public\render-page.js:30:30)
    at Object.../../node_modules/pdfjs-dist/lib/web/pdf_link_service.js (C:\work\aavn-portal-workspace\packages\client\public\render-page.js:18639:17)
    at __webpack_require__ (C:\work\aavn-portal-workspace\packages\client\public\render-page.js:30:30)
    at Module.../../node_modules/react-pdf/dist/esm/LinkService.js (C:\work\aavn-portal-workspace\packages\client\public\render-page.js:22670:93)
    at __webpack_require__ (C:\work\aavn-portal-workspace\packages\client\public\render-page.js:30:30)
    at Module.../../node_modules/react-pdf/dist/esm/Document.js (C:\work\aavn-portal-workspace\packages\client\public\render-page.js:22109:71)
    at __webpack_require__ (C:\work\aavn-portal-workspace\packages\client\public\render-page.js:30:30)
    at Module.../../node_modules/react-pdf/dist/esm/entry.js (C:\work\aavn-portal-workspace\packages\client\public\render-page.js:25120:67)
    at __webpack_require__ (C:\work\aavn-portal-workspace\packages\client\public\render-page.js:30:30)
    at Module../src/components/ReaderPage/PDFReader/index.js (C:\work\aavn-portal-workspace\packages\client\public\render-page.js:29742:67)
    at __webpack_require__ (C:\work\aavn-portal-workspace\packages\client\public\render-page.js:30:30)
    at Module../src/components/ReaderPage/index.js (C:\work\aavn-portal-workspace\packages\client\public\render-page.js:29764:68)
    at __webpack_require__ (C:\work\aavn-portal-workspace\packages\client\public\render-page.js:30:30)
(node:21076) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To tesuccess Building static HTML for pages - 2.369s - 42/42 17.73/s
success Generating image thumbnails - 16.344s - 31/31 1.90/s
success onPostBuild - 0.009s
info Done building in 24.2845958 sec
Done in 24.55s.
Done in 24.86s.
@rootlinux2
Copy link

rootlinux2 commented Oct 9, 2020

Hi @davistran86 I had this error, I try using a state and useEffect

const [isClient, setIsClient] = useState(false);
...
useEffect(() => { setIsClient(true); }, []);
...
return ( isClient && ( <The Component here />));

I also tray

if (typeof window !== 'undefined' && typeof document !== 'undefined')

But the error persists only on build for production in development I have no error.

@gshilin
Copy link

gshilin commented Oct 16, 2020

It happens also without Gatsby when running SSR on nodejs:

(node:16012) UnhandledPromiseRejectionWarning: ReferenceError: window is not defined
    at node_modules/pdfjs-dist/lib/web/ui_utils.js:564:3
    at new Promise (<anonymous>)
    at Object.<anonymous> (node_modules/pdfjs-dist/lib/web/ui_utils.js:563:26)
    at Module._compile (internal/modules/cjs/loader.js:1118:30)
    at Module._compile (node_modules/pirates/lib/index.js:99:24)
    at Module._extensions..js (internal/modules/cjs/loader.js:1138:10)
    at Object.newLoader [as .js] (node_modules/pirates/lib/index.js:104:7)
    at Module.load (internal/modules/cjs/loader.js:982:32)
    at Function.Module._load (internal/modules/cjs/loader.js:875:14)
    at Module.require (internal/modules/cjs/loader.js:1022:19)

@wojtekmaj
Copy link
Owner

Go to node_modules/react-pdf/dist/{esm|umd}/eventBus.js (pick esm or umd, depending on the build you're using - hopefully esm) and replace its contents with the following:

function dispatchDOMEvent(eventName, args = null) {
  const details = Object.create(null);

  if (args && args.length > 0) {
    const obj = args[0];

    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        continue;
      }

      const value = obj[key];

      if (key === 'source') {
        if (value === window || value === document) {
          return;
        }

        continue;
      }

      details[key] = value;
    }
  }

  const event = document.createEvent('CustomEvent');
  event.initCustomEvent(eventName, true, true, details);
  document.dispatchEvent(event);
}

export default class EventBus {
  constructor({
    dispatchToDOM = false,
  } = {}) {
    this._listeners = Object.create(null);
    this._dispatchToDOM = dispatchToDOM === true;

    if (dispatchToDOM) {
      console.error('The `eventBusDispatchToDOM` option/preference is deprecated, add event listeners to the EventBus instance rather than the DOM.');
    }
  }

  on(eventName, listener) {
    this._on(eventName, listener, {
      external: true,
    });
  }

  off(eventName, listener) {
    this._off(eventName, listener);
  }

  dispatch(eventName, ...args) {
    const eventListeners = this._listeners[eventName];

    if (!eventListeners || eventListeners.length === 0) {
      if (this._dispatchToDOM) {
        dispatchDOMEvent(eventName, args);
      }

      return;
    }

    let externalListeners;
    eventListeners.slice(0).forEach(({
      listener,
      external,
    }) => {
      if (external) {
        if (!externalListeners) {
          externalListeners = [];
        }

        externalListeners.push(listener);
        return;
      }

      listener(...args);
    });

    if (externalListeners) {
      externalListeners.forEach(listener => listener(...args));
      externalListeners = null;
    }

    if (this._dispatchToDOM) {
      dispatchDOMEvent(eventName, args);
    }
  }

  _on(eventName, listener, options = {}) {
    let eventListeners = this._listeners[eventName];

    if (!eventListeners) {
      eventListeners = [];
      this._listeners[eventName] = eventListeners;
    }

    eventListeners.push({
      listener,
      external: options.external === true,
    });
  }

  _off(eventName, listener) {
    const eventListeners = this._listeners[eventName];

    if (!eventListeners) {
      return;
    }

    for (let i = 0, ii = eventListeners.length; i < ii; i += 1) {
      if (eventListeners[i].listener === listener) {
        eventListeners.splice(i, 1);
        return;
      }
    }
  }
}

If that won't explode, we can consider replacing Mozilla's eventBus with this custom one, making us independent from ui_utils, which should fix the problem.

@wojtekmaj wojtekmaj self-assigned this Nov 5, 2020
@wojtekmaj wojtekmaj added the enhancement New feature or request label Nov 5, 2020
@hc-12
Copy link

hc-12 commented Dec 2, 2020

I'm currently experiencing the same issue with v5.

The error occurs at line 563 in ui_utils.js. Changing mozilla's file confirmed the fix.

const animationStarted = new Promise(function (resolve) {
  window.requestAnimationFrame(resolve);
});

to:

const animationStarted = new Promise(function (resolve) {
  if (typeof window === 'undefined') {
    return resolve();
  }

  window.requestAnimationFrame(resolve);
});

@wojtekmaj
Copy link
Owner

wojtekmaj commented Dec 3, 2020

My suggestion would be to:

  • try my workaround

  • use yarn patch to fix Mozilla's code for now,

  • raise an issue in their repository - looks like all it needs is

    const animationStarted = new Promise(function (resolve) {
      if (
        typeof PDFJSDev !== "undefined" &&
    -    PDFJSDev.test("LIB && TESTING") &&
    +    PDFJSDev.test("LIB && TESTING") ||
        typeof window === "undefined"
      ) {
        // Prevent "ReferenceError: window is not defined" errors when running the
        // unit-tests in Node.js/Travis.
        setTimeout(resolve, 20);
        return;
      }
      window.requestAnimationFrame(resolve);
    });

@wojtekmaj wojtekmaj added bug Something isn't working and removed enhancement New feature or request labels Mar 15, 2021
@wojtekmaj wojtekmaj changed the title Version 5.0.0 has error with Gatsby build - window is not defined Gatsby build error - window is not defined Mar 15, 2021
@wojtekmaj wojtekmaj pinned this issue Mar 15, 2021
@wojtekmaj
Copy link
Owner

All,
please kindly help me with testing the fix for this issue.
➡️ #748

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants