Search code examples
polymerpolymer-3.x

How to import external JavaScript into Polymer 3.0


Let's say I have a traditional javascript library such as google-charts and I wanted to incorporate that into my Polymer 3.0 project. How would I actually do the import?

This is how I would traditionally do it: https://developers.google.com/chart/interactive/docs/quick_start


Solution

  • ES Modules on NPM

    Normally, one would prefer an ES module version of such a library if available (e.g., on NPM), since ES modules allow tree shaking (by Polymer CLI in this case) to reduce the size of the production build output.

    Modules are loaded in JavaScript with the import keyword. If available on NPM, the library could be installed in your Polymer project with the npm-install command. For instance, you'd install google-charts like this:

    npm install --save google-charts
    

    Then, import that package in your element code:

    import { GoogleCharts } from 'google-charts';
    

    Example:

    import { PolymerElement } from '@polymer/polymer';
    import { GoogleCharts } from 'google-charts';
    
    class MyElement extends PolymerElement {
      // ...
    
      ready() {
        super.ready();
        GoogleCharts.load(/* ... */);
      }
    }
    

    demo

    Non-ES Modules (not on NPM)

    On the other hand if ESM is unavailable, the script is likely an AMD/UMD module, which adds symbols to the global scope. In that case, you'd still import the file, and access the global as you normally would had you used the <script> tag.

    If the script is not on NPM, you'd have to copy the file locally into your project (and include the library file in your release), and then import the file by path. For example, if you copied the library to <root>/src/libs/google-charts.js, the element code at <root>/src/components/Chart.html would import it like this:

    import '../libs/google-charts'
    

    Example:

    import { PolymerElement } from '@polymer/polymer';
    import '../libs/google-charts' // adds GoogleCharts to global
    
    class MyElement extends PolymerElement {
      // ...
    
      ready() {
        super.ready();
        GoogleCharts.load(/* ... */);
      }
    }