Using Import to load a js library in a custom component

I am trying to load a library into a JS custom component. All of the code sample for using the the libary say I need to import it first

import { jsPDF } from "jspdf";

But I am getting an error trying to: Cannot use import statement outside a module

If I don't do the import and just try and instantiate directly: var pdf = new jsPDF('p', 'pt', 'a4'); I get the following error: jsPDF is not a constructor

There are es6, umd and node version of the distributable, but all have the same result.

Any idea how I get this library working?

Try loading the UMD script from a CDN in your retool app and then access it with window.jspdf in your custom component

var { jsPDF } = window.jspdf;
var pdf = new jsPDF();
2 Likes

To solve the error, set the type attribute to module when loading the script in your HTML code. When working with ECMAScript modules and JavaScript module import statements in the browser, you'll need to explicitly tell the browser that a script is module. To do this, you have to add type="module" onto any ‹script› tags that point to a JavaScript module. Once you do this you can import that module without issues.

<script type="module" src="./index.js"></script>

If you are working on Node.js or react applications and using import statements instead of require to load the modules, then ensure your package.json has a property "type": "module" as shown below.

{
  // ...
  "type": "module",
  // ...
}

Moreover, In some cases, you may have to use both import and require statements to load the module properly.

// import { parse } from 'node-html-parser';
parse = require('node-html-parser');

This error "Cannot use import statement outside a module " can happen in different cases depending on whether you're working with JavaScript on the server-side with Node.js , or client-side in the browser. There are several reasons behind this error, and the solution depends on how you call the module or script tag.

2 Likes