1

Been trying to learn how to create/distribute a npm package, and I've composed my first library that utilizes the ResizeObserver API, which currently has about 89.6% global support at the moment.

I'd like to bundle up a file that includes the resize-observer-polyfill as well apart of the library also, so someone could import it as import <library-name> from "<library-name>/polyfilled";

I've used TSDX to generate the project, and currently am just shipping the index.ts file, along with the index.d.ts type file. Inside the index.ts file, there is a function that uses the resize observer internally.

I'm not sure how to create the setup to handle this, and if it can just be done purely through changing the config to include it (TSDX uses Rollup) or if I need to do something else, like dynamically import the module, but not sure how this would work in terms of the bundle size, and if it would be added to the overall library size.

// index.js
(async () => {
    if (!ResizeObserver in window) {
        const module = await import('resize-observer-polyfill');
        window.ResizeObserver = module.ResizeObserver
    }
}();

// main function exported
export default () => {
    function loadResizeObserver() {
        const ro = new ResizeObserver((entries) => {
            // ...
        })
    }
}

What is the best way to handle adding polyfills to libraries. Or should I just point at the polyfill for the consumer to add if it's needed?

joshuaaron
  • 810
  • 1
  • 15
  • 27

1 Answers1

0

I would suggest to not include the pollyfill in the library as it will increase the size of your package.

Just add the details of what and how pollyfills can be used if required by end user so the devs who need this support (obviously for old browsers) can add it very easily.

Adding by default will increase the size and will result as an unutilized code for those who are focusing on the latest version of browsers.

Rathore
  • 185
  • 8
  • with dynamic import that's not necessarily true, but the biggest issue in here is that the export is synchronous, while the import is asynchronous, meaning code that executes that export won't have ResizeObserver available, in case it was missing. But yeah, I'd left the polyfill outside the library, whenever it's possible, and have a proper dance on top of the HTML, if that's possible. – Andrea Giammarchi Jan 19 '21 at 11:10