Qix- / color-convert

Plain color conversion functions in JavaScript
MIT License
746 stars 96 forks source link

feat: allow conversions to be individually imported/tree-shakable #94

Closed Ignigena closed 3 years ago

Ignigena commented 3 years ago

We are utilizing color-convert for a small number of conversions on the frontend and can't take advantage of tree shaking in Webpack to only bundle the conversions we need. This results in a much larger bundle size than we would otherwise need.

This PR is a step towards modularizing the imports and exports, per #57 but with a focus on retaining backwards compatibility. To this end, CJS is still being used rather than switching completely over to UMD just yet. The biggest thing missing here is the mapping for non-direct conversions which in the meantime may not be fully tree-shakable. Considering this will likely need a build step (unless the steps are just mapped explicitly) it seemed to make sense to tackle that separately alongside a UMD conversion, potentially also utilizing Rollup or another bundler for publishing.

The main focus here was just to split the direct conversion functions into individual exports for better tree shaking. For use cases that simply require one or two direct conversion functions, these can be imported individually with dedicated entry points resulting in a much smaller bundle size, ex:

// only need a single direct conversion?
const hexToRgb = require('color-convert/conversions/hex/rgb')
hexToRgb('#315084')

// making several direct conversions?
const { rgb, hex } = require('color-convert/conversions')
hex.rgb('#315084')
rgb.hex([49, 80, 132])

// existing interface unchanged
const convert = require('color-convert')
convert.hex.rgb('#315084')

For now, this means tree-shaking can be opt-in by importing color-convert/conversions or deeper. While the existing main color-convert import is unchanged but also not fully shakable. Otherwise, all of the direct conversion functions themselves are unchanged -- just split up from a single giant conversions.js into a conversions/ directory with dedicated entry paths and a structure conducive to selective imports.

jimmywarting commented 3 years ago

Think u should Require Node.js 12.20.0 and move to ESM for better cross Deno/Browser imports

Qix- commented 3 years ago

Yes that's probably what's going to happen. I'm not a fan of the approach here but it's an interesting approach nonetheless :)