1

I have a program with a fallback for browsers that do not support web workers. The reason I'm doing this is because I want to deploy it to cocoon's canvas+, which does not support web workers. The non web worker code can access the script 'mountainNoise.js' fine, since it uses ES6 import and export, however when the worker imports the script via "importScripts()" it throws an error since export declarations can only appear in modules.

Is there a way to detect if the code is running in a module? My main concern is duplicating the file to support both versions, but this is ridiculous since it's taking much more memory for one line of code.

Legomite
  • 99
  • 2
  • 7
  • seems like workers [don't support modules yet](https://github.com/audreyt/node-webworker-threads/issues/15). as far as detecting, i would detect the error instead of modularity, so try/catch, which will handle new problems with modularity as well. – dandavis Oct 16 '18 at 20:20

2 Answers2

0

The thing is that this is ground to language semantics and duplication can Be the answer. I can suggest try catch. I know its not a good solution but maybe better than duplication.

  • Try and catch does not work. The error still stops script execution when try is executed with the export keyword is present, it stops everything :( – Legomite Oct 16 '18 at 22:29
0

I'm not will sure if this will work in a web worker, but it's a common pattern in js libraries that want to support both node.js and browsers.

if (
  typeof module !== 'undefined' &&
  typeof module.exports !== 'undefined'
) {
  module.exports = MyLib
  console.log('module.exports exists, import/export should be supported')
} else {
  window.MyLib = MyLib
  console.log('in a browser')
}
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337