Modular JavaScript.



Modular JavaScript.

0 0


jsmeetup

my slides

On Github JacobJWBurden / jsmeetup

Modular JavaScript.

Jacob Burden

@jekrb

I'm fairly new.

But highly opinionated.

As a frontend developer I want to do these things...

  • Write really nice looking code.
  • Send the user a wall of text.

Easiest way to write nice looking code.

Write less code.

Decouple your code.

Disclaimer

  • I'm not against writing the better solution if it needs more code.
  • This is not relevant to every web app.
  • This more relevant to a native web app or large javascript library.

Our current options are problematic.

Extra http request.

Single giant.js

Making extra request.

  • Keeps files seperated.
  • Easy to work with.
  • Potentially slows down app.

Working in hugefile.js

  • Single http request.
  • Looking at lots of code.
  • You'll start to resent your work.

Solution?

Browserify!

Works really nicely with NPM.

Lets you cleanly use dependencies.

Underscore

Terminal

npm install underscore --save

isNull.js

var _ = require('underscore')

console.log(_.isNull(null))
// true

This file is larger than it seems.

isNull.js

module.exports = function isNull(obj) {
	return obj === null
}

isNumber.js

var toString = Object.prototype.toString


module.exports = function isNumber(obj) {
    return toString.call(obj) === '[object Number]'
}

entry.js

var isNull = require('./isNull.js')
var isNumber = require('./isNumber.js')

console.log(isNull(null))
//true
console.log(isNumber(1337))
//true

bundle up

browserify entry.js > app.bundle.js

Work in seperate modules.

Send the user app.bundle.js

Send app.bundle.js to the user.

In your terminal

beefy entry.js
beefy (v2.1.1) is listening on http://127.0.0.1:9966

Check your bundled code in the browser.

Faster production with Moonboots.

var Hapi = require('hapi')
var server = new Hapi.Server('localhost', config.http.port)

var moonboots = require('moonboots_hapi')
var moonbootsConfig = require('./moonbootsConfig')

server.pack.register({plugin: moonboots, 
                     options: moonbootsConfig}, 

    function (err) {
	    if (err) throw err;
	    server.start(function (err) {
	        if (err) throw err;
	    });
});

moonbootsConfig.js

module.exports = {
    moonboots: {
        main: __dirname + '/client/app.bundle.js'

Extremly portable

Save dependencies to package.json

In summary.

  • Seperate development from production.
  • Write small, maintainable modules.

Thank you!

Links