geotiffjs / geotiff.js

geotiff.js is a small library to parse TIFF files for visualization or analysis. It is written in pure JavaScript, and is usable in both the browser and node.js applications.
https://geotiffjs.github.io/
MIT License
845 stars 175 forks source link

Use dynamic imports for non-browser-compatible modules #422

Open IvanSanchez opened 5 months ago

IvanSanchez commented 5 months ago

Bit of background: I'm at the Évora OGC-OSGeo-ASF codesprint, trying to get multiband rasters work with gleo via geotiff.js. I wrote gleo so that it worked as native browser ESM modules, via <script type='module'> and importmap. See e.g. https://gitlab.com/IvanSanchez/gleo/-/blob/master/browser-demos/91-offscreen-indicator.html?ref_type=heads#L19-L40

The problems that turn up when trying to run geotiff.js as native ESM modules are pretty much the sames as https://github.com/geotiffjs/geotiff.js/issues/411 - a file like sources/remote.js unconditionally imports the browser-compatible and the browser-incompatible files (i.e. a file with import from 'fs' or import from 'http' will crash in a browser).

The approach of this fix is to conditionally load those troublesome modules, using dynamic imports. It still works the same, just with a couple more async calls.

See also https://github.com/DanielJDufour/xml-utils/pull/7

constantinius commented 4 months ago

Thanks @IvanSanchez for providing this. This was always a thorn in my side (having to reference modules not available for the browser).

Unfortunately, I'm too far removed from the current state of the art in terms of bundling.

@ahocevar I think you were the one who introduced rollup in the build process. Do you think this change is reasonable?

DanielJDufour commented 4 months ago

@IvanSanchez , I've promoted your changes for xml-utils from a release candidate to a minor release (along with some upgraded dependencies). If you like, you can use v1.8.0 of xml-utils in this PR now: https://github.com/DanielJDufour/xml-utils/releases/tag/v1.8.0