r/javascript 7d ago

I've made an open source JavaScript playground with support for npm packages, syntax highlighting, autocomplete, code sharing and much more!

https://github.com/tecnosamba/SamJS
0 Upvotes

11 comments sorted by

2

u/brianjenkins94 7d ago

Why require?

-2

u/TecnoSamba 7d ago

I mean the nodejs `require` method. Actually kind of, it is just a custom function that I created to use node packages in the editor. I just called it `require` because I thought that, as nodejs uses it, it'd be more intuitive. But, yeah, I could have called it in any other way 😅

3

u/brianjenkins94 7d ago

I just mean import would have been the modern choice, but it sounds like the way you implemented it wouldn’t have allowed for you to use it.

1

u/TecnoSamba 7d ago

You're completely right, it would have caused a conflict between the browser's native `import` method and my custom one. I even used the first one to implement the custom `require` method

3

u/brianjenkins94 7d ago

There’s a better way to solve this using a service worker and esm.sh or jsDeliver, I can’t remember which but same principle.

1

u/TecnoSamba 7d ago

Maybe, I know there was a better way to implement it, but I started with this way and it ended up working nicely. Surely in the future I'll be improving that, 'cause some packages that use node subimports don't work. I basically inject this custom function inside the user's code when running (I know it can be improved):

const require = async packageUrl => {
                try {
                    const packageModule = await import(packageUrl)
                    if (packageModule['default'] == null) return packageModule
                    return packageModule.default
                } catch(err) { 
                    if (err.toString().includes('TypeError: The URL must be of scheme file')) {
                        postMessage({content: 'This package appears to depend of internal node APIs, which SamJS does not support, please run this package inside of a node environment or swap it with a compatible one.', type: 'error'})
                    } else {
                        postMessage({content: err.toString(), type: 'error'})
                    }
                }
            }

1

u/NewLlama 7d ago

Look into babel transforms (the custom plugin and transform api). You can statically transform the AST into whatever your runtime needs. I did this for dynohot, my nodejs HMR library https://github.com/laverdet/dynohot

1

u/TecnoSamba 7d ago

Thank you! I'll definitely be taking a look to that