Search code examples
web-workerh3

h3-js in a web worker: document is not defined


I'm trying to use h3-js inside a web worker. The error I get is:

Uncaught ReferenceError: document is not defined
    at libh3-browser.js:6
    at Module../node_modules/h3-js/dist/browser/h3-js.es.js (libh3-browser.js:2)
    at __webpack_require__ (bootstrap:19)
    at Module../src/utils/worker/methods/clusterPins.ts (clusterPins.ts:1)
    at __webpack_require__ (bootstrap:19)
    at Module../src/utils/worker/methods/aggregateAndClusterPins.ts (aggregateAndClusterPins.ts:1)
    at __webpack_require__ (bootstrap:19)
    at Module../src/utils/worker/methods/index.ts (index.ts:1)
    at __webpack_require__ (bootstrap:19)
    at Module../node_modules/babel-loader/lib/index.js?!./node_modules/eslint-loader/dist/cjs.js?!./src/utils/worker/index.ts (index.ts:1)

The only issue I was able to find is on the h3-js github related to a React-native issue, which is not related to mine.

The code looks like this:

import h3 from 'h3-js';
const h3Index = h3.geoToH3(37.3615593, -122.0553238, 7);

Interestingly I'm able to run it inside a node instance with any problems, which makes me unsure if there's something I'm missing.


Solution

  • This is a limitation of the current Emscripten build - we don't actually need document, but there are references to it deep in the Emscripten runtime code. Hopefully we'll be able to remove this in the future. In the meantime, shimming document = {} onto global or this ought to provide a workaround.