Skip to content
This repository has been archived by the owner on Jan 27, 2021. It is now read-only.

nikcorg/commonjs-and-amd

Repository files navigation

A miniscule study in sharing code between CommonJS and AMD environments

In my current project, I'm sharing a large portion of code between the server and the browser. Initially I used a customised UMDJS signature for this purpose. Eventually, it proved problematic when building a monolith; r.js understood absolutely nothing and all my modules were nameless. And let's admit it, it's not pretty.

At first, I tried finding a solution to make r.js understand UMDJS, but quite quickly gave up and decided I need to look elsewhere for a better solution.

That solution was writing everything as CommonJS. Which is nice.

How it's done

  • All application code is written in CommonJS format
  • Cajon is used during development
  • RequireJS (or possibly Almond if all your code is in the monolith) is used in the final build, where the CommonJS code is transformed into AMD-modules, using r.js with cjsTranslate: true
  • Components (means contrib libraries) are always built into a separate monolith, with a little help from bootstrap.js in the client-folder. They are built separately, because the cjsTranslate setting would mess up some libraries during the build

Application startup

  • Application startup is always done by loading the components monolith, which using bootstrap.js loads the application startup script
  • As a benefit the script-tag for "booting up" remains unchanged between dev and release

Demo

NB! Requires Grunt 0.4.

Fetch dependencies by commanding npm install. Run tests by commanding npm test.

Build by commanding npm run-script debug (dev version) or npm run-script build (release version).

Run the server by commanding npm start, then visit http://localhost:3000 (default port) in your browser.

Demo app

The codebase contains a simple - yet possibly the most convoluted ever - Todo MVC style app as an example, with a ridiculously large dependency graph. All for the sake of demonstrating something really, really simple.

About

Sharing code between a CommonJS and AMD environment

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published