color-js / color.js

Color conversion & manipulation library by the editors of the CSS Color specifications
https://colorjs.io
MIT License
1.93k stars 81 forks source link

Tree-shakable `parse()` doesn't seem to work #248

Closed nym21 closed 2 years ago

nym21 commented 2 years ago

Hiya 👋,

I tried to follow the documentation but I can't make the tree-shakable API work.

The parse function returns the following error:

Uncaught TypeError: Could not parse red as a color. Missing a plugin?

Here's a reproduction code (and it's not ESM, the same code doesn't work in a Vue app with Vite):

<!DOCTYPE html>
<html lang="en">
  <script type="module">
    import { parse } from 'https://esm.run/colorjs.io/fn'

    console.log(parse('red'))
  </script>
</html>
LeaVerou commented 2 years ago

Confirmed I can reproduce this even by importing src/index-fn.js directly: https://codepen.io/leaverou/pen/JjZaPpq?editors=0010

Other observations:

Investigating.

LeaVerou commented 2 years ago

Ah, narrowed it down. The thing is, with the tree-shakable API you need to do everything manually, including registering color spaces you want Color.js to know about:

import { parse, ColorSpace, sRGB } from 'https://colorjs.io/src/index-fn.js';

ColorSpace.register(sRGB);

console.log(parse('red'));

Once you do that, parsing sRGB colors works. Obviously you'd need to do it separately for other color spaces as well.

You can still use an unregistered color space in many places by just passing around its object, but for parsing its formats (or serializing to them) it absolutely needs to be registered.

Perhaps we should include a way to register all color spaces automatically, though do note this would make them non tree-shakable (this was the original design of the tree-shakable API, see #163 ) since you'd have a reference to them whether they are used or not. Basically, once you register a color space, it's not tree-shakable anymore. If you have any ideas about this, they are welcome!

Demo: https://codepen.io/leaverou/pen/MWXqgXX?editors=0010

nym21 commented 2 years ago

Thank you so much for your help !

nym21 commented 2 years ago

To avoid similar future issues, when you'll have the time maybe adding the solution to this page should help ! (It was the page that I used and got confused)

LeaVerou commented 2 years ago

Absolutely.