Working with imports from other JS files

I was trying to be DRY so I decided to use an imported function in obj.CustomJS but had been defeated by bokeh itself…

Example import file:

    function hello() {
        return 'hello';

I then add the script as a module in the html and so, in my CustomJS I first tried import { hello } from './my_file.js'; but I got:
Uncaught SyntaxError: import declarations may only appear at top level of a module

So I thought I’ll use jQuery.getScript but I was greeted with:
Uncaught TypeError: $.getScript is not a function

… which I tried to resolve but did not prevail…

Am I doing something wrong or maybe did I actually found a :bug: ?

I have found that i made a mistake in import by not importing module, but the correct import also generates the same error

CustomJS creates a closure (an anonymous function) for executing the provided code, so there is no way to use regular imports in such context (regular imports can be used only at the top-level of a module, as the error indicates). However, you can try using dynamic imports, e.g. like this:

(async () => {
  const my_module = await import('/modules/my-module.js');

(or use promise API instead of this).

1 Like

Thanks for the advice @mateusz - this worked like a charm in my case!