• Stars
    star
    113
  • Rank 310,115 (Top 7 %)
  • Language
  • License
    MIT License
  • Created over 9 years ago
  • Updated about 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

intro to modular programming for frontend JavaScript
jam3-lesson ยป module-basics

Modules for Frontend JavaScript

This is a brief intro to modules for modern frontend development. It will introduce Node, npm, and browserify. After this guide, you should be equipped to create your first npm module.

# sections

# concepts

modules

In this context, "modular" JavaScript refers to a piece of code that operates independently of the applications which surround it. A "module" โ€” sometimes just a single function โ€” is written, tested, and published in isolation, and often a good candidate for re-use across projects.

The goal is to build small programs that do one thing, do it well, and compose easily with other programs (the Unix Philosophy).

Some examples:

  • xhr - an XMLHttpRequest abstraction
  • seed-random - deterministic seeded pseudo-random number generator
  • object-assign - a polyfill for Object.assign
  • gl-matrix - vector & matrix math, ideal for 2D and 3D applications

There are a few different formats for authoring and publishing modules, such as ES6, AMD, and CommonJS. This article will focus on CommonJS (used by Node).

dependencies

Each module can have a formalized set of "dependencies" โ€” that is, other modules it needs to work. Dependencies can help reduce repetition and share code across many modules. The tooling will figure out how to download and consume these dependencies under the hood. In turn, those modules can have their own dependencies, and so forth.

For example, the earlier mentioned xhr module has a dependency graph that looks a little like this, where each is a separate module:

xhr
โ”œโ”€โ”€ once            # run a function once
โ””โ”€โ”ฌ parse-headers   # parse http headers
  โ”œโ”€โ”ฌ for-each      # forEach() but works on objects
  โ”‚ โ””โ”€โ”€ is-function # test if value is a function
  โ””โ”€โ”€ trim          # string trim utility

semantic versioning

As you re-use the same piece of code across many projects, bugs and limitations with the original module begin to emerge. The code evolves and changes to better suit the new use cases, and sometimes it leads to a breaking API (i.e. renaming a public function).

This is where semantic versioning can help us. A version is broken down into major.minor.patch numbers, separated by decimals:

  • major denotes a breaking change in the documented API (e.g. renaming or removing a public function)
  • minor denotes a new feature was added in a backwards-compatible manner
  • patch denotes a bug was fixed in a backwards-compatible manner

Modules typically start at version 1.0.0. When you bump one number, you must reset the numbers to the right of it back to zero. For example:

  • making a bug fix to 1.0.0 -> 1.0.1 (patch change)
  • adding a new feature to 1.0.1 -> 1.1.0 (minor change)
  • changing a method name in 1.1.0 -> 2.0.0 (major change)

When we install a module, we are also opting in for all of its patch and minor versions within the same major version. This way, we get the latest bug fixes, but our code won't break if a dependency decides to change its API. Later, we will explore how to configure this option and "lock down" our application's dependencies.

# tools

To bring these concepts together, we will primarily be using these three open source tools:

  • node - a platform built on Chrome's JavaScript engine (V8)
  • npm - a package manager for JavaScript modules
  • browserify - a tool which bundles Node modules into something browsers understand

node

The first step is to install Node; you can download it from nodejs.org. Among other things, it provides a command-line interface for executing JavaScript source.

Once it's installed, open Terminal and try entering the following:

node -e "console.log(10 * 2)"

If all goes well, the above should print 20 (where -e is for eval).

img

