Skip to content

Narazaka/browserfs-module.js

Repository files navigation

npm npm license npm download total npm download by month Bower Bower

Dependency Status devDependency Status Travis Build Status AppVeyor Build Status Code Climate

The Node.js' require() on the browser!

Motivation

Browsers do not support the require() API on Node.js, since they do not have File Systems. (And we are playing with magic require() processors, like webpack).

But we can make fake File System on browsers by using BrowserFS.

Now, why not use the real require()?

Install

npm:

npm install browserfs-module

bower:

bower install browserfs-module

Usage

node ./foo.js corresponds to Module._load ('./foo.js').

You can use require() in ./foo.js just like on Node.js.

<script src="browserfs.js"></script>
<script src="browserfs-module.js"></script>
<script>
var fsBase = new BrowserFS.FileSystem.InMemory();
BrowserFS.initialize(fsBase);

var fs = BrowserFS.BFSRequire('fs');
fs.writeFileSync('/main.js', 'module.exports = require("sub");');
fs.mkdirSync('/node_modules');
fs.writeFileSync('/node_modules/sub.js' ,'module.exports = "sub required!";');

Module = browserfsModule.Module;
var main = Module._load("/main");
console.log(main); // "sub required!"
</script>

License

This is released under MIT License.