eleventy-plugin-bundle icon indicating copy to clipboard operation
eleventy-plugin-bundle copied to clipboard

Bundling javascript modules

Open bennypowers opened this issue 2 years ago • 0 comments

ab.webc:

<script type="module">
import { LitElement } from 'lit';
customElements.define('a-b', class extends LitElement {});
</script>

cd.webc:

<script type="module">
import { LitElement } from 'lit';
customElements.define('c-d', class extends LitElement {});
</script>

index.webc:

<script type="module" :src="getBundleFileUrl('js')" webc:keep></script>

Uncaught SyntaxError: redeclaration of import LitElement3k1axR86sr.js:3:9note: Previously declared at line 1, column 9

One way to fix this would be to add an async callback to the bundles option which provides an api to collect sources and write outputs, or to do so in the transforms option.

eleventyConfig.addPlugin(bundlerPlugin, {
  transforms: [
    async function(content, collect) {
          // this.type returns the bundle name.
      if (this.type === 'js' &&
          // proposal: this.attributes exposes the source element's attributes
          this.attributes.type === 'module') {
        collect(this, content);
        return false; // don't bundle, instead hold the item in memory
      }
    },
    async function(content) {
      if (this.type == bundlerPlugin.collection) { // a Symbol()
        const { build } = await import('esbuild');
        const result = await build({
          bundle: true,
          /* ... collected has source strings and metadata, etc */
          entryPoints: writeToTmpAndMakeEntryPointsConfig(collected),
        });
        const [{ path, contents }] = result.outputFiles;
        return {
           url: path,
           content: contents,
        }
      }
    }
  ],
});

above APIs are proposals for discussion only, salt to taste.

bennypowers avatar Jun 05 '23 05:06 bennypowers