Permalink
Switch branches/tags
Nothing to show
Find file Copy path
6d0d1d3 Jun 28, 2017
1 contributor

Users who have contributed to this file

96 lines (68 sloc) 2.47 KB
<h1>JavaScript the <i>New</i> Way</h1>
<p>The new way of writing JavaScript is to install modules from npm, write your JavaScript with those modules, and bundle those up into a new JavaScript files that you include with a script tag. You'll need a few extra tools.</p>
<h3>Prerequisites</h3>
<p>You'll need to install Node.js and npm. <a href="https://nodejs.org/en/download/">Download here</a>
<p>Check that worked by running <code>npm</code> and making sure it actually prints something out.</p>
<p>Install <a href="http://browserify.org/">browserify</a> with <code>npm install -g browserify</code></p>
<p>Install <a href="https://github.com/substack/watchify">watchify</a> with <code>npm install -g watchify</code></p>
<h3>The New Way</h3>
<p>
Step 1: Make sure prerequisites are installed, or install them if they are not.
</p>
<p>
Step 2: Set up your directory with npm init.
<br>
<pre>
npm init
</pre>
</p>
<p>
Step 3: Install any npm modules you'd like to use. In this example I used two modules.
<br>
<pre>
npm install --save arithmetic
npm install --save repeat-string
</pre>
</p>
<p>
Step 4: Write your JavaScript. You can include these files by "requiring" them at the top.
<br>
<pre>
var arithmetic = require('arithmetic');
arithmetic.add(2, 4);
</pre>
</p>
<p>
Step 5: Bundle your JavaScript. You can do this with a tool like browserify, which takes your JavaScript, and the dependency modules, and puts them into one file.
<br>
<pre>
browserify newway.js -o bundle.js
</pre>
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.
<pre>
watchify newway.js -o bundle.js
</pre>
</p>
<p>
Step 6: Now you include a script tag with bundle.js
<br>
<pre>
&lt;script src="bundle.js"&gt;&lt;/script&gt;
</pre>
</p>
<h3>What This Page Looks Like</h3>
<p>Include the script tag generated by the build tool.
<pre>
&lt;!-- Include a bundle which was generated. --&gt;
&lt;script src="bundle.js"&gt;&lt;/script&gt;
</pre>
<h3>
<a href="oldway.html">
See the Old Way
</a>
</h3>
<a href="https://github.com/jkeesh/hello-browser-npm/blob/master/newway.html">See the Code for this Page</a>
<h3>Samples</h3>
<div id="fillin"></div>
<!-- Include a bundle which was generated -->
<script src="bundle.js"></script>