I’m unable to import/use 3rd party Javascript in a Vaadin 14 application. For example starting with the “Starter” app I tried to get highlight.js working by adding the following to the MainView.
@NpmPackage(value = "highlight.js", version = "9.15.10") @JsModule(value="highlight.js/lib/index.js", loadMode = LoadMode.EAGER) @CssImport(value="highlight.js/styles/darcula.css")
I also imported the package using npm import highlight.js --save (just in case).
When I build I can see that highlight.js has been included in the webpack and everything builds w/o errors however the module is not available from my app. For example if I try to reference the hljs variable I get an error (ReferenceError) : hljs is not defined and I can’t see any of the hljs declarations available in the JS console.
I also tried using a simple local Javascript function, so I added test.js to <project>/frontend/src as: function test() { console.log("Hello, World!"); }
And then added @JavaScript(value="./src/test.js") to the MainView.java. Again everything builds fine but this function isn’t added to my page.
It’s obivious I’m doing something simple wrong but I can’t see it and I need to progress this before I can migrate our App to Vaadin 14.
The library is imported as a javascript module, so it’s not available globally.
Instead of doing this: @JsModule(value=“highlight.js/lib/index.js”, loadMode = LoadMode.EAGER), you can load it in your javascript file (for example highlight-loader.js) and use it inside:
import hljs from 'highlight.js';
// hljs is available, you can use it in your file
hljs.registerLanguage('javascript', javascript);
// OR If you want hljs available in your 'page'
window.hljs = hljs;
And add in your Java file (you still need @NpmPackage) @JsModule("highlight-loader.js")