harrydehix / simple-units

expandable unit system, providing unit conversion on small and large scale
MIT License
2 stars 2 forks source link

Module requires util polyfill to work in browser #8

Open TimonLukas opened 1 year ago

TimonLukas commented 1 year ago

Hey there! Pretty nifty library, thanks for building and sharing :) earlier I tried to use it in a browser application using Vite. This doesn't work immediately since the module requires the util package, which browsers and their environments do not provide.

By using a Polyfill I was able to work around this, and the result seemed to work fine. Since it seems like the only reason is providing extra info through a symbol, a good solution could be to make it optional, to try and check the environment (though doing so reliably would probably need another package), or (probably best) to handle the exception from the failed import by making it dynamic.

If you can use any help with this, please let me know! Aside from this hiccup I really like the library, well done!

harrydehix commented 1 year ago

Hey, thanks for your feedback. I'm glad you enjoy my library! I'll have a look at this very soon and tell you when the issue is fixed.

harrydehix commented 1 year ago

Hi again, I can't figure out how to exactly fix the bug because I'm not familiar with vite and working with the browser. Some help would be nice🫠!

TimonLukas commented 1 year ago

Hey! Of course, I'd be glad :) I haven't tested this, but if you look at Unit.ts you'll see that you use the import from util only for adding custom inspect information. The util module doesn't exist in the browser context, so this will fail.

A fix would be not to import it and then declare the class, but instead to declare the class, and then attempt importing and adding the symbol. Something like this:

export default class Unit {
    // all your code
}

import("util")
  .then(({ inspect }) => {
    Unit.prototype[inspect.custom] = function (depth: any, options: any) {
      return options.stylize(this.toString(), "special")
    }
  })
  .catch(() => {
    // browser environment
  })