How to use npm modules in browser? is possible to use them even in local (PC)?

browserify is the correct direction, but it took me quite some effort to work out the actual solution. I have summarized a short blog for this, and here are some quick recap:

Say, you want to use emailjs-mime-parser and buffer npm libraries in your HTML.

  1. install everything required
npm install -g browserify
npm install emailjs-mime-parser
npm install buffer
  1. write a simple main.js as a wrapper:
var parse = require('emailjs-mime-parser').default
var Buffer = require('buffer').Buffer
global.window.parseEmail = parse
global.window.Buffer = Buffer
  1. compile everything using browserify
browserify main.js -o bundle.js
  1. now, you could use bundle.js inside the HTML file.
<html>
<head>
<script src="https://stackoverflow.com/questions/49562978/bundle.js"></script>
<script>
console.log(window.parseEmail);
console.log(window.Buffer);
</script>
<body>
</body>
</html>

Leave a Comment