SidneyNemzer / snippets

A Chrome extension that allows you to create and edit JavaScript code snippets, which are synced to all your computers
https://chrome.google.com/webstore/detail/snippets/fakjeijchchmicjllnabpdkclfkpbiag
63 stars 9 forks source link

Support for ESM Syntax #27

Open gingerchew opened 3 years ago

gingerchew commented 3 years ago

I don't know what the limitations are, but it would be nice to be able to use import and export syntax inside of the snippets. Getting to use SkyPack inside of a snippet or snippet imports, like this.

// Without knowing all that much about Chrome Extensions or Github Gist API
// I was thinking of things like these 2, but these seem *impossible* or *incredibly hard*

// I'm assuming this is the least likely or hardest to implement
import snippetGist from SnippetsExtension.snippetName;
// This is probably the weirdest / dumbest
import snippetGist from '$snippetName';

// Getting just the standard ESM working with URLs would be ideal.
import gistFunction from 'https://gist.githubusercontent.com/${user}/{blah}/raw/{blah}/snippetName.js'
SidneyNemzer commented 3 years ago

That's a great idea, it would be really handy to be able to use ESM.

Regarding the first two, I'm not aware of any mechanism that would allow resolving those imports. However if we get the third one working, a bit of string replacement might work well enough...

As far as standard ESM, Chrome doesn't let extensions directly execute "module" scripts, but I have an idea:

Instead of using chrome.devtools.inspectedWindow.eval to directly run the code, it should be possible to eval a script like:

const s = document.createElement("script")
s.setAttribute("type", "module")
s.innerText = snippetContent
document.body.appendChild(s)

After some quick testing, it seems to work!

However there are a few limitations:

Feel free to take a stab at this if you're interested. Otherwise I'll try it when I get around to it.

gingerchew commented 3 years ago

Yeah the first two were long shots for sure!

My laptop is in the shop right now, but I'll take a crack at it once I get it back 😊

gingerchew commented 3 years ago

I haven't been able to get any actual coding started with this, work has been swamped, but I figured I'd share the resources I've found so far.

Maybe this will be useful to someone else who comes along and wants to give it a shot too.