[Vaadin 14.2] - JsModule and JQuery

Hello all,

After lot of reading and tests, i’m stucking again…

I just wanna to use on some views a JS libraries. This case is [PrintThis]
(https://jasonday.github.io/printThis/) library … This a JQuery plugin, so need JQuery prior.

I succeed to load JQuery using @NpmPackage and @JsModule, and using a “loader” to define the “jquery” and the “$” variables.
But when i’m loading using @JsModule the print-this plugin, the whole JS crash and nothing work anymore …
→ I also tested to replace loader by a webcomponent config, without success

My tests :

@NpmPackage(value = "jquery", version = "3.5.1")
@NpmPackage(value = "print-this", version = "1.15.1")

@JsModule("jquery/dist/jquery.min.js")
@JsModule("./src/jquery-loader.js")

@JsModule("print-this/printThis.js")

And the loader, pretty simple :

import jQuery from 'jquery';

window.jQuery = jQuery;
window.$ = jQuery;

if (typeof jQuery !== 'undefined') {
    alert("jQuery is loaded in a javascript file");
} else {
    alert("jQuery is not loaded in a javascript file");
}

What’s the hell ?

Thanks for your help.

You can find a tutorial about jquery in flow here
https://vaadin.com/learn/tutorials/integrate-jquery-into-vaadin-flow#_use_jquery_with_a_plugin

The last part should help you, webpack is a little bit tricky with jquery.

Can you try this solution?

That’s excatly the tuto that i followed.

1/ Using NpmPackages and loader.js :

Works when only jquery, but when i add the jquery-plugin, just crash and says that the “$” var is not defined …

1/ Using WebPack :

I modified the webpack.config.js
The WebPack part crash and i don’t know why …

For all of that, i also tried to find examples like [vaadin-tooltip-js]
(https://github.com/jcgueriaud1/vaadin-tooltip-js)

More infos, nothing in the WebPack for these.

1a/ With Jquery only :

@NpmPackage(value = "jquery", version = "3.5.1")

@JsModule("jquery/dist/jquery.min.js")
@JsModule("./src/jquery-loader.js")

@JsModule("./src/test.js")

→ It works !!!

1b/ With Jquery and the plugin :

@NpmPackage(value = "jquery", version = "3.5.1")
@NpmPackage(value = "print-this", version = "1.15.1")

@JsModule("jquery/dist/jquery.min.js")
@JsModule("./src/jquery-loader.js")

@JsModule("print-this/printThis.js")

@JsModule("./src/test.js")

I have this issue :

Uncaught ReferenceError: jQuery is not defined
    at eval (webpack-internal:///../node_modules/print-this/printThis.js:335)
    at Object.../node_modules/print-this/printThis.js (VAADIN/build/vaadin-bundle-8a81f72ee6b5f2446863.cache.js:6606)
    at __webpack_require__ (VAADIN/build/vaadin-bundle-8a81f72ee6b5f2446863.cache.js:20)
    at eval (webpack-internal:///../target/frontend/generated-flow-imports.js:123)
    at Module.../target/frontend/generated-flow-imports.js (VAADIN/build/vaadin-bundle-8a81f72ee6b5f2446863.cache.js:6629)
    at __webpack_require__ (VAADIN/build/vaadin-bundle-8a81f72ee6b5f2446863.cache.js:20)
    at VAADIN/build/vaadin-bundle-8a81f72ee6b5f2446863.cache.js:84
    at VAADIN/build/vaadin-bundle-8a81f72ee6b5f2446863.cache.js:87

My Js Files :

jquery-loader.js :

import jQuery from 'jquery';

window.jQuery = jQuery;
window.$ = jQuery;

test.js :

if (typeof jQuery !== 'undefined') {
    alert("jQuery is loaded in a javascript file");
} else {
    alert("jQuery is not loaded in a javascript file");
}

Thanks for your help, i don’t understand …

Hi,

Sorry for the late answer. I probably forgot to post the solution here.

You can change webpack.config.js:

const merge = require('webpack-merge');
const webpack = require('webpack');
const flowDefaults = require('./webpack.generated.js');

module.exports = merge(flowDefaults, {
    // expose jquery's $ for imports
    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery'
        })
    ]
});

(don’t forget this line const webpack = require('webpack'); perhaps this was your error)

This should remove the error jquery is not defined when you are calling the print library.

@NpmPackage(value = "jquery", version = "3.5.1")
@NpmPackage(value = "print-this", version = "1.15.1")
@JsModule("./src/print-loader.js")
@Route("printthis")
public class PrintThisView extends VerticalLayout {

    public PrintThisView() {
        addClassName("main-layout");
        add(new Span("test"));
        add(new Button("test button", event -> {
            getUI().get().getPage().executeJs("printMainLayout($0)", getElement());
        }));

    }

}

And print-loader.js.

import 'print-this';

window.printMainLayout = function(element) {
    $(element).printThis();
};

If the webpack.config.js change is not working, you can post the error here.

Thanks for the answer !!!

I tried quite excatly that you told, but got a crash in webpack …

Here the stack :

------------------ Starting Frontend compilation. ------------------
2020-06-24 15:57:32 INFO  dev-webpack - Running webpack to compile frontend resources. This may take a moment, please stand by...
2020-06-24 15:57:33 ERROR o.a.c.c.C.[Tomcat]
.[localhost]
.
[/] - Exception sending context initialized event to listener instance of class [com.vaadin.flow.spring.VaadinServletContextInitializer$DevModeServletContextListener]

java.lang.RuntimeException: Unable to initialize Vaadin DevModeHandler
	at com.vaadin.flow.spring.VaadinServletContextInitializer$DevModeServletContextListener.contextInitialized(VaadinServletContextInitializer.java:352)
	at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4676)
	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5139)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
	at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
	at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
	at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
	at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
	at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
	at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
	at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
	at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
	at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
	at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
	at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
	at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:930)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
	at org.apache.catalina.startup.Tomcat.start(Tomcat.java:468)
	at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:123)
	at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.<init>(TomcatWebServer.java:104)
	at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:437)
	at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:191)
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:178)
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:158)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545)
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143)
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758)
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750)
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
	at com.aperam.adriana.AdrianaApplication.main(AdrianaApplication.java:32)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:567)
	at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: javax.servlet.ServletException: java.lang.IllegalStateException: Webpack exited prematurely
	at com.vaadin.flow.server.startup.DevModeInitializer.initDevModeHandler(DevModeInitializer.java:335)
	at com.vaadin.flow.spring.VaadinServletContextInitializer$DevModeServletContextListener.contextInitialized(VaadinServletContextInitializer.java:349)
	... 44 common frames omitted
