Search code examples
polymerlit-element

Load ordinary JavaScripts in Polymer 3 elements or lit-elements


I am in the middle of converting a Polymer 2 app to Polymer 3. Modulizer did not work for me so I converted it manually. Thanks to the great upgrade guide it has been mostly straight forward so far.

One task is left though: in my Polymer 2 app I had a special html import (d3-import.html) that brought in the d3.js lib version 3 which comes as a plain JavaScript file (no ES6 module!). This import was dynamically loaded in only two out of overall 20 pages because the other 18 pages did not need it.

In Polymer 3 I can not import it as an ES6 module because it is not a module. Loading it in my main start.html would mean it gets loaded even if the user only uses the other 18 pages that don't need it. I tried writing script-tags in my web component templates but that doesn't seem to work. Unfortunately I don't see any error in the browser tools. The template simply stops to load at the line of the script-tags.

Any idea how to do this?

Additional question: since I start using lit-element in the same application. How to solve the same problem with lit-element?

Edit: note that I currently don't use any build steps/tools except for polymer-build to replace the module paths with actual file paths.


Solution

  • Note that this challenge has nothing to do with Polymer or LitElement, this is only an issue with how to load non-module resources from a module.

    The most straightforward way that I know of is to use a bundler like Rollup that can support CommonJS or UMD. Rollup has the commonjs plugin for this: https://github.com/rollup/plugins/tree/master/packages/commonjs

    The other option is to upgrade to D3 5.x, which appears to be published as standard modules itself. Given the number of files involved, you'll still likely want a bundler to reduce network roundtrips.