(if that doesn't work, you may need to re-install Node via homebrew)

Now you can run JavaScript files with node path/to/file.js, or start a REPL (read-eval-print-loop) with node.

repl

Tip: You can quit the REPL with Control + C

This is a great way to quickly test some generic JavaScript code without booting up a browser.

Since we are running in Node, we also have access to a standard library for things like File I/O and backend programming.

For example, let's use Node's built-in url module to parse the URL string "http://google.com/"

url

Here we are requiring a built-in module called url. Require statements are part of Node, and look like this:

const url = require('url');

//... use url.parse()

npm

The next tool we need is npm. If you installed Node through the site above, you should already have npm set up! We can test that with the following command:

npm -v

(if that doesn't work, you may need to re-install Node and npm via homebrew)

Node bundles with a very outdated version of npm, so it's best to update it to get the latest features and security fixes:

sudo npm install npm -g

Let's try installing our first module: http-server. This helps us get a static site up quickly without a bloated GUI tool like MAMP.

npm install http-server -g

Note: The -g flag tells npm to install the module globally.

If you get an EACCESS error, you need to fix your permissions:

Fixing npm permissions
More Details (Stackoverflow)

Once it installs, you should be able to run it like so:

http-server -o

This should open the browser on http://localhost:8080/.

http

Awesome! You just used your first module. This one is a command line tool, which is why we installed it globally with -g. When we install code dependencies (like xhr), we typically install them locally.

browserify

To bridge the gap between Node/npm and the browser, we will use a tool called browserify. It transforms Node require() statements into something the browser can execute, and bundles different modules into a single script. This allows us to use built-in Node modules like url, as well as modules on npm.

Close the earlier process (Control + C), and then stub out a folder where we can write some demos. In Linux/OSX shell:

#go to your projects folder
cd ~/Documents

#make a new test folder
mkdir test-browserify

#move into that folder
cd test-browserify

#make an empty JavaScript file
touch index.js

On Windows, it might look like this:

cd `%HOMEPATH%/Documents`
mkdir test-browserify
cd test-browserify
type NUL > index.js

basics

Open the empty index.js file we created above in your favourite editor (like SublimeText). Add the following and save it:

const url = require('url');

const parts = url.parse(window.location.href);
console.log(parts);

The above code won't work yet in the browser, since it uses Node APIs. For our demo, we will use a tool called budล to transform our Node require() statements into something the browser can understand. Install the tool like so:

npm install budo -g

Now start budo on our source file, like so:

budo index.js --live

This will start a browserify development server on port 9966. When index.js is requested, it will get "browserified" and transformed into something the browser can run. It will also serve you a basic index.html if you didn't write one, with a <script> tag for our index.js. The --live flag will ensure the browser reloads when your JavaScript code changes.

Now, when you open up http://localhost:9966 in your browser and check the DevTools console, you'll see the Node code working as expected!

console

local modules

The last thing we'll cover here is using a third-party module in our code. Let's install a SVG helper module, svg-create-element.

npm install svg-create-element

Note: We aren't installing this globally with -g. In later lessons we'll formalize this as a dependency with a package.json.

This will add the module into a folder called node_modules in our current directory. Now let's replace our index.js code with the following:

//require the SVG helper module
const create = require('svg-create-element');

//create a SVG element
const svg = create('svg');

//add a polyline
const line = create('polyline', {
    stroke: 'orange',
    strokeWidth: 4,
    fill: 'transparent',
    points: [ 
      [ 50, 100 ], 
      [ 100, 50 ], 
      [ 150, 100 ], 
      [ 200, 50 ]
    ].join(' ')
});
svg.appendChild(line);

//add contnet to DOM
document.body.appendChild(svg);

And now, when we refresh our http://localhost:9966/ page, we will see a sweet 2D line!

svg

# other tools

In this guide, we use Browserify and require() statements. This is perhaps one of the easiest and most "bare bones" way of using Node.js and npm modules within your frontend code. However, there are many other tools like Browserify that include more features, including supporting ES6 import and export, such as:

  • Parcel - a zero-config bundler and development server
  • Webpack - a powerful bundler for modern JavaScript applications

# further reading

This article only covers the basics of Node, npm, and getting modules working in the browser. A future lesson will go into more depth on the require() statement, and how we can build and publish our own modules. Until then, check out some of these links:

More Repositories

1

math-as-code

a cheat-sheet for mathematical notation in code form
14,818
star
2

devtool

[OBSOLETE] runs Node.js programs through Chromium DevTools
JavaScript
3,774
star
3

nice-color-palettes

nice colour palettes as JSON
JavaScript
848
star
4

three-bmfont-text

renders BMFont files in ThreeJS with word-wrapping
JavaScript
764
star
5

glsl-fast-gaussian-blur

optimized single-pass blur shaders for GLSL
JavaScript
659
star
6

hihat

๐ŸŽฉ local Node/Browser development with Chrome DevTools
JavaScript
447
star
7

jam3-lesson-webgl-shader-threejs

Using custom vertex and fragment shaders in ThreeJS
JavaScript
361
star
8

jam3-lesson-webgl-shader-intro

A brief introduction to fragment shaders.
307
star
9

web-audio-player

a cross-browser WebAudio player
JavaScript
244
star
10

360-image-viewer

A standalone panorama viewer with WebGL
JavaScript
243
star
11

ae-to-json

will export an After Effects project as a JSON object
JavaScript
225
star
12

msdf-bmfont

Generate BMFont texture and spec using msdfgen
JavaScript
161
star
13

jam3-lesson

142
star
14

audiobuffer-to-wav

convert an AudioBuffer to .wav format
JavaScript
132
star
15

Invisible-Highway

Invisible Highway is an experiment in controlling physical things in the real world by drawing in AR. Simply make a pathway along the floor on your phone and the robot car will follow that path on the actual floor in your room. A custom highway with scenery is generated along the path to make the robots a little more scenic on your phone screen.
C#
130
star
16

awesome-streetview

beautiful [lat, lng] Google Street View locations
JavaScript
129
star
17

ffmpeg-gif

shell script to convert video to high quality GIF with ffmpeg
JavaScript
124
star
18

orbit-controls

generic controls for orbiting a target in 3D
JavaScript
110
star
19

nextjs-boilerplate

Jam3 NextJS Generator for SPA, SSG, SSR and JAMStack applications
TypeScript
107
star
20

svg-to-image

convert SVG text to a Image that can be drawn in canvas
JavaScript
103
star
21

voice-activity-detection

Voice activity detection
JavaScript
102
star
22

extract-streetview

extract street view spherical images and depth information
JavaScript
101
star
23

react-f1

F1 ui animation library for React
JavaScript
90
star
24

webgl-react-boilerplate

WebGL React App โšก๏ธ
JavaScript
87
star
25

opentype-layout

word wraps and lays out Opentype.js glyphs
JavaScript
86
star
26

chaikin-smooth

Chaikin's smoothing algorithm for 2D polylines
JavaScript
82
star
27

f1

A stateful ui library
JavaScript
78
star
28

touch-scroll-physics

scroll physics for a scroll pane with edge bounce and velocity
JavaScript
77
star
29

preloader

A library for loading common web assets
JavaScript
69
star
30

three-png-stream

streams ThreeJS render target pixel data
JavaScript
66
star
31

layout-bmfont-text

word-wraps and lays out text glyphs
JavaScript
59
star
32

react-background-video-player

React background video component with simple player API
JavaScript
58
star
33

ios-safe-audio-context

create a WebAudio context that works in iOS and everywhere else
JavaScript
57
star
34

perspective-camera

a high-level 3D perspective camera
JavaScript
53
star
35

glsl-hsl2rgb

HSL to RGB color conversion in GLSL
GLSL
50
star
36

touches

simplified touch/mouse events for flick and swipe
JavaScript
45
star
37

ios-video-test

a test of inline iOS video playback
JavaScript
45
star
38

three-path-geometry

thick 2D lines for ThreeJS
JavaScript
42
star
39

jam3-lesson-canvas2d

open source code for a Canvas2D workshop at Jam3
JavaScript
41
star
40

maya-json-export

a generic Maya to JSON exporter for triangle meshes
JavaScript
41
star
41

glsl-100-to-300

transpiles GLSL tokens from v100 to v300 es
JavaScript
39
star
42

xhr-request

tiny http client for Node and the browser
JavaScript
39
star
43

webvr-gearvr-test

a simple test of WebVR running natively in GearVR
JavaScript
38
star
44

generator-jam3

This is a generator for Jam3 projects
JavaScript
37
star
45

google-maps-api

Get up and running with the google maps API quickly
JavaScript
34
star
46

babel-plugin-static-fs

statically transforms Node fs for the browser
JavaScript
33
star
47

ae-to-json-cli

This is a command line application to export After Effects files as JSON
JavaScript
33
star
48

tech-we-use

A list of technologies: modules, libraries, and tools we use
32
star
49

load-bmfont

loads a BMFont file in Node and the browser
JavaScript
31
star
50

jam3-testing-tools

a brief intro to testing tools
30
star
51

gl-pixel-stream

streaming gl.readPixels from an FBO
JavaScript
30
star
52

jam3-lesson-module-creation

introduction to creating a new npm module
29
star
53

threejs-generate-gif

Generate an animated GIF (using the GPU) from a threejs scene
JavaScript
29
star
54

tap-dev-tool

prettifies TAP in the browser's console
JavaScript
29
star
55

text-split

Utility for splitting text into chunks based on regex.
JavaScript
27
star
56

three-simplicial-complex

render simplicial complexes with ThreeJS
JavaScript
27
star
57

three-buffer-vertex-data

an easy way to set vertex data on a BufferGeometry
JavaScript
27
star
58

parse-dds

parses the headers of a DDS texture file
JavaScript
26
star
59

threejs-post-process-example

a tutorial on ThreeJS post processing
JavaScript
24
star
60

add-px-to-style

Will add px to the end of style values which are Numbers
JavaScript
24
star
61

google-panorama-by-location

gets a Google StreetView by [ lat, lng ]
JavaScript
24
star
62

mesh-heightmap-contours

Given a heightmap, generate a "contoured" terrain mesh
JavaScript
24
star
63

detect-import-require

list require and import paths from a JavaScript source
JavaScript
24
star
64

says

cross-platform 'say' command using Electron
JavaScript
23
star
65

background-cover

Simulate 'background-size: cover' on HTMLVideoElement and HTMLImageElement
JavaScript
23
star
66

analyser-frequency-average

gets an average intensity between two frequency ranges
JavaScript
23
star
67

webgl-components

Modular components and utilities used for WebGL based projects ๐Ÿ’…
TypeScript
22
star
68

video-element

A simple HTML5/YouTube Video Element with a unified interface
JavaScript
22
star
69

three-fluid-demo

ThreeJS fluid simulation demo
GLSL
22
star
70

delaunify

randomly delaunay-triangulates an image
JavaScript
22
star
71

camera-unproject

unproject 2D point to 3D coordinate
JavaScript
21
star
72

heightmap-contours

Generate a series of 2D contour meshes over a heightmap
JavaScript
21
star
73

glsl-blend-overlay

blend mode 'overlay' for GLSL
C
20
star
74

ray-3d

a high-level ray picking helper for 3D intersection
JavaScript
19
star
75

scroll-manager

A handler for scrolling inside elements with different eases
JavaScript
19
star
76

touch-pinch

minimal two-finger pinch gesture detection
JavaScript
19
star
77

three-orbit-viewer

quick harness for viewing a mesh with orbit viewer
JavaScript
18
star
78

css-transform-to-mat4

Will take a string which is a css transform value (2d or 3d) and return a mat4 or 3d transformation matrix from the string.
JavaScript
17
star
79

gl-shader-output

test a shader's gl_FragColor output on a 1x1 canvas
JavaScript
17
star
80

gh-api-stream

streams JSON content from a GitHub API
JavaScript
17
star
81

uploadr

CLI tool which uploads a folder via SFTP
JavaScript
17
star
82

camera-spin

Mouse/touch-draggable first-person camera
JavaScript
17
star
83

exif-orientation-image

Properly displays an image via canvas based on the exif orientation data.
JavaScript
16
star
84

jam3-lessons-react

Quick and brief reference for React development
15
star
85

preview-dds

preview and save DDS textures from the command line
JavaScript
15
star
86

meetup-creative-coding-webgl

A WebGL experiment created for Jam3's Creative Coding Meetup on October 23rd 2019.
JavaScript
14
star
87

detect-audio-autoplay

detects whether the browser can auto-play audio
JavaScript
14
star
88

ae-threejs-multichannel-sdf

A signed distance field Effect plugin for Adobe After Effects
C
13
star
89

slot-machine-button

๐ŸŽฐ React Slot Machine Button
JavaScript
13
star
90

google-maps-image-api-url

This module will return a string which is a url to load an image from the Google Maps Image API
JavaScript
13
star
91

webgl-to-canvas2d

Convert a webgl context or webgl canvas into a 2d canvas
JavaScript
13
star
92

f1-dom

Create f1 ui with the dom
JavaScript
12
star
93

nyg

Not another yeoman generator, a simplified project generator based around prompts and events.
JavaScript
12
star
94

camera-picking-ray

creates a picking ray for a 2D/3D camera
JavaScript
11
star
95

scroll-bar-width

Detect browser scrollbar size
JavaScript
11
star
96

nyg-jam3

Second generation of the Jam3 Generator, many new features and breaking change features
JavaScript
11
star
97

awwwards-stream

scrape Awwwards data
JavaScript
11
star
98

adviser

Jam3 quality advisor. Integrates checking for best practices at Jam3
JavaScript
11
star
99

google-assistant-21-days-of-gratitude

JavaScript
11
star
100

google-assistant-greeting-cards

JavaScript
10
star