Hi there,
I’m trying to create a custom widget with the “Custom widget builder” (CWB). I’d like to use an external library but I cannot find how to do that properly without having the following error : SyntaxError: import declarations may only appear at top level of a module.
For example I’m trying to use the FakerJS library with the following CDN.
Is that possible with the CWB or do I need to host my source code?
Thanks in advance for your help!
Here is a minimal example that should hopefully get you started https://docs.getgrist.com/qABh8z92L9eb/Widget-tester?utm_id=share-doc
<html>
<head>
<script src="https://docs.getgrist.com/grist-plugin-api.js"></script>
</head>
<body>
<div style="font-family: sans-serif; padding: 1em;">
<h2>Custom widget builder</h2>
<p id="email"></p>
</div>
<script type="module">
import { faker } from "https://cdn.jsdelivr.net/npm/@faker-js/faker@10.4.0/+esm";
document.getElementById("email").textContent = faker.internet.email();
</script>
</body>
</html>
Hi @David_Fabijan thanks a lot!
I thought I tried this in my numerous trials but apparently not..
So the only way is to get the JavaScript code in a <script type="module"> below the HTML? No way to get is separated in the JS tab from the Custom Widget Builder?
Actually I’m not really all that good with widget building. But it seems that for the widget builder you do always put the imported library into the html part. Take a look at the ABC widget which is one of the nicer impelemented ones for more insight.
Yes that’s exactly what I’m trying to do but with FakerJS it doesn’t work. I don’t get why with some libraries it works and some it doesn’t.
Because I’ve already succeeded to do that with D3.js for example (with this widget)
Example in Custom Widget Builder that does not work:
HTML
<html>
<head>
<script src="https://docs.getgrist.com/grist-plugin-api.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@faker-js/faker@10.4.0/dist/index.min.js"></script>
</head>
<body>
<div style="font-family: sans-serif; padding: 1em;">
<h2>Custom widget builder</h2>
<p id="email"></p>
</div>
</body>
</html>
JS
grist.ready({ requiredAccess: 'none' });
grist.onRecords(table => {});
grist.onRecord(record => {});
document.getElementById("email").textContent = faker.internet.email();
Result
When I click on “Preview” I get the following errors:
Uncaught SyntaxError: import declarations may only appear at top level of a module index.min.js:7:1
Uncaught ReferenceError: faker is not defined index.html:17:10
May it comes from the way the library is coded?
I’ll be honest I don’t know exactly what’s going on here
But with some AI help I’m coming up with the concept that (this particular version of) faker is ESM-only so you’’re required to use it with the module approach. Older versions of faker (and most other libraries) work with the global approach.