1

I want to import a module for one of my .js files and call my .js file with Vaadin 14. Unfortunately I struggle with importing it and a ReferenceError is thrown in the browser.

My view:

@Route(value = "jstest", layout = MainView.class)
@PageTitle("jstest")
@JsModule("./sipcall.js")
@NpmPackage(value = "sip.js", version = "0.15.10")
public class SipJsTest extends Div {
    private Button b;
    public SipJsTest() {
        b = new Button();
        b.setText("Execute SIP.js");
        b.addClickListener(listener -> {
            Page page = UI.getCurrent().getPage();
            page.executeJs("executesipcall()");
        });
        add(b);
    }
}

sipcall.js (the module is named this way) is located in frontend/sipcall.js/. If I do a simple console output the function is called correctly. The error appears if I try to use the imported module.

sipcall.js:

import "sip.js";

window.executesipcall = function() {
    var ua = new SIP.UA(...) // from the imported module, throws exception
}

node_modules/sip.js/ contains the module that I imported with @NpmPackage. The module is also listed in package.json with "sip.js": "0.15.10".

Webconsole error:

client-4FB121A4CC0177A1068809F06428A755.cache.js:57 Uncaught ReferenceError: SIP is not defined at window.executesipcall (vaadin-bundle-6b322b28264dafdccb46.cache.js:4505) at Object.eval (eval at St (client-4FB121A4CC0177A1068809F06428A755.cache.js:991), :1:1)

Any ideas why Vaadin does not recognize the import? Is it because it is not imported in global scope (mentioned here)?

Michael Kemmerzell
  • 4,802
  • 4
  • 27
  • 43
  • I'm not too confident in what I'm saying, but are you sure the npmPackage path is correct? the actual sip.js file should be in some kind of subfolder within node_modules, no? For example, Vaadins Button class has the annotation `@NpmPackage( value = "@vaadin/vaadin-button", version = "2.2.2" )` --> they don't even specify a single .js file – kscherrer Mar 06 '20 at 07:47
  • 1
    Yes, the module is in a subfolder in node_modules/sip.js/ – Michael Kemmerzell Mar 06 '20 at 07:50
  • Yes, the folder name contains the .js ending. The npm package is called this way I think: https://sipjs.com/download/ – Michael Kemmerzell Mar 06 '20 at 07:52
  • 1
    Is your sip.js and sipcall.js in the same folder, as you seem to have 'import "sip.js";', which may be failing part and hence 'var ua = new SIP.UA(...)' fails as it was not imported. – Tatu Lund Mar 06 '20 at 08:24
  • @TatuLund I found a solution by using require() to import the module – Michael Kemmerzell Mar 06 '20 at 08:29

1 Answers1

0

I found a solution. I had to use NodeJs' require() to import the module instead of import. It works but I am not sure why.

sipcall.js:

window.executesipcall = function() {
    var sip = require("sip.js");
    var ua = new sip.UA(...)
}

What is require()?

Michael Kemmerzell
  • 4,802
  • 4
  • 27
  • 43