Import js script into Typescript JupyterLab extension

Hello, I’m writing a JupyterLab FrontEnd plugin that must use a specific library.
I’m trying to import a js script made inside my company, so it is not a public library.

Usually, i would import the script this way, but I don’t know how to do it in Typescript:

<body>
...
<script type="text/javascript" src="https://something.com/my-library.min.js"></script> 
</body>

I plan to call the script function every time a notebook is changed, like this:

function changedNotebook(app: JupyterFrontEnd, tracker: INotebookTracker): void {

tracker.currentChanged.connect(() => {
myLibrary.myMethod();

});
}

So, how do I import a static js script in Jupyterlab extension written in typescript? And how do I use it?

If you can have my-library.min.js at build time, creating a .d.ts file can work. your file tree might look like:

- package.json
- tsconfig.json
- src/
  - plugin.ts
  - typings.d.ts
  - my-library.js

typings.d.ts:

declare module './my-library-min.js' {}

Of course, you could keep going, and write some actual typings!

plugin.ts:

import myLibrary from `./my-library-min.js`

tsconfig.json (in addition to what you already have):

{
  "compilerOptions": {
    "allowJS": true
  }
} 

If you can’t have it at build time (e.g. it updates dynamically) you can make a script node, and wait for its onload, like this.

Good luck!

You could also write your lab plugin in JS, and avoid having to create typings. If the library is only available from a URL, you could try to dynamically import your library with

const exports = require('https://yoururl.com');

Thank you for the reply.

I started writing in JS, but most of extensions are written in Typescript, so it would be easier to write in Typescript.

I managed to make it work, using most of @bollwyvl instructions. Some did not work.

inside my src file, I have two files:

  • index.ts
  • script_importer.js

In my index.ts file:

import {prefixScript} from ‘./script_importer’;
.
.
.
function importMyLibraryScript(app: JupyterFrontEnd, tracker: INotebookTracker): void {
prefixScript(“https://something.com/my-library.min.js”,
function() { console.log(“The script has been correctly loaded.”); afterScriptLoad(tracker); });

and in script_importer.js:

function loadError(oError) {
throw new URIError(“The script " + oError.target.src + " didn`t load correctly.”)
}

export function prefixScript(url, onloadFunction){
var newScript = document.createElement(“script”);
newScript.onerror = loadError;
if(onloadFunction) { newScript.onload = onloadFunction;}
document.head.appendChild(newScript);
newScript.type = ‘text/javascript’
newScript.src = url;
}

I tried using a typing, but it was not necessary.

Thank you for your help.