I’m generating some JavaScript code dynamically with string manipulations and then use eval
to parse it to functions. I’d like to show the generated code in a cell (the “result” of a cell, to be specific). Do you know of any way to achieve this?
I tried with js-beautify but was unable to import it properly, as it requires three different scripts to be loaded.
Could there be some way to utilize the functionality in Observable’s own CodeMirror code editor from within a cell?
Meanwhile, I’ll include indentation and linebreaks as I generate the code.
Hi mast4461, and welcome to the forum! Could you elaborate on what failed about js-beautify? I think I got it working, at least in some basic capacity.
When modules fail to import properly, you can try our handy Module Require Debugger, which tries a bunch of different import patterns to see what seems to work. I’ve found it pretty effective.
In the case of js-beautify, it recommends this:
beautify = require('https://bundle.run/js-beautify@1.13.5')
Which you can use like:
beautify("2+2"); // returns `2 + 2`
As seen here.
I’m more familiar with Prettier, so I also did a longer example with that.
1 Like