Caused by: java.lang.IllegalStateException: Webpack exited prematurely
	at com.vaadin.flow.server.DevModeHandler.<init>(DevModeHandler.java:220)
	at com.vaadin.flow.server.DevModeHandler.createInstance(DevModeHandler.java:318)
	at com.vaadin.flow.server.DevModeHandler.start(DevModeHandler.java:268)
	at com.vaadin.flow.server.DevModeHandler.start(DevModeHandler.java:245)
	at com.vaadin.flow.server.startup.DevModeInitializer.initDevModeHandler(DevModeInitializer.java:331)
	... 45 common frames omitted
2020-06-24 15:57:33 ERROR o.a.catalina.core.StandardContext - One or more listeners failed to start. Full details will be found in the appropriate container log file
2020-06-24 15:57:33 WARN  o.a.c.c.C.[Tomcat]
.[localhost]
.
[/] - Cannot deserialize session attribute [com.vaadin.flow.server.VaadinSession.springServlet]
 for session [AE64C32A55E52C146A96AC12B281F894]

2020-06-24 15:57:33 ERROR o.a.catalina.core.StandardContext - Context [] startup failed due to previous errors
2020-06-24 15:57:33 WARN  o.a.c.loader.WebappClassLoaderBase - The web application [ROOT]
 appears to have started a thread named [HikariPool-1 housekeeper]
 but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.base@13.0.1/jdk.internal.misc.Unsafe.park(Native Method)
 java.base@13.0.1/java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:235)
 java.base@13.0.1/java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2123)
 java.base@13.0.1/java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1182)
 java.base@13.0.1/java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:899)
 java.base@13.0.1/java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1054)
 java.base@13.0.1/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1114)
 java.base@13.0.1/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
 java.base@13.0.1/java.lang.Thread.run(Thread.java:830)
2020-06-24 15:57:33 WARN  o.a.c.loader.WebappClassLoaderBase - The web application [ROOT]
 appears to have started a thread named [Thread-332]
 but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.base@13.0.1/sun.nio.ch.Net.accept(Native Method)
 java.base@13.0.1/sun.nio.ch.NioSocketImpl.accept(NioSocketImpl.java:755)
 java.base@13.0.1/java.net.ServerSocket.implAccept(ServerSocket.java:662)
 java.base@13.0.1/java.net.ServerSocket.platformImplAccept(ServerSocket.java:628)
 java.base@13.0.1/java.net.ServerSocket.implAccept(ServerSocket.java:604)
 java.base@13.0.1/java.net.ServerSocket.implAccept(ServerSocket.java:561)
 java.base@13.0.1/java.net.ServerSocket.accept(ServerSocket.java:518)
 app//com.vaadin.flow.server.DevServerWatchDog$WatchDogServer.run(DevServerWatchDog.java:58)
 java.base@13.0.1/java.lang.Thread.run(Thread.java:830)
2020-06-24 15:57:34 INFO  o.a.catalina.core.StandardService - Stopping service [Tomcat]

2020-06-24 15:57:34 WARN  o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
2020-06-24 15:57:34 INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown initiated...
2020-06-24 15:57:34 INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown completed.
2020-06-24 15:57:34 INFO  o.s.b.a.l.ConditionEvaluationReportLoggingListener - 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-06-24 15:57:34 ERROR o.s.boot.SpringApplication - Application run failed
org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:161)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545)
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143)
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758)
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750)
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
	at com.aperam.adriana.AdrianaApplication.main(AdrianaApplication.java:32)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:567)
	at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
	at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:142)
	at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.<init>(TomcatWebServer.java:104)
	at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:437)
	at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:191)
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:178)
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:158)
	... 14 common frames omitted
Caused by: java.lang.IllegalStateException: StandardEngine[Tomcat]
.StandardHost[localhost]
.TomcatEmbeddedContext[] failed to start
	at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.rethrowDeferredStartupExceptions(TomcatWebServer.java:187)
	at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:126)
	... 19 common frames omitted

I think you have this error because spring-dev-tools is trying to restart. Did you try to restart completely the server?

Which version of vaadin are you using?

EDIT: Vaadin 14.2, it’s in the title :slight_smile:

Yeah,

Here my pom head :

	<properties>
		<vaadin.version>14.2.1</vaadin.version>
	</properties>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.1.RELEASE</version>
	</parent>

This is my demo project. I’ve updated the spring boot from 2.2.0 to 2.3.1. I don’t have any errors
18329509.zip (245 KB)

My bad, just missed brackets {...} into webpack.js file …

Works better right now.

Thanks a lot !