Here's a solution that takes a completely different approach: packs all the modules into a JSON object and requires modules by reading and executing the contents of the file without additional requests.
https://github.com/STRd6/require/blob/master/main.coffee.md
STRd6 / require depends on the presence of a JSON package at run time. The require function is created for this package. The package contains all the files that your application may require. Additional HTTP requests are not executed because the package binds all the dependencies. It is so close that you can get Node.js style on the client.
The package structure is as follows:
entryPoint: "main" distribution: main: content: "alert(\"It worked!\")" ... dependencies: <name>: <a package>
Unlike Node, a package does not know its external name. It depends on the pacakge, including addiction, to name it. This provides complete encapsulation.
Given everything that sets up a function here that loads a file from a package:
loadModule = (pkg, path) -> unless (file = pkg.distribution[path]) throw "Could not find file at #{path} in #{pkg.name}" program = file.content dirname = path.split(fileSeparator)[0...-1].join(fileSeparator) module = path: dirname exports: {} context = require: generateRequireFn(pkg, module) global: global module: module exports: module.exports PACKAGE: pkg __filename: path __dirname: dirname args = Object.keys(context) values = args.map (name) -> context[name] Function(args..., program).apply(module, values) return module
This external context provides some variable that the modules have access to.
The A require function is exposed to modules, so they may need other modules.
Additional properties such as a reference to a global object and some metadata are also exposed.
Finally, we execute the program inside the module and the given context.
This answer will be most useful to those who want to have a synchronous Node.js require statement style in the browser and are not interested in remote script loading solutions.
Daniel X Moore Sep 30 '13 at 6:12 2013-09-30 06:12
source share