node.jscdnesbuildjsdelivr

Use npm modules in browser js


I had a script that ran well in the JS terminal, but I tried to transfer to the browser and it would not run. I have been trying to figure out how to use npm packages in browser, specifically pythonia, which is necessary for my program. I tried using browserify to bundle, which didn't work, but I learned that I should switch to esbuild, which gave me

✘ [ERROR] Could not resolve "http"

bundle.js:198:23:
  198 │     var http = require("http");

that error every time I tried to use a package (basically the packages used node js preinstalled modules like http, but require does not work in browser). I also needed to use "child_spawn" but got the same error because I had to use require. I tried using a cdn, specifically jsdeliver. I used this code:

    <script
type="module"
src="https://cdn.jsdelivr.net/npm/translate@2/index.min.js"
></script>
<script>
    const text = translate("Hello world", "es").then(() => {
        console.log(text);
    });
</script>

but I got the error "translate is not defined", which I think must mean I'm doing something wrong? Clearly there is some user error here, but I've been searching for days and I've gone in circles. What method would be best/what am I doing wrong to include npm modules in browser? I know this question has a lot to it, but I don't really know what path to go down here. Any help would be much appreciated. Thank you!


Solution

  • Turns out I was did not know what I was doing at all a few weeks ago. Learned about express and front end/back end servers and got that working. I found this: https://www.youtube.com/watch?v=5TxF9PQaq4U&t=961s very useful for those who want to do this as well.