🏠 back to Observable

Any alternative to eval() ?

Currently I am working on a note book.

it require a module online
ObjectA = require(url)
it also has a attached js file with content like this

When I try to run the js file in the notebook I can only use eval() like this
jsString = FileAttachment("theJS.js").text() with

I have try
import (await FileAttachment("theJS.js").url()) and
new Function(jsString)() and similar method and they all return error of ObjectA is not defined

Wonder if there is any way to do that without using eval()

Mike Bostock does this:-

morph = require(await FileAttachment("nanomorph-5.4.2.js").url())


Its all dependant on how the JS is packed in the file though. If the above does not work send us a link as we don’t have enough context to know.


thx for the reply!
Sorry for not being clear enough for my question
here is a simple page that (I hope) describe the problem I have


Given this is a single line of JS I put it in a notebook cell.

I give the cell a name and reference it before where I need it installed so the reactive runtime executes the riscript installer is called before trying to highlight anything.

Of course, you can import that riscript installer cell from another notebook that uses highlighter. So I think this is a good way of formulating it.

For highlight.js specifically, you might take a look at the approach taken in this notebook:

Basically it uses a trick (due to @mootari) to add the highlighter to Observable’s hljs.

1 Like

The reason why I want to load the attached js file instead of copy and paste the content of it is that the customised hljs model might be updated in the future.
The goal is that when the model is updated I can simply replace the attached file without any more changes of the notebook…

Yeah that’s why I brought up that it can be imported as normal. Put that snippet in its own dedicated notebook and you can maintain that independently to your core notebook.

Copy and pasting that snippet is less work than anything else, and you decouple the maintenance. In a sense, you use a notebook to bundle that snippet, as a notebook IS a module. By pasting the code in a cell, you are bundling the code into a module for ease of consumption in other notebooks.

I see you point…
I think I will go for that for now
Thx a lot!

though still hope that there can be a way of just loading the file

1 Like