The Node.js' require()
on the browser!
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()
?
npm:
npm install browserfs-module
bower:
bower install browserfs-module
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>
This is released under MIT License.