uiwjs / react-color

🎨 Is a tiny color picker widget component for React apps.
https://uiwjs.github.io/react-color
MIT License
274 stars 92 forks source link

fix: avoid star exporting react components #140

Closed dangreaves closed 6 months ago

dangreaves commented 6 months ago

Fixes #104.

The CommonJS build is currently broken due to a duplicate export with the name render. Any project which currently imports the CommonJS build will get an Uncaught TypeError: Cannot redefine property: render error.

The reason for this is because all of the sub packages are star exported from the main entrypoint, which results in multiple exports with the name render.

You can confirm this problem by creating the following simple CommonJS file, and seeing the error.

const reactColor = require("@uiw/react-color");
console.log(reactColor);
// Uncaught TypeError: Cannot redefine property: render

When the entrypoint compiles down to CommonJS, it ends up like this. Each of these Object.keys blocks is looping over all the exports from the sub package, and attaching them to exports using Object.defineProperty.

var _reactColorSwatch = _interopRequireWildcard(require("@uiw/react-color-swatch"));
Object.keys(_reactColorSwatch).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
  if (key in exports && exports[key] === _reactColorSwatch[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _reactColorSwatch[key];
    }
  });
});
var _reactColorWheel = _interopRequireWildcard(require("@uiw/react-color-wheel"));
Object.keys(_reactColorWheel).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
  if (key in exports && exports[key] === _reactColorWheel[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _reactColorWheel[key];
    }
  });
});

You cannot use Object.defineProperty to redefine an existing property. So the first block defines a render property on exports, and then subsequent packages try to set the same property, causing the error.

I note that in the documentation, all the React components are imported via their name anyway, so these star exports are not needed, apart from @uiw/color-convert which contains utility functions.

By removing the star exports, we no longer get render directly exported multiple times in the CommonJS file, and the problem is fixed.

jaywcjlove commented 6 months ago

This change may cause TypeScript project errors @dangreaves

It's just faster and more convenient to use typescript type names

jaywcjlove commented 6 months ago

@dangreaves thx!