Skip to content

oyvindeh/simpler-browser-require

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

NPM Version Build Status

simpler-browser-require

simpler-browser-require is an even simpler, node.js-like require() for the browser. It is not an asynchronous script loader, and it only works with absolute paths (hence simpler).

Usage

Wrapping each module in a require.register call:

require.register('my/module/id', function (require, exports, module) {
	// module code here
});

...allows the require function to return the module's public contents:

var lib = require('my/module/id');

...exposed by decorating the exports object:

var myModuleVar = 'my module';

exports.myModuleMethod = function() {
  return myModuleVar;
};

...or overwritting the exports object completely:

function MyModule() {
  this.myVar = 'my instance var';
};

MyModule.prototype.myMethod = function() {
  return this.myVar;
};

module.exports = MyModule;

Lazy modules

Passing a string (instead of a function) to require.register enables lazy evaluation of module contents. The module will be parsed and evaluated only when require'd:

require.register('my/module/id', "function (require, exports, module) {\n  exports.foo = 'foo';\n}");

The raw source is retrievable via require.raw(path):

localStorage.setItem('my/module/id', window.require.raw('my/module/id'));
window.require.register('my/module/id', localStorage.getItem('my/module/id'));
// ...
var myModule = require('my/module/id');
console.log(myModule.foo); //=> 'foo'

About

An even simpler, node.js-like require() for the browser.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%