Javascript Function defined in JsFile used by @JavaScript - Annotation is n

Hi,

i have this js file in frontend/js/test.js

function testFunction() {
	console.log("Here i am");
}

My view is doing at class level a

@JavaScript("./js/test.js")

And during startup Webpack tells me

[199]
 ./js/test.js?babel-target=es6 55 bytes {0} [built]

My Code executes a

UI.getCurrent().getPage().executeJs("testFunction()");

But i can’t see the log in the browser’s js console…
Doing a console.log(typeof testFunction) results in undefined

Anyone a glue what’s missing?

Kind regards
Michael

Hi Michael,

Your JavaScript file is embedded as a module. So your function testFunction. is not defined globally ( but in a module scope).

You can define it globally like this:
window.testFunction = function testFunction()…

Hi,

thanks for the information. Will try that.

But i thought using a @JavaScript - Annotation is not to define a function on module basis but to define a “regular” Javascript (think you call it global) function?!

Can you give me a link explaining the differences between global Javascript and Javascript modules?

Kind Regards
Michael

Hi,

Sorry for the late answer. I don’t know if there is something about JavaScript module in vaadin.com. It’s not specific to vaadin. here you have some explanation https://survivejs.com/webpack/what-is-webpack/ or here https://flaviocopes.com/es-modules/

I also do not quite understand myself why @JavaScript annotation doesn’t import functions into global scope, since (according to https://vaadin.com/docs/v14/flow/importing-dependencies/tutorial-importing.html ) it should "import plain .js files. "

I have opened a bug report here, since this topic definitely needs to be clarified, either in the documentation or in @JavaScript class javadoc: https://github.com/vaadin/flow/issues/8285

Hi, I’ve summarized the topic at https://mvysny.github.io/Vaadin-difference-jsmodule-javascript/ - please let me know what you think :slight_smile:

That’s a really good summary :slight_smile: