Three js and workers (UPDATED)

Hi I am trying to create a fallback for firefox seen as they don’t seem to support
so one option I’ve been reading about is importScripts();

In my worker file I have tried to replace these imports:

import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.124/build/three.module.js';
import {texture_splatter} from './texture-splatter.js' ;
import {math} from '/shared/math.mjs';
import {noise} from '/shared/noise.mjs';
import {terrain_height} from '/shared/terrain-height.mjs' ;

with importScripts('/shared/terrain-height.mjs'); etc etc

but I get this error: SyntaxError: export declarations may only appear at top level of a module three.module.js:51461 from a the lib three.js

I am correct in thinking the above replacing code should work so i can rule that out of being the problem… also if it is three.js has anyone got a solution ?

thanks!

edit:
In my script that loads the worker js I load it like this:

export const terrain_builder_threaded = (function() {

  const _NUM_WORKERS = 4;
  let _IDs = 0;
....



 class WorkerThread {
    constructor(s) {
      this._worker = new Worker(s, {type: 'module'});
      this._worker.onmessage = (e) => {
        this._OnMessage(e);
      };
      this._resolve = null;
      this._id = _IDs++;
    }

    _OnMessage(e) {
      const resolve = this._resolve;
      this._resolve = null;
      resolve(e.data);
    }

    get id() {
      return this._id;
    }

    postMessage(s, resolve) {
      this._resolve = resolve;
      this._worker.postMessage(s);
    }
  }

Later on …

 class _TerrainChunkRebuilder_Threaded {
    constructor(params) {
      this._pool = {};
      this._old = [];

      this._workerPool = new WorkerThreadPool(
          _NUM_WORKERS, 'src/terrain-builder-threaded-worker.js');
  
      this._params = params;
    }

    _OnResult(chunk, msg) {
      if (msg.subject == 'build_chunk_result') {
        chunk.RebuildMeshFromData(msg.data);
        chunk.Show();
      }
    }

Not sure if this way matters or not for firefox… works on chrome atleast

Updated more info !

You can’t use importScripts() to import ES6 modules. That’s why you get the runtime error in three.module.js.

1 Like