Here’s a very simple “hello world” for npm modules in the browser. If there is a simpler or more straightforward, but usable way, that doesn’t require learning 20 different tools in depth, please let me know!
The Old Way
When I refer to the “old way” and the “new way,” I mean them in a bit of a hand-wavy way. I’m not referring to the “new-new way” — like ES6 — more just the “new way” meaning using npm modules.
Here’s a web page with a sample of the old way.
The New Way
The issue is that it’s a bit confusing to get started. And there are a lot of strong and conflicting opinions on the right or best way to do things.
But say you want to start using npm modules in the browser, where do you start?
You’ll need a few things to get started. Here’s what I’ve found so far as the easiest setup to get started.
You’ll need to install Node.js and npm. Download here
Check that worked by running
npm and making sure it actually prints something out.
Install browserify with
npm install -g browserify
Install watchify with
npm install -g watchify
Hello World for npm modules in the browser
Step 1: Make sure prerequisites are installed, or install them if they are not.
Step 2: Set up your directory with npm init.
Step 3: Install any npm modules you’d like to use. In this example I used two modules.
npm install --save arithmetic
npm install --save repeat-string
var arithmetic = require('arithmetic');
browserify newway.js -o bundle.js
If you use browserify like this, you’ll have to make a new bundle every time you make a change. To make it a bit easier, you can run this watchify command, which will create your new bundle every time you save your file.
watchify newway.js -o bundle.js
Step 6: Now you include a script tag with bundle.js
So it is a bit more steps and a few more tools — and much harder to get initially set up, but once you are familiar there is lots of good stuff there.
Here’s a web page with a sample of the new way.
Here is the full HTML file: https://github.com/jkeesh/hello-browser-npm/blob/master/newway.html
Here is the full JS file: https://github.com/jkeesh/hello-browser-npm/blob/master/newway.js
Here’s the code for the repo with these examples: https://github.com/jkeesh/hello-browser-npm
Here’s one more sample simple setup:
<h1>Simple Web Page</h1><script src=”simplebundle.js”></script>
var repeat = require(‘repeat-string’);console.log(repeat(‘hey’, 100));
$ npm install repeat-string
$ watchify main.js -o simplebundle.js
Hope this helps!