I'm learning how to use Flux and I encountered the following line in the documentation: "We can use Node's EventEmitter to get started with a store."
I understand that you can use things like Browserify to do the bundling and minifying, grabbing all the dependencies that Node code has to make the bundled browser-compatible JS file. But what's bugging me right now is how you know what you can do this with. How do we know what Node code we're allowed to use in the browser?
So, first of all let's consider that when in node you have
fs
, path
, util
, etc.Then you have the packager / module bundlers
the transpilers i.e. source to source compilers that typicall will handle syntax tranforms like
Babel.js that shims modern JavaScript to legacy engines
and the techniques
Because you need to do polyfills if you want to transform not only syntax but even globals (like the Promise), so you combine transpiler to polyfill having like babel-polyfill
Finally we have different kind of modules design patterns (modules format) to be handled for the bundling process:
and formats that are not in those ones that must be bundled/shimmed - where possible - through custom loaders.
That said, native modules will not run in the browser: you cannot bundle a native module through Webpack. Ordinary modules will, but not all. This is due to several reasons. There are some specific methods that cannot be "browserified" or "webpacked". Let's take as example fs
. Can you put this built-in module in the browser? There are some abstraction for that called brfs, that are transforms for built-in node apis fs.readFileSync()
and fs.readFile()
, so you will do
$ browserify -t brfs example/main.js > bundle.js
to get
var fs = require('fs');
var html = fs.readFileSync(__dirname + '/robot.html', 'utf8');
console.log(html);
This will not work for every non built-in modules, in the npm
modules jungle, so WebPack has a module.noParse
option to exclude Addons modules, non supported modules, etc. - see here about that.
So you have to look at the list of the transforms that means you can apply this transform to browserify
to obtain like the fs
transform mentioned above.
So that said, how do you know that a certain module will run in the browser? When you design your web application and Node backend you have to do opportunistic design choises to design shared modules/library that will run in both the environment, so being shimmed/packed at some point, like object models, application logic, etc., other modules that will deal with the File System I/O or will use native addons, so that will work in the server only, packing through wrappers it's possibile, but the behavior will look differently, as we have seen in the fs
example above, and web specific modules, so it's a design matter.
A note can be added about networking modules i.e. node http
, https
that thanks to library abstractions like node request will run everywhere or using specific transforms like http-browserify.