javascriptpolymer-3.xgoogle-code-prettify

Google code-prettify Code highlighting not working for Polymer 3


How to use Google code-prettify in Polymer 3?

The syntax highlighting is not working. Sample code below:

class MyView1 extends PolymerElement {
    static get template() {
        return html` 
      <style include="shared-styles">

 </style>

       <script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>

                <pre class="prettyprint">
                    <code class="language-java">
                        public static void getValue(){

                            String name = "Vikram";
                        }




                    </code>
                </pre>

I have added a working sample at https://stackblitz.com/edit/polymer-element-example-d7n14q where the code can be edited and run as well.


Solution

  • This library is working in an old way and doesn't play well with ShadowDom. Instead you should use a library like Highlight.js which is available as a module. In polymer 3 first import the library with your specific language

    import hljs from 'highlight.js/lib/highlight';
    import java from 'highlight.js/lib/languages/java';
    hljs.registerLanguage('java', java);
    

    then highlight your element with

    hljs.highlightBlock(this.$.code);
    

    here a working example : https://stackblitz.com/edit/polymer-element-example-tthbbn