vuejs/vue-web-component-wrapper

Best way to load polyfills automatically

serbemas opened this issue · 0 comments

I'm currently working on a project that creates a web component using the Vue Web Component Wrapper library.

I execute this command to generate the web component library:

vue-cli-service build --target wc --name widget ./src/components/widget.vue

At this point, I have compiled the web component and the next step is to load the polyfills to add compatiblity with the old browsers versions.

To avoid load manually the polyfills in each website where the component is used, I have been thinking about to create a 'loader.js' script inside this project to load automatically the polyfills.

So with this aproach, the final user only has to reference the 'loader.js' script and it will check the browser compatibility and load the required files.

An example of loader will be something like this: (I haven't tested it)

function loadScript(src) {
  const script = document.createElement('script');
  script.async = true;
  script.rel = 'preload';
  script.src = src;
  document.head.appendChild(script);
}

if (!('customElements' in window)) {
  loadScript('dist/webcomponents-bundle.js');
}

if (!HTMLElement.prototype.attachShadow) {
  loadScript('dist/shadydom.min.js');
}

loadScript('dist/widget.min.js');

With this code, I need to have inside the dist folder the 'loader.js' script and the polyfills, to be able to serve that files when user loads the script.

How should I create this loader inside the vue cli project?

To generate it when the componet is compiled, I've tried to use the copy-webpack-plugin to copy all the files inside dist. But with this solution I'm not able to use the environment variables inside the script for example.

configureWebpack: {
    plugins: [
      new CopyWebpackPlugin(
        [
          {
            from: 'src/loader.js',
            to: '.',
          },
          {
            from: './node_modules/@webcomponents/webcomponentsjs/webcomponents-bundle.js',
            to: './loader',
          },
          {
            from: './node_modules/@webcomponents/shadydom/shadydom.min.js',
            to: './loader',
          },
        ],
      ),
    ],
  },

What is the best way to achieve this?

Regards