duetds / date-picker

Duet Date Picker is an open source version of Duet Design System’s accessible date picker. Try live example at https://duetds.github.io/date-picker/
https://www.duetds.com
MIT License
1.73k stars 68 forks source link

How to include (but not bundle) in a published library #85

Closed tamlyn closed 3 years ago

tamlyn commented 3 years ago

I have a package of Vue components published to npm that has @duetds/date-picker as a dependency. It works fine when using my library as commonjs via webpack, but I'd like to also publish a UMD version for use directly in browsers.

I define my externals in webpack as follows but I get an error when it cannot find defineCustomElements:

    externals: {
      lodash: {
        root: '_',
        commonjs: 'lodash',
        commonjs2: 'lodash'
      },
      '@duetds/date-picker/dist/loader': {
        root: 'duet-date-picker', // <-- what should this be?
        commonjs: '@duetds/date-picker/dist/loader',
        commonjs2: '@duetds/date-picker/dist/loader'
      },
      ...
    }

I understand that in browserland I don't need to call defineCustomElements – just including the script tag should be enough – but my code still breaks because it expects the function to exist.

I can get it working by putting a shim in the page before loading my library but it feels like this is not the correct way:

<script>
  window['duet-date-picker'] = { defineCustomElements: () => {} }
</script>

Here's a full working example.

Is there a best practice for this?

WickyNilliams commented 3 years ago

I guess the issue here is that we don't have a umd build that exposes defineCustomElements on the window. We have a build for bundlers, and a build for script tag use. But that script tag build is side effectful, it doesn't expose any functions, it eagerly registers the component itself.

I don't think Stencil supports creating that kind of UMD build. I could create a separate webpack build step that bundles it all into a umd format, but I don't really want to add additional complexity.

I would suggest simply not externalising the picker! Or you might be able to fudge something by using a script with type="module" and importing the ES build of the picker. But I'd go with simply bundling it. Lodash etc it makes sense to externalise since it may be included elsewhere on the page already. But the chances of the same being true for the picker are very slim

Sorry I can't help more!