Skip to content

Instantly share code, notes, and snippets.

@robotlolita
Last active December 17, 2015 05:39
Show Gist options
  • Save robotlolita/5559727 to your computer and use it in GitHub Desktop.
Save robotlolita/5559727 to your computer and use it in GitHub Desktop.
A short introduction to CommonJS modules

So you want to use modules? Modules in CommonJS are just files. So if you want a module, the first thing you should create is yourAwesomeModule.js

You'll need Node.js and, if you want to support browsers, you'll need Browserify

// Good, you have an `yourAwesomeModule` module now
// Let's make some useful things here:
function add(a, b) { return a + b }
// Everything inside your module is private by default
// if you want the outside world to know about what you've
// defined, you need to export it:
exports.add = add
// So you got another module that wants to use `add`.
// Well, no biggie, just import the module!
var awesome = require('./yourAwesomeModule')
awesome.add(1, 2) // => 3
// Whoa! Awesome!
// So, CommonJS modules have first-class modules. This means that
// `awesome` is just a plain JavaScript object. It can be, in fact,
// anything you want, even functions!
var sayOk = function(){
console.log('Ok!')
}
// To export anything, you assign it to the `module.exports`:
module.exports = sayOk
// Again, to use it, you just `require` it away:
var sayOk = require('./sayOk')
// But now `sayOk` is the function you've exported:
sayOk() // => 'Ok!'
# Oh, and let's not forget, we need to install other libraries too.
# NPM makes it easier by giving you a `npm install <somelibrary>`.
#
# It stores all your libraries in a `node_modules` folder, and solves
# all the dependency problems for you.
#
# Let's grab a module for string interpolation:
mkdir node_modules
npm install spice
// And you just require it as normal, but without a `relative` path:
var spice = require('spice')
// Usage is the same, you just use whatever the module gives you:
spice('Hello, {:world}', { world: 'you!' }) // => 'Hello, you!'

That's all, folks!

If you're running in node:

$ node yourFile

Is all you need. If you're running in the browser, you just:

$ browserify yourFile.js > browserPackage.js

And then you include your awesome browser package in your page:

<!-- this will have everything you need already! -->
<script src="browserPackage.